Example usage for com.squareup.okhttp ResponseBody contentLength

List of usage examples for com.squareup.okhttp ResponseBody contentLength

Introduction

In this page you can find the example usage for com.squareup.okhttp ResponseBody contentLength.

Prototype

public abstract long contentLength() throws IOException;

Source Link

Document

Returns the number of bytes in that will returned by #bytes , or #byteStream , or -1 if unknown.

Usage

From source file:retrofit2.CallTest.java

License:Apache License

@Test
public void conversionProblemIncomingMaskedByConverterIsUnwrapped() throws IOException {
    // MWS has no way to trigger IOExceptions during the response body so use an interceptor.
    OkHttpClient client = new OkHttpClient();
    client.interceptors().add(new Interceptor() {
        @Override//from  w w  w. ja va2 s  .co m
        public com.squareup.okhttp.Response intercept(Chain chain) throws IOException {
            com.squareup.okhttp.Response response = chain.proceed(chain.request());
            ResponseBody body = response.body();
            BufferedSource source = Okio.buffer(new ForwardingSource(body.source()) {
                @Override
                public long read(Buffer sink, long byteCount) throws IOException {
                    throw new IOException("cause");
                }
            });
            body = ResponseBody.create(body.contentType(), body.contentLength(), source);
            return response.newBuilder().body(body).build();
        }
    });

    Retrofit retrofit = new Retrofit.Builder().baseUrl(server.url("/")).client(client)
            .addConverterFactory(new ToStringConverterFactory() {
                @Override
                public Converter<ResponseBody, ?> responseBodyConverter(Type type, Annotation[] annotations,
                        Retrofit retrofit) {
                    return new Converter<ResponseBody, String>() {
                        @Override
                        public String convert(ResponseBody value) throws IOException {
                            try {
                                return value.string();
                            } catch (IOException e) {
                                // Some serialization libraries mask transport problems in runtime exceptions. Bad!
                                throw new RuntimeException("wrapper", e);
                            }
                        }
                    };
                }
            }).build();
    Service example = retrofit.create(Service.class);

    server.enqueue(new MockResponse().setBody("Hi"));

    Call<String> call = example.getString();
    try {
        call.execute();
        fail();
    } catch (IOException e) {
        assertThat(e).hasMessage("cause");
    }
}