AbtPst
AbtPst

Reputation: 8008

Apache HTTP : How to set custom ContentType

I am using the apache http client to upload a file as

public void whenSendMultipartRequestUsingHttpClient_thenCorrect() 
  throws ClientProtocolException, IOException {
    CloseableHttpClient client = HttpClients.createDefault();
    HttpPost httpPost = new HttpPost("http://www.example.com");

    MultipartEntityBuilder builder = MultipartEntityBuilder.create();
    builder.addTextBody("ads", "John");
    builder.addTextBody("qwe", "pass");
    builder.addBinaryBody("file", new File("test.txt"),
      ContentType.APPLICATION_OCTET_STREAM, "file.ext");

    HttpEntity multipart = builder.build();
    httpPost.setEntity(multipart);

    CloseableHttpResponse response = client.execute(httpPost);
    assertThat(response.getStatusLine().getStatusCode(), equalTo(200));
    client.close();
}

the problem is that the server side needs the ContentType of the file to be application/myCustomTag

However, this is not a value in the ContentType interface. Is there any way for me to provide a custom string as ContentType?

EDIT

I tried to recreate the request as seen on the browser

with my request headers as

[X-head1: {someJson}, Accept: application/json, X-head2: someVal, X-head3: otherVal, Content-Type: application/json]

and the payload

[Content-Disposition: form-data; name="file.ext"; filename="test.txt", Content-Type: application/octet-stream, Content-Transfer-Encoding: binary]

the key difference that i can see is that in the payload i see the following in the browser

Content-Type: application/myCustomTag

which is not an HTTP standard Content-Type so i cannot set it as such

Upvotes: 2

Views: 3282

Answers (1)

B. Bri
B. Bri

Reputation: 585

Did you try setHeader on your HttpPost ? API here

Alternative:

ContentType.create("application/myCustomTag")

Upvotes: 1

Related Questions