1

Problem

I'm working with an external REST API on a test system. There is an upload path I'm trying to implement and I am using the Apache HTTPClient. I tried it with the following postman configuration and it works perfectly:

Postman Request

The upload works fine like that.

Implementation in Java

CloseableHttpClient httpClient = HttpClients.createDefault();
HttpPut request = new HttpPut("../upload") // placeholder url, not the real one
    
request.setHeader("Content-type", "multipart/form-data");   
request.setHeader(HttpHeaders.AUTHORIZATION, "HEY I AM A TOKEN");       
    
FileBody fileBody = new FileBody(new File("dummy.pdf"), ContentType.create("application/pdf"));
MultipartEntityBuilder builder = MultipartEntityBuilder.create();
builder.addPart("file", fileBody);
request.setEntity(builder.build());
    
CloseableHttpResponse response = httpClient.execute(request);

Error

I always get a specific error from the rest api:

File could not have been parsed

The documentation of the upload path mentions the following details:

  • Header Content-Type multipart/form-data
  • Only one multipart element
  • Content-Type of the element needs to be application/pdf
  • Name needs to be "file"

I think I do every point of this list in my request - so what is the difference between the postman request and my own java http request?

What do I miss?

EDIT:

The same code with OkHTTP works. Still don't know why it does not work with Apache HttpClient.

OkHttpClient testClient = new OkHttpClient();
File testfile = new File("dummy.pdf");

RequestBody body = new MultipartBuilder().type(MultipartBuilder.FORM).addFormDataPart("file","dummy.pdf",
RequestBody.create(MediaType.parse("application/pdf"),testfile)).build();

Request testreq = new Request.Builder()
.url("../upload")
.header("Authorization", "HI I AM A TOKEN")
.put(body)
.build();
Response testres = testClient.newCall(testreq).execute();
2
  • Are you sure of the URI "../upload"? I am getting an error with it - Target host is not specified. Commented Nov 5, 2021 at 11:08
  • I did not want to post the real url but this part should be fine. The error I receive would be different if the url/path is wrong. Commented Nov 5, 2021 at 11:33

1 Answer 1

0

I had to remove this line

request.setHeader("Content-type", "multipart/form-data");   

to make it work. I dont really know why so if someone can help me out with this and give some explanation I'm up for it. For the moment I'm happy because it works now.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.