【发布时间】:2014-11-27 15:44:57
【问题描述】:
例如,我需要翻译一下:
curl -X PUT -u ident:pass -H "Content-Type : application/json" --data-binary @G:\jonJob.json "http://localhost:8080/jobs/"
(这行得通)。
在带有 httpClient 的 java 中。我尝试了很多东西,但没有任何效果.. 有人可以帮帮我吗?
我尝试过的:
public class PostFile {
@SuppressWarnings("deprecation")
public static void main(String[] args) throws Exception {
CredentialsProvider provider = new BasicCredentialsProvider();
UsernamePasswordCredentials credentials = new UsernamePasswordCredentials("ident", "pass");
provider.setCredentials(AuthScope.ANY, credentials);
HttpClient httpClient = HttpClientBuilder.create().setDefaultCredentialsProvider(provider).build();
HttpPut httppost = new HttpPut("http://localhost:8080/jobs/");
File file = new File("G:/jsonJob.json");
HttpEntity httpEntity = MultipartEntityBuilder.create().addBinaryBody("file", file, ContentType.create("application/json"), file.getName()).build();
httppost.setEntity(httpEntity);
System.out.println("executing request " + httppost.getRequestLine());
HttpResponse response = httpClient.execute(httppost);
HttpEntity resEntity = response.getEntity();
System.out.println(response.getStatusLine());
if (resEntity != null) {
System.out.println(EntityUtils.toString(resEntity));
}
if (resEntity != null) {
resEntity.consumeContent();
}
httpClient.getConnectionManager().shutdown();
}
}
结果:“HTTP/1.1 415 Not supported type”(不支持的媒体类型)
【问题讨论】:
-
嗨,谢谢你的回答,我已经用更多信息编辑了我的帖子(抱歉我的英语不好)
-
不要使用 MME 'multipart' 将 curl @ 替换为帖子。使用 ByteArrayEntity。并获取标头集: request.addHeader("Content-Type", "application/json") ;