Example usage for com.squareup.okhttp RequestBody contentLength

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

Introduction

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

Prototype

public long contentLength() throws IOException 

Source Link

Document

Returns the number of bytes that will be written to out in a call to #writeTo , or -1 if that count is unknown.

Usage

From source file:alberto.avengers.model.rest.utils.interceptors.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 ww. j  ava 2s  .c  o  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));
        }

        String endMessage = "--> END " + request.method();
        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));

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

        String endMessage = "<-- END HTTP";
        if (logBody) {
            BufferedSource source = responseBody.source();
            source.request(Long.MAX_VALUE); // Buffer the entire body.
            Buffer buffer = source.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));
            }

            endMessage += " (" + buffer.size() + "-byte body)";
        }
        logger.log(endMessage);
    }

    return response;
}

From source file:cn.com.canon.darwin.modules.service.api.interceptor.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);
    }// ww w  .j  av  a2  s.  c o  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() + ' ' + request.url() + ' ' + protocol;
    if (!logHeaders && hasRequestBody) {
        requestStartMessage += " (" + requestBody.contentLength() + "-byte body)";
    }
    logger.log(requestStartMessage);

    if (logHeaders) {
        //            if (hasRequestBody) {
        //                // Request body headers are only present when installed as a
        //                // network interceptor. Force
        //                // them to be included (when available) so there values are
        //                // known.
        //                if (requestBody.contentType() != null) {
        //                    logger.log("Content-Type: " + requestBody.contentType());
        //                }
        //                if (requestBody.contentLength() != -1) {
        //                    logger.log("Content-Length: " + requestBody.contentLength());
        //                }
        //            }

        //            Headers headers = request.headers();
        //            for (int i = 0, count = headers.size(); i < count; i++) {
        //                String name = headers.name(i);
        //                // Skip headers from the request body as they are explicitly
        //                // logged above.
        //                if (!"Content-Type".equalsIgnoreCase(name) && !"Content-Length".equalsIgnoreCase(name)) {
        //                    logger.log(name + ": " + headers.value(i));
        //                }
        //            }

        if (!logBody || !hasRequestBody) {
            logger.log("--> END " + request.method());
        } else if (bodyEncoded(request.headers())) {
            logger.log("--> END " + request.method() + " (encoded body omitted)");
        } else {
            Buffer buffer = new Buffer();
            requestBody.writeTo(buffer);

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

            logger.log("");
            if (isPlaintext(buffer)) {
                logger.log(buffer.readString(charset));
                logger.log("--> END " + request.method() + " (" + requestBody.contentLength() + "-byte body)");
            } else {
                logger.log("--> END " + request.method() + " (binary " + requestBody.contentLength()
                        + "-byte body omitted)");
            }
        }
    }

    long startNs = System.nanoTime();
    Response response;
    try {
        response = chain.proceed(request);
    } catch (Exception e) {
        logger.log("<-- HTTP FAILED: " + e);
        throw e;
    }
    long tookMs = TimeUnit.NANOSECONDS.toMillis(System.nanoTime() - startNs);

    ResponseBody responseBody = response.body();
    long contentLength = responseBody.contentLength();
    String bodySize = contentLength != -1 ? contentLength + "-byte" : "unknown-length";
    logger.log("<-- " + response.code() + ' ' + response.message() + ' ' + response.request().url() + " ("
            + tookMs + "ms" + (!logHeaders ? ", " + bodySize + " 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 || !HttpEngine.hasBody(response)) {
        logger.log("<-- END HTTP");
    } else if (bodyEncoded(response.headers())) {
        logger.log("<-- END HTTP (encoded body omitted)");
    } else {
        BufferedSource source = responseBody.source();
        source.request(Long.MAX_VALUE); // Buffer the entire body.
        Buffer buffer = source.buffer();

        Charset charset = UTF8;
        MediaType contentType = responseBody.contentType();
        if (contentType != null) {
            try {
                charset = contentType.charset(UTF8);
            } catch (UnsupportedCharsetException e) {
                logger.log("");
                logger.log("Couldn't decode the response body; charset is likely malformed.");
                logger.log("<-- END HTTP");

                return response;
            }
        }
        if (!isPlaintext(buffer)) {
            logger.log("");
            logger.log("<-- END HTTP (binary " + buffer.size() + "-byte body omitted)");
            return response;
        }
        if (contentLength != 0) {
            logger.log("");
            logger.log(buffer.clone().readString(charset));
        }
        logger.log("<-- END HTTP (" + buffer.size() + "-byte body)");
    }
    //        }

    return response;
}

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

License:Open Source License

private RequestBody uppercase(final RequestBody original) {
    return new RequestBody() {
        @Override//from  ww  w.j av a 2s .co  m
        public MediaType contentType() {
            return original.contentType();
        }

        @Override
        public long contentLength() throws IOException {
            return original.contentLength();
        }

        @Override
        public void writeTo(BufferedSink sink) throws IOException {
            Sink uppercase = uppercase(sink);
            BufferedSink bufferedSink = Okio.buffer(uppercase);
            original.writeTo(bufferedSink);
            bufferedSink.emit();
        }
    };
}

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

License:Apache License

@Test
public void networkInterceptorsCanChangeRequestMethodFromGetToPost() throws Exception {
    server.enqueue(new MockResponse());

    client.networkInterceptors().add(new Interceptor() {
        @Override//from  w  w  w .  j  ava2s.  c om
        public Response intercept(Chain chain) throws IOException {
            Request originalRequest = chain.request();
            MediaType mediaType = MediaType.parse("text/plain");
            RequestBody body = RequestBody.create(mediaType, "abc");
            return chain.proceed(originalRequest.newBuilder().method("POST", body)
                    .header("Content-Type", mediaType.toString())
                    .header("Content-Length", Long.toString(body.contentLength())).build());
        }
    });

    Request request = new Request.Builder().url(server.url("/")).get().build();

    client.newCall(request).execute();

    RecordedRequest recordedRequest = server.takeRequest();
    assertEquals("POST", recordedRequest.getMethod());
    assertEquals("abc", recordedRequest.getBody().readUtf8());
}

From source file:com.cml.rx.android.api.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.  j a  v  a  2  s  . c o  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() + ' ' + request.url() + ' ' + protocol;
    if (!logHeaders && hasRequestBody) {
        requestStartMessage += " (" + requestBody.contentLength() + "-byte body)";
    }
    logger.log(requestStartMessage);

    if (logHeaders) {
        if (hasRequestBody) {
            // Request body headers are only present when installed as a
            // network interceptor. Force
            // them to be included (when available) so there values are
            // known.
            if (requestBody.contentType() != null) {
                logger.log("Content-Type: " + requestBody.contentType());
            }
            if (requestBody.contentLength() != -1) {
                logger.log("Content-Length: " + requestBody.contentLength());
            }
        }

        Headers headers = request.headers();
        for (int i = 0, count = headers.size(); i < count; i++) {
            String name = headers.name(i);
            // Skip headers from the request body as they are explicitly
            // logged above.
            if (!"Content-Type".equalsIgnoreCase(name) && !"Content-Length".equalsIgnoreCase(name)) {
                logger.log(name + ": " + headers.value(i));
            }
        }

        if (!logBody || !hasRequestBody) {
            logger.log("--> END " + request.method());
        } else if (bodyEncoded(request.headers())) {
            logger.log("--> END " + request.method() + " (encoded body omitted)");
        } else {
            Buffer buffer = new Buffer();
            requestBody.writeTo(buffer);

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

            logger.log("");
            if (isPlaintext(buffer)) {
                logger.log(buffer.readString(charset));
                logger.log("--> END " + request.method() + " (" + requestBody.contentLength() + "-byte body)");
            } else {
                logger.log("--> END " + request.method() + " (binary " + requestBody.contentLength()
                        + "-byte body omitted)");
            }
        }
    }

    long startNs = System.nanoTime();
    Response response;
    try {
        response = chain.proceed(request);
    } catch (Exception e) {
        logger.log("<-- HTTP FAILED: " + e);
        throw e;
    }
    long tookMs = TimeUnit.NANOSECONDS.toMillis(System.nanoTime() - startNs);

    ResponseBody responseBody = response.body();
    long contentLength = responseBody.contentLength();
    String bodySize = contentLength != -1 ? contentLength + "-byte" : "unknown-length";
    logger.log("<-- " + response.code() + ' ' + response.message() + ' ' + response.request().url() + " ("
            + tookMs + "ms" + (!logHeaders ? ", " + bodySize + " 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 || !HttpEngine.hasBody(response)) {
            logger.log("<-- END HTTP");
        } else if (bodyEncoded(response.headers())) {
            logger.log("<-- END HTTP (encoded body omitted)");
        } else {
            BufferedSource source = responseBody.source();
            source.request(Long.MAX_VALUE); // Buffer the entire body.
            Buffer buffer = source.buffer();

            Charset charset = UTF8;
            MediaType contentType = responseBody.contentType();
            if (contentType != null) {
                try {
                    charset = contentType.charset(UTF8);
                } catch (UnsupportedCharsetException e) {
                    logger.log("");
                    logger.log("Couldn't decode the response body; charset is likely malformed.");
                    logger.log("<-- END HTTP");

                    return response;
                }
            }

            if (!isPlaintext(buffer)) {
                logger.log("");
                logger.log("<-- END HTTP (binary " + buffer.size() + "-byte body omitted)");
                return response;
            }

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

            logger.log("<-- END HTTP (" + buffer.size() + "-byte body)");
        }
    }

    return response;
}

From source file:com.ibm.watson.developer_cloud.service.RequestBuilderTest.java

License:Open Source License

/**
 * Test with body./*from  w  w w  . j  a v  a  2s .  co  m*/
 * 
 * @throws IOException Signals that an I/O exception has occurred.
 */
@Test
public void testWithBody() throws IOException {
    final File test = new File("src/test/resources/car.png");

    final Request request = RequestBuilder.post(urlWithQuery)
            .withBody(RequestBody.create(HttpMediaType.BINARY_FILE, test)).build();

    final RequestBody requestedBody = request.body();

    assertEquals(test.length(), requestedBody.contentLength());
    assertEquals(HttpMediaType.BINARY_FILE, requestedBody.contentType());
}

From source file:com.parse.ParseOkHttpClientTest.java

License:Open Source License

@Test
public void testGetOkHttpRequest() throws IOException {
    Map<String, String> headers = new HashMap<>();
    String headerName = "name";
    String headerValue = "value";
    headers.put(headerName, headerValue);

    String url = "http://www.parse.com/";
    String content = "test";
    int contentLength = content.length();
    String contentType = "application/json";
    ParseHttpRequest parseRequest = new ParseHttpRequest.Builder().setUrl(url)
            .setMethod(ParseHttpRequest.Method.POST).setBody(new ParseByteArrayHttpBody(content, contentType))
            .setHeaders(headers).build();

    ParseOkHttpClient parseClient = new ParseOkHttpClient(10000, null);
    Request okHttpRequest = parseClient.getRequest(parseRequest);

    // Verify method
    assertEquals(ParseHttpRequest.Method.POST.toString(), okHttpRequest.method());
    // Verify URL
    assertEquals(url, okHttpRequest.urlString());
    // Verify Headers
    assertEquals(1, okHttpRequest.headers(headerName).size());
    assertEquals(headerValue, okHttpRequest.headers(headerName).get(0));
    // Verify Body
    RequestBody okHttpBody = okHttpRequest.body();
    assertEquals(contentLength, okHttpBody.contentLength());
    assertEquals(contentType, okHttpBody.contentType().toString());
    // Can not read parseRequest body to compare since it has been read during
    // creating okHttpRequest
    Buffer buffer = new Buffer();
    okHttpBody.writeTo(buffer);/*from   ww w.  j  a v a2 s  .c  om*/
    ByteArrayOutputStream output = new ByteArrayOutputStream();
    buffer.copyTo(output);
    assertArrayEquals(content.getBytes(), output.toByteArray());
}

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);
    }//from   ww w. j  a v  a  2  s .c  o 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:com.xing.api.CallSpecTest.java

License:Apache License

@Test
public void builderEnsuresEmptyBody() throws Exception {
    CallSpec.Builder builder = builder(HttpMethod.PUT, "", false).responseAs(Object.class);
    // Build the CallSpec so that we can build the request.
    builder.build();/*  w w w  .j  a  va 2  s.c o m*/

    Request request = builder.request();
    assertThat(request.method()).isEqualTo(HttpMethod.PUT.method());
    assertThat(request.httpUrl()).isEqualTo(httpUrl);
    assertThat(request.body()).isNotNull();

    RequestBody body = request.body();
    assertThat(body.contentType()).isNull();
    assertThat(body.contentLength()).isEqualTo(0);

    Buffer buffer = new Buffer();
    body.writeTo(buffer);
    assertThat(buffer.readUtf8()).isEmpty();
}

From source file:com.xing.api.CallSpecTest.java

License:Apache License

@Test
public void builderAllowsRawBody() throws Exception {
    CallSpec.Builder builder = builder(HttpMethod.PUT, "", false).responseAs(Object.class)
            .body(RequestBody.create(MediaType.parse("application/text"), "Hey!"));
    // Build the CallSpec so that we can build the request.
    builder.build();/*  w  w  w .java2 s  . c om*/

    Request request = builder.request();
    RequestBody body = request.body();
    assertThat(body.contentLength()).isEqualTo(4);
    assertThat(body.contentType().subtype()).isEqualTo("text");

    Buffer buffer = new Buffer();
    body.writeTo(buffer);
    assertThat(buffer.readUtf8()).isEqualTo("Hey!");
}