3

我正在尝试将 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

但我收到以下错误:{“错误”:“未授权”}。

这就是我的 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<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(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 开头的卷曲线和以“--data-binary”开头的卷曲线?-d 的 java 等效项是什么?

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

任何提示表示赞赏。谢谢

4

1 回答 1

4

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

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

实施curl -d将需要做一些事情,比如将 a 传递StringEntityhttpPost.setEntity()使用您要发送的值。

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

于 2012-02-02T00:01:52.697 回答