1

I'm having below code to send a multipart/form-data request.

List<Attachment> multipartData = new ArrayList<>();
ContentDisposition cd1 = new ContentDisposition("form-data; name=\"file\"; 
filename="+fileObj.getName());

FileInputStream inputStream = new FileInputStream(fileObj);
multipartData.add(new Attachment("file",inputStream, cd1));

MultipartBody multipart = new MultipartBody(multipartData);

In my RestClient class, I'm using the below lines of code to send a POST request using JAX-RS Client object

if ("POST".equals(method)) {
            response = this.client.getBuilder().post(Entity.entity(entity,MediaType.MULTIPART_FORM_DATA));

I checked the HTTP request body using Wiremock and is as below:

Transfer-Encoding: [chunked]
Accept: [*/*]
Cache-Control: [no-cache]
User-Agent: [Apache-CXF/3.2.5]
Connection: [keep-alive]
Host: [127.0.0.1:9990]
Pragma: [no-cache]
Content-Type: [multipart/form-data; boundary="uuid:04b491f5-50de-4f4f-b7c0-cd745136d3d1"]

--uuid:04b491f5-50de-4f4f-b7c0-cd745136d3d1
Content-Type: application/octet-stream
Content-Transfer-Encoding: binary
Content-ID: <file>
Content-Disposition: form-data; name="file"; filename=sample.txt

<File content goes here>

I want to know how the content-length header is missing in the request payload. Is there any way to set the content-length header to the request?

Please help me.

Sudhakar Reddy
  • 116
  • 1
  • 12
  • 1
    The transfer encoding is "chunked", which overrides the use of the Content-Length (basically, it is used preciesly when the total length is unknown, by outputting data in several chunks of variable size, and not in one chunk). – GPI Oct 08 '18 at 13:43
  • Is there a way to disable Transfer_encoding as "chunked" and force the client to add Content-Length header? – Sudhakar Reddy Oct 09 '18 at 05:32
  • 1
    From the server side, the only way to disable chunked encoding is to support only HTTP 1.0 and not HTTP 1.1, which I would not recommend (reasons vary from supporting https/TLS to interactions with possible proxies, etc...). So, while it may be possible, I'd strongly strongly suggest that you work around your need of a Content-Length. Why/What do you need the content length in the header for ? – GPI Oct 09 '18 at 07:18
  • 1
    Because the exposed API is built in Django framework. It wont accept chunked data. – Sudhakar Reddy Oct 10 '18 at 05:49

1 Answers1

1

I used the apache cxf WebClient to unset the transfer encoding as chunked.

if ("POST".equals(method)) {
    Invocation.Builder builder = this.client.getBuilder();
    WebClient.getConfig(builder).getHttpConduit().getClient().setAllowChunking(false);
    response = builder.post(Entity.entity(entity,MediaType.MULTIPART_FORM_DATA));
}

With this, the client is able to send the request with content-length header.

Sudhakar Reddy
  • 116
  • 1
  • 12