Example usage for com.squareup.okhttp ResponseBody create

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

Introduction

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

Prototype

public static ResponseBody create(final MediaType contentType, final long contentLength,
        final BufferedSource content) 

Source Link

Document

Returns a new response body that transmits content .

Usage

From source file:co.paralleluniverse.fibers.okhttp.InterceptorTest.java

License:Open Source License

static ResponseBody uppercase(ResponseBody original) throws IOException {
    return ResponseBody.create(original.contentType(), original.contentLength(),
            Okio.buffer(uppercase(original.source())));
}

From source file:com.facebook.buck.slb.LoadBalancedHttpResponseTest.java

License:Apache License

@Before
public void setUp() throws IOException {
    mockLoadBalancer = createMock(HttpLoadBalancer.class);
    mockInputStream = createMock(InputStream.class);

    mockBufferedSource = createMock(BufferedSource.class);
    mockBufferedSource.close();/*from  w  w  w .  j  a va2 s .  c om*/
    EasyMock.expectLastCall().once();

    responseBody = ResponseBody.create(MediaType.parse("text/plain"), 42, mockBufferedSource);
    request = new Request.Builder().url(SERVER.toString()).build();
    response = new Response.Builder().body(responseBody).code(200).protocol(Protocol.HTTP_1_1).request(request)
            .build();
}

From source file:com.kubeiwu.easyandroid.easyhttp.core.retrofit.Utils.java

License:Apache License

/**
 * Replace a {@link Response} with an identical copy whose body is backed by
 * a {@link Buffer} rather than a {@link Source}.
 *//* w ww.j  a  va  2 s  .c o m*/
public static ResponseBody readBodyToBytesIfNecessary(final ResponseBody body) throws IOException {
    if (body == null) {
        return null;
    }

    BufferedSource source = body.source();
    Buffer buffer = new Buffer();
    buffer.writeAll(source);
    source.close();

    return ResponseBody.create(body.contentType(), body.contentLength(), buffer);
}

From source file:com.pangbo.android.thirdframworks.retrofit.Utils.java

License:Apache License

/**
 * Replace a {@link Response} with an identical copy whose body is backed by a
 * {@link Buffer} rather than a .//from w w  w . j a va2s . c om
 */
static ResponseBody readBodyToBytesIfNecessary(final ResponseBody body) throws IOException {
    if (body == null) {
        return null;
    }

    BufferedSource source = body.source();
    Buffer buffer = new Buffer();
    buffer.writeAll(source);
    source.close();

    return ResponseBody.create(body.contentType(), body.contentLength(), buffer);
}

From source file:com.rafagarcia.countries.backend.webapi.HttpLoggingInterceptor.java

License:Apache License

@Override
public Response intercept(Chain chain) throws IOException {
    Level level = this.level;

    Request request = chain.request();
    if (level == Level.NONE) {
        return chain.proceed(request);
    }//w  w  w. ja v  a  2s .  co m

    boolean logBody = level == Level.BODY;
    boolean logHeaders = logBody || level == Level.HEADERS;

    RequestBody requestBody = request.body();
    boolean hasRequestBody = requestBody != null;

    Connection connection = chain.connection();
    Protocol protocol = connection != null ? connection.getProtocol() : Protocol.HTTP_1_1;
    String requestStartMessage = "--> " + request.method() + ' ' + requestPath(request.httpUrl()) + ' '
            + protocol(protocol);
    if (!logHeaders && hasRequestBody) {
        requestStartMessage += " (" + requestBody.contentLength() + "-byte body)";
    }
    logger.log(requestStartMessage);

    if (logHeaders) {
        Headers headers = request.headers();
        for (int i = 0, count = headers.size(); i < count; i++) {
            logger.log(headers.name(i) + ": " + headers.value(i));
        }

        if (logBody && hasRequestBody) {
            Buffer buffer = new Buffer();
            requestBody.writeTo(buffer);

            Charset charset = UTF8;
            MediaType contentType = requestBody.contentType();
            if (contentType != null) {
                contentType.charset(UTF8);
            }

            logger.log("");
            logger.log(buffer.readString(charset));
        }

        String endMessage = "--> END " + request.method();
        if (logBody && hasRequestBody) {
            endMessage += " (" + requestBody.contentLength() + "-byte body)";
        }
        logger.log(endMessage);
    }

    long startNs = System.nanoTime();
    Response response = chain.proceed(request);
    long tookMs = TimeUnit.NANOSECONDS.toMillis(System.nanoTime() - startNs);

    ResponseBody responseBody = response.body();
    logger.log("<-- " + protocol(response.protocol()) + ' ' + response.code() + ' ' + response.message() + " ("
            + tookMs + "ms" + (!logHeaders ? ", " + responseBody.contentLength() + "-byte body" : "") + ')');

    if (logHeaders) {
        Headers headers = response.headers();
        for (int i = 0, count = headers.size(); i < count; i++) {
            logger.log(headers.name(i) + ": " + headers.value(i));
        }

        if (logBody) {
            Buffer buffer = new Buffer();
            responseBody.source().readAll(buffer);

            Charset charset = UTF8;
            MediaType contentType = responseBody.contentType();
            if (contentType != null) {
                charset = contentType.charset(UTF8);
            }

            if (responseBody.contentLength() > 0) {
                logger.log("");
                logger.log(buffer.clone().readString(charset));
            }

            // Since we consumed the original, replace the one-shot body in the response with a new one.
            response = response.newBuilder()
                    .body(ResponseBody.create(contentType, responseBody.contentLength(), buffer)).build();
        }

        String endMessage = "<-- END HTTP";
        if (logBody) {
            endMessage += " (" + responseBody.contentLength() + "-byte body)";
        }
        logger.log(endMessage);
    }

    return response;
}

From source file:retrofit.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//  w ww.j av  a2 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, ?> fromResponseBody(Type type, Annotation[] annotations) {
                    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");
    }
}

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. c  om
        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");
    }
}