Upload File in form data using Java

Paul :

I am trying to perform a HTTP Post Request in Java using the Apache API.

With curl the request looks like this

curl https://host/upload
-X POST
-H "Authorization: Bearer xxx"
-H "Content-Type: multipart/form-data"
-H "Accept: application/json"
-F "file=@{PathToImage}" -F "type=file" 

While this work fine when running it with CURL the server returns a 500er result when running it with the following Java code

    final HttpPost httppost = new HttpPost("https://host/upload");
    httppost.addHeader("Authorization", "Bearer xxx");
    httppost.addHeader("Accept", "application/json");
    httppost.addHeader("Content-Type", "multipart/form-data");

    final MultipartEntityBuilder builder = MultipartEntityBuilder.create();
    final File file = new File("c:\\tmp\\myfile.pdf");
    builder.addBinaryBody("file", file);
    builder.addTextBody("type", "file");
    final HttpEntity entity = builder.build();
    httppost.setEntity(entity);
    final HttpResponse response = httpclient.execute(httppost);
    httpclient.close();

Any idea what I am missing here?

C. Smith :

This question is similar. But I believe the answer is changing your addBinary to addPart.

final HttpPost httppost = new HttpPost("https://host/upload");
httppost.addHeader("Authorization", "Bearer xxx");
httppost.addHeader("Accept", "application/json");
httppost.addHeader("Content-Type", "multipart/form-data");

final MultipartEntityBuilder builder = MultipartEntityBuilder.create();
final File file = new File("c:\\tmp\\myfile.pdf");
builder.addPart("file", new FileBody(file));
builder.addTextBody("type", "file");
final HttpEntity entity = builder.build();
httppost.setEntity(entity);
final HttpResponse response = httpclient.execute(httppost);
httpclient.close();

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=322078&siteId=1