alternatives to content-length -1 MultipartBuilder
I am doing the following test:
@Test
public void testMultipartBuilder() throws Exception {
MockWebServer mockWebServer = new MockWebServer();
mockWebServer.play();
OkHttpClient client = new OkHttpClient();
mockWebServer.setDispatcher(new Dispatcher() {
@Override
public MockResponse dispatch(RecordedRequest request) throws InterruptedException {
if (request.getHeader("Content-Length") == null) {
return new MockResponse()
.setStatus("HTTP/1.1 411")
.setResponseCode(411)
.addHeader("content-type: text/plain; charset=utf-8")
.setBody("Length Required");
} else
return new MockResponse()
.setStatus("HTTP/1.1 200")
.setResponseCode(Constants.HTTP_OK)
.addHeader("content-type: text/plain; charset=utf-8")
.setBody("server: nginx");
}
});
RequestBody requestBody = new MultipartBuilder()
.type(MultipartBuilder.FORM)
.addFormDataPart("title", "Square Logo")
.addFormDataPart("image", null,
RequestBody.create(MediaType.parse("image/png"),
new File("website/static/logo-square.png")))
.build();
com.squareup.okhttp.Request request = new com.squareup.okhttp.Request.Builder()
.url(mockWebServer.getUrl("/images/"))
.post(requestBody)
.build();
com.squareup.okhttp.Response response = client.newCall(request).execute();
assertTrue(response.isSuccessful());
}
the contentLength() from MultipartBuilder returns the number of bytes that will be written to out in a call to writeTo, or -1 if that count is unknown.
As this happens it does not send the header Content-Length, and my need this header to process the request.
what options exist to obtain the content-length?
Write the multipart body to a Buffer. Then use that Buffer as the body for the actual request.
Can be?
Buffer buffer = new Buffer();
requestBody.writeTo(buffer);
com.squareup.okhttp.Request request = new com.squareup.okhttp.Request.Builder()
.url(mockWebServer.getUrl("/images/"))
.post(RequestBody.create(MultipartBuilder.FORM,buffer.readByteArray()))
.build();
Hmm, it's unfortunate that you to call .readByteArray(). Maybe we should allow passing a Buffer. I'll have to see if that has any adverse effects.
I Agree.
public static RequestBody create(final MediaType contentType, final Buffer buffer) {
return new RequestBody() {
@Override public MediaType contentType() {
return contentType;
}
@Override public long contentLength() {
return buffer.size();
}
@Override public void writeTo(BufferedSink sink) throws IOException {
Source source = buffer;
try {
sink.writeAll(source);
} finally {
Util.closeQuietly(source);
}
}
};
}
Use buffer.size()
works fine , but it would be a viable option Request accepted Buffer as a parameter?
Unfortunately since Buffer is mutable, we'd need to defensively copy in that case, which would be inefficient. Does tempt me to offer an optimized Buffer.byteString() that shares pages with the backing-buffer.
Definitely not a good choice
in this case is possible create a method that takes a RequestBody and new RequestBody that knows its content length. It is not always necessary to know the content-length
I'm currently having similar situation where server didn't want to work with Transfer-Encoding=chunked instead of Content-Length header so I had to use @felipeska 's approach with one change which made it complete.
Passing MediaType.FORM to create method removed boundary which rendered multipart request useless. Instead of it, I've passed requestBody.contentType() and maintained same Content-Type which was built by MultipartRequestBuilder.
TBH, not very happy and proud with solving it this way (allocating buffer for request just to be rewritten) since I feel there should be some way to choose this due to different server support.
@vbokan yup. We can make MultipartRequestBuilder compute the content-length in its content-length method, but doing so is somewhat ugly. Made less so by an Okio change that's currently stalled:
https://github.com/square/okio/pull/98
@swankjesse may change a Request with an interceptor (Network Interceptors)?
@vbokan You can also use an Application Interceptor. still not the best option.
public class ContentLengthInterceptor implements Interceptor {
@Override
public Response intercept(Chain chain) throws IOException {
Request originalRequest = chain.request();
if (originalRequest.body().contentLength() != -1) {
return chain.proceed(originalRequest);
}
Request customRequest = originalRequest.newBuilder()
.method(originalRequest.method(), requestBodyWithContentLength(originalRequest.body()))
.build();
return chain.proceed(customRequest);
}
private RequestBody requestBodyWithContentLength(RequestBody requestBody) throws IOException {
Buffer buffer = new Buffer();
try {
requestBody.writeTo(buffer);
} catch (IOException e) {
throw new IOException("Unable to copy RequestBody");
}
return new RequestBody() {
@Override
public MediaType contentType() {
return requestBody.contentType();
}
@Override
public long contentLength() {
return buffer.size();
}
@Override
public void writeTo(BufferedSink sink) throws IOException {
sink.write(ByteString.read(buffer.inputStream(), (int) buffer.size()));
}
};
}
}
I was just bitten by the same issue when trying to upload to S3.
The proposed workaround is problematic:
- It requires you to buffer the entire thing in-memory (can't easily side-step this one, as explicitly setting the Content-Length header is ignored). Imagine uploading a file that weights a few mb to S3.
- It is very non-obvious.
I hope it is put in 2.3, would be great.
Till then, trying to use the Buffer method and get the work done..
@Sheikh-Aman is sad to have to do this, if you can avoid using multipartBuilder .. or take the multipartBuilder legacy as he solves.
As a temporary workaround for me, I ended up going with using ion just for multipart image uploads. Worked like a charm if anyone wants an alternative. I'm using it for uploading to S3 with a multipart form submission.