okhttp icon indicating copy to clipboard operation
okhttp copied to clipboard

alternatives to content-length -1 MultipartBuilder

Open felipeska opened this issue 11 years ago • 16 comments

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?

felipeska avatar Jan 27 '15 16:01 felipeska

Write the multipart body to a Buffer. Then use that Buffer as the body for the actual request.

JakeWharton avatar Jan 27 '15 17:01 JakeWharton

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();

felipeska avatar Jan 27 '15 18:01 felipeska

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.

JakeWharton avatar Jan 27 '15 18:01 JakeWharton

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);
        }
      }
    };
  }

felipeska avatar Jan 27 '15 18:01 felipeska

Use buffer.size()

JakeWharton avatar Jan 27 '15 18:01 JakeWharton

works fine , but it would be a viable option Request accepted Buffer as a parameter?

felipeska avatar Jan 27 '15 19:01 felipeska

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.

swankjesse avatar Jan 27 '15 19:01 swankjesse

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

felipeska avatar Jan 27 '15 20:01 felipeska

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 avatar Jan 28 '15 23:01 vbokan

@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 avatar Jan 29 '15 00:01 swankjesse

@swankjesse may change a Request with an interceptor (Network Interceptors)?

felipeska avatar Jan 29 '15 00:01 felipeska

@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()));
      }
    };
  }
}

felipeska avatar Jan 29 '15 01:01 felipeska

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.

tals avatar Jan 31 '15 23:01 tals

I hope it is put in 2.3, would be great. Till then, trying to use the Buffer method and get the work done..

Aman-Aalam avatar Feb 20 '15 21:02 Aman-Aalam

@Sheikh-Aman is sad to have to do this, if you can avoid using multipartBuilder .. or take the multipartBuilder legacy as he solves.

felipeska avatar Feb 20 '15 23:02 felipeska

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.

wildseansy avatar Feb 20 '15 23:02 wildseansy