如何将curl -X post翻译成java

我试图将curl命令转换为Java(使用Apache HttpClient 4.x):

export APPLICATION_ID=SOME_ID export REST_API_KEY=SOME_KEY curl -i -X POST \ -H "X-Parse-Application-Id: ${APPLICATION_ID}" \ -H "X-Parse-REST-API-Key: ${REST_API_KEY}" \ -H "Content-Type: image/png" \ --data-binary @/Users/thomas/Desktop/greep-small.png \ https://api.parse.com/1/files/greep.png 

但是我收到以下错误:{“error”:“unauthorized”}。

这就是我的java代码:

 DefaultHttpClient httpclient = new DefaultHttpClient(); HttpHost targetHost = new HttpHost("localhost", 80, "http"); httpclient.getCredentialsProvider().setCredentials( new AuthScope(targetHost.getHostName(), targetHost.getPort()), new UsernamePasswordCredentials("username", "password")); HttpPost httpPost = new HttpPost("https://api.parse.com/1/files/greep.png"); System.out.println("executing request:\n" + httpPost.getRequestLine()); List nameValuePairs = new ArrayList(2); nameValuePairs.add(new BasicNameValuePair("Example-Application-Id", "SOME_ID")); nameValuePairs.add(new BasicNameValuePair("Example-REST-API-Key", "SOME_KEY")); nameValuePairs.add(new BasicNameValuePair("Content-Type", "image/png")); httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs)); HttpResponse response = httpclient.execute(httpPost); HttpEntity responseEntity = response.getEntity(); System.out.println("----------------------------------------"); System.out.println(response.getStatusLine()); if (responseEntity != null) { System.out.println("Response content length: " + responseEntity.getContentLength()); } System.out.println(EntityUtils.toString(responseEntity)); httpclient.getConnectionManager().shutdown(); 

如何翻译以-H开头的curl线和以“–data-binary”开头的curl线? 什么是等价的-d?

  -d '{ "name":"Andrew", "picture": { "name": "greep.png", "__type": "File" } }' \ 

任何提示都表示赞赏。 谢谢

标头不匹配。 curl命令使用X-Parse-Application-IdX-Parse-REST-API-Key而Java代码使用Example-Application-IdExample-REST-API-Key 。 我想你会希望那些匹配。 另外,您将它们设置为请求的POST主体而不是HTTP标头。 您需要在setHeader上使用其中一个setHeader方法。 我还建议不要以这种方式明确设置Content-Type 。 内容类型通常作为发布的HttpEntity一部分提供。

要在Java中使用HttpClient发布图像内容,您需要使用引用文件路径的/Users/thomas/Desktop/greep-small.png (在您的示例中为/Users/thomas/Desktop/greep-small.png )。 现在,您正在将标头值作为名称值对发布,如前所述。

实现curl -d需要做一些事情,比如使用你想发送的值将httpPost.setEntity()传递给httpPost.setEntity()

最后,Java代码使用了一些我在curl命令中根本看不到的凭据。