Apache Httpclient 4.5.6中的多部分发布请求不起作用

时间:2019-05-30 16:03:23

标签: java api apache-httpclient-4.x

我正在尝试将文件上传到服务器。使用Postman工具时,请求工作正常。

在邮递员中,我有:

POST :https://transport-stg.transperfect.com/api/files/upload?filename=test.png&targetFolderId=2ff5ea6a-8187-4622-ab58-c7511c445ae7

在标题中,我有:

Content-Type = multipart/form-data
Authorixation = Bearer access_code

我体内有:

  file = test.txt (this is file to be uploaded,able to select file location in Postman)

“以上内容”可以在邮递员工具中正常工作。

现在,我使用HttpClient 4.5.6作为Java编写了以下代码

try {
 CloseableHttpClient httpClient = HttpClients.createDefault();
File file = new File("C:\\Users\\lKadariya\\Desktop\\test.txt");
  String authorizationValue = "Bearer "+accessToken;
HttpEntity data = MultipartEntityBuilder.create()
        .setMode(HttpMultipartMode.BROWSER_COMPATIBLE)
        .addBinaryBody("srcUploader",file,ContentType.DEFAULT_BINARY,file.getName())
        .build();
  HttpUriRequest request = RequestBuilder.post("https://transport-stg.transperfect.com/api/files/upload")
          .addHeader("Content-Type","multipart/form-data")
          .addHeader("Authorization",authorizationValue)
          .addHeader("Accept","application/json")
          .addParameter("filename","test.txt")
          .addParameter("targetFolderId","2ff5ea6a-8187-4622-ab58-c7511c445ae7")
          .setEntity(data)
          .build();
   ResponseHandler<String> responseHandler = response -> {
    int status = response.getStatusLine().getStatusCode();
    if (status >= 200 && status < 300) {
      HttpEntity entity = response.getEntity();
      return entity != null ? EntityUtils.toString(entity) : null;
    } else {
      throw new ClientProtocolException("Unexpected response status: " + status);
    }
  };
  String responseBody = httpClient.execute(request, responseHandler);

我无法上传文件。 错误:无法从服务器上传文件。 邮递员给出了预期的答复。

上面的Httpclient代码有什么问题吗?

OKhttp库也可以正常运行

OkHttpClient client = new OkHttpClient();
    RequestBody requestBody = new MultipartBody.Builder()
            .setType(MultipartBody.FORM)
//            .addPart(
//                    Headers.of("Content-Disposition", "form-data; name=\"title\""),
//                    RequestBody.create(null, "test"))
            .addPart(
                    Headers.of("Content-Disposition", "form-data; name=\"test\""),
                    RequestBody.create(MEDIA_TYPE_TXT, new File("test.txt")))
//            .addFormDataPart("file","file.txt",
//                    RequestBody.create(MediaType.parse("application/octet-stream"),new File("test.txt"))
//                    )
            .build();

    Request request = new Request.Builder()
            .header("Authorization", "Bearer " + accessToken)
            .url("https://transport-stg.transperfect.com/api/files/upload?filename=basic.txt&targetFolderId=2ff5ea6a-8187-4622-ab58-c7511c445ae7")
            .post(requestBody)
            .header("Content-Type","multipart/form-data")
            .build();
try {
  Response response = client.newCall(request).execute();

HttpClient代码可能出什么问题了?

1 个答案:

答案 0 :(得分:0)

HttpUriRequest request = RequestBuilder.post("https://transport-stg.transperfect.com/api/files/upload")
      .addHeader("Content-Type","multipart/form-data")

代码中的Content-Type值无效,因为它不包含boundary参数。

您不应在请求级别插入Content-Type头,而应让HttpClient根据包含的请求实体的属性自动生成它。