简体   繁体   中英

Multipart Post request in Apache Httpclient 4.5.6 not working

I am trying to upload a file to the server. The request is working fine while using Postman tool.

In Postman I have :

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

In Header I have :

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

In Body I have:

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

This Above is working as expected in postman tool.

Now I wrote a below code in Java using HttpClient 4.5.6 as

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);

And i am not able to upload the file. ERROr: Unable to upload file from server. the postman is giving the expected respone.

What could go wrong with this above Httpclient code?

The OKhttp library is also working fine as

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();

What could go wrong in the HttpClient code?

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

The Content-Type value in your code is invalid as it does not include the boundary parameter.

You should not meddle with Content-Type header at the request level and let HttpClient generate it automatically based on properties of the enclosed request entity.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM