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:com.yandex.disk.rest.RestClientIO.java

License:Apache License

void downloadUrl(final String url, final DownloadListener downloadListener)
        throws IOException, CancelledDownloadException, DownloadNoSpaceAvailableException, HttpCodeException {

    Request.Builder req = buildRequest().url(url);

    long length = downloadListener.getLocalLength();
    String ifTag = "If-None-Match";
    if (length >= 0) {
        ifTag = "If-Range";
        StringBuilder contentRange = new StringBuilder();
        contentRange.append("bytes=").append(length).append("-");
        logger.debug("Range: " + contentRange);
        req.addHeader("Range", contentRange.toString());
    }//from  www.j  av  a2 s .co m

    String etag = downloadListener.getETag();
    if (etag != null) {
        logger.debug(ifTag + ": " + etag);
        req.addHeader(ifTag, etag);
    }

    Request request = req.build();
    Response response = client.newCall(request).execute();

    boolean partialContent = false;
    int code = response.code();
    switch (code) {
    case 200:
        // OK
        break;
    case 206:
        partialContent = true;
        break;
    case 304:
        throw new FileNotModifiedException(code);
    case 404:
        throw new NotFoundException(code);
    case 416:
        throw new RangeNotSatisfiableException(code);
    default:
        throw new HttpCodeException(code);
    }

    ResponseBody responseBody = response.body();
    long contentLength = responseBody.contentLength();
    logger.debug("download: contentLength=" + contentLength);

    long loaded;
    if (partialContent) {
        ContentRangeResponse contentRangeResponse = parseContentRangeHeader(response.header("Content-Range"));
        logger.debug("download: contentRangeResponse=" + contentRangeResponse);
        if (contentRangeResponse != null) {
            loaded = contentRangeResponse.getStart();
            contentLength = contentRangeResponse.getSize();
        } else {
            loaded = length;
        }
    } else {
        loaded = 0;
        if (contentLength < 0) {
            contentLength = 0;
        }
    }

    OutputStream os = null;
    try {
        downloadListener.setStartPosition(loaded);
        MediaType contentTypeHeader = responseBody.contentType();
        if (contentTypeHeader != null) {
            downloadListener.setContentType(contentTypeHeader.toString());
        }
        downloadListener.setContentLength(contentLength);

        int count;
        InputStream content = responseBody.byteStream();
        os = downloadListener.getOutputStream(partialContent);
        final byte[] downloadBuffer = new byte[1024];
        while ((count = content.read(downloadBuffer)) != -1) {
            if (downloadListener.hasCancelled()) {
                logger.info("Downloading " + url + " canceled");
                client.cancel(request.tag());
                throw new CancelledDownloadException();
            }
            os.write(downloadBuffer, 0, count);
            loaded += count;
            downloadListener.updateProgress(loaded, contentLength);
        }
    } catch (CancelledDownloadException ex) {
        throw ex;
    } catch (Exception e) {
        logger.warn(e.getMessage(), e);
        client.cancel(request.tag());
        if (e instanceof IOException) {
            throw (IOException) e;
        } else if (e instanceof RuntimeException) {
            throw (RuntimeException) e;
        } else if (e instanceof DownloadNoSpaceAvailableException) {
            throw (DownloadNoSpaceAvailableException) e;
        } else {
            // never happen
            throw new RuntimeException(e);
        }
    } finally {
        try {
            if (os != null) {
                os.close();
            }
        } catch (IOException ex) {
            // nothing
        }
        try {
            response.body().close();
        } catch (IOException | NullPointerException ex) {
            logger.warn(ex.getMessage(), ex);
        }
    }
}

From source file:feign.okhttp.OkHttpClient.java

License:Apache License

private static feign.Response.Body toBody(final ResponseBody input) {
    if (input == null || input.contentLength() == 0) {
        return null;
    }//from w w  w  .java 2  s.co  m
    if (input.contentLength() > Integer.MAX_VALUE) {
        throw new UnsupportedOperationException("Length too long " + input.contentLength());
    }
    final Integer length = input.contentLength() != -1 ? (int) input.contentLength() : null;

    return new feign.Response.Body() {

        @Override
        public void close() throws IOException {
            input.close();
        }

        @Override
        public Integer length() {
            return length;
        }

        @Override
        public boolean isRepeatable() {
            return false;
        }

        @Override
        public InputStream asInputStream() throws IOException {
            return input.byteStream();
        }

        @Override
        public Reader asReader() throws IOException {
            return input.charStream();
        }
    };
}

From source file:io.macgyver.core.okhttp.LoggingInterceptor.java

License:Apache License

@Override
public Response intercept(Chain chain) throws IOException {

    Level level = this.level;

    Request request = chain.request();
    if (level == Level.NONE || (!slf4j.isDebugEnabled())) {
        return chain.proceed(request);
    }//w  w  w .  ja v  a  2 s  .com

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

    try {

        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.httpUrl() + ' '
                + protocol(protocol);
        if (!logHeaders && hasRequestBody) {
            requestStartMessage += " (" + requestBody.contentLength() + "-byte body)";
        }
        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) {
                    log("Content-Type: " + requestBody.contentType());
                }
                if (requestBody.contentLength() != -1) {
                    log("Content-Length: " + requestBody.contentLength());
                }
            }

            Headers headers = request.headers();
            for (int i = 0, count = headers.size(); i < count; i++) {
                String name = headers.name(i);

                if (name.equalsIgnoreCase("authorization")) {
                    log(name + ": ************");
                } else {
                    // Skip headers from the request body as they are
                    // explicitly
                    // logged above.
                    if (!"Content-Type".equalsIgnoreCase(name) && !"Content-Length".equalsIgnoreCase(name)) {
                        log(name + ": " + headers.value(i));
                    }
                }
            }

            if (!logBody || !hasRequestBody) {
                slf4j.debug("--> END " + request.method());
            } else if (bodyEncoded(request.headers())) {
                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) {
                    contentType.charset(UTF8);
                }

                log("");
                String body = redactRequestBody(buffer.readString(charset));

                log(body);

                log("--> END " + request.method() + " (" + requestBody.contentLength() + "-byte body)");
            }
        }

    } catch (Exception e) {
        LoggerFactory.getLogger(LoggingInterceptor.class).warn("problem logging request: " + e); // no stack trace
    }
    long startNs = System.nanoTime();
    Response response = chain.proceed(request);
    try {
        long tookMs = TimeUnit.NANOSECONDS.toMillis(System.nanoTime() - startNs);

        ResponseBody responseBody = response.body();
        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++) {
                log(headers.name(i) + ": " + headers.value(i));
            }

            if (!logBody || !HttpEngine.hasBody(response)) {
                log("<-- END HTTP");
            } else if (!isResponseBodyPrintable(response)) {
                log("<-- END HTTP (body omitted)");
            } else {
                BufferedSource source = responseBody.source();
                source.request(maxPrintableBodySize); // 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) {
                    log("");
                    log(redactResponseBody(buffer.clone().readString(charset)));
                }

                log("<-- END HTTP (" + buffer.size() + "-byte body)");
            }
        }
    } catch (Exception e) {
        LoggerFactory.getLogger(LoggingInterceptor.class).warn("problem logging: " + e.toString());
    }

    return response;
}

From source file:name.kevinlocke.appveyor.testutils.ConcurrentHttpLoggingInterceptor.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 w  w w . j  a v  a 2 s. c om*/

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

    RequestBody requestBody = request.body();

    Connection connection = chain.connection();
    Protocol protocol = connection != null ? connection.getProtocol() : Protocol.HTTP_1_1;
    UUID requestId = UUID.randomUUID();
    StringBuilder requestMessage = new StringBuilder("--> ").append(requestId).append('\n')
            .append(request.method()).append(' ').append(request.httpUrl()).append(' ').append(protocol);
    if (!logHeaders && requestBody != null) {
        requestMessage.append(" (").append(requestBody.contentLength()).append("-byte body)");
    }
    requestMessage.append('\n');

    if (logHeaders) {
        if (requestBody != null) {
            // 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) {
                requestMessage.append("Content-Type: ").append(requestBody.contentType()).append('\n');
            }
            if (requestBody.contentLength() != -1) {
                requestMessage.append("Content-Length: ").append(requestBody.contentLength()).append('\n');
            }
        }

        Headers headers = request.headers();
        for (int i = 0, count = headers.size(); i < count; i++) {
            String name = headers.name(i);
            if ("Authorization".equalsIgnoreCase(name) || "Proxy-Authenticate".equalsIgnoreCase(name)
                    || "Proxy-Authorization".equalsIgnoreCase(name)
                    || "WWW-Authenticate".equalsIgnoreCase(name)) {
                requestMessage.append(name).append(": *****\n");
            }
            // Skip headers from the request body as they are explicitly
            // logged above.
            else if (!"Content-Type".equalsIgnoreCase(name) && !"Content-Length".equalsIgnoreCase(name)) {
                requestMessage.append(name).append(": ").append(headers.value(i)).append('\n');
            }
        }

        if (!logBody || requestBody == null) {
            requestMessage.append("--> END ").append(requestId).append('\n');
        } else if (bodyEncoded(request.headers())) {
            requestMessage.append("--> END ").append(requestId).append(" (encoded body omitted)").append('\n');
        } else {
            Buffer buffer = new Buffer();
            requestBody.writeTo(buffer);

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

            requestMessage.append('\n');
            if (isPlaintext(buffer)) {
                requestMessage.append(buffer.readString(charset)).append("\n--> END ").append(requestId)
                        .append(" (").append(requestBody.contentLength()).append("-byte body)\n");
            } else {
                requestMessage.append("--> END ").append(requestId).append(" (binary ")
                        .append(requestBody.contentLength()).append("-byte body omitted)\n");
            }
        }
    }

    logger.log(requestMessage.substring(0, requestMessage.length() - 1));

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

    ResponseBody responseBody = response.body();
    long contentLength = responseBody.contentLength();
    StringBuilder responseMessage = new StringBuilder("<-- ").append(requestId).append(' ')
            .append(response.request().url()).append(" (").append(tookMs).append("ms");
    if (!logHeaders) {
        responseMessage.append(", ");
        if (contentLength != -1) {
            responseMessage.append(contentLength).append("-byte");
        } else {
            responseMessage.append("unknown-length");
        }
        responseMessage.append(" body");
    }
    responseMessage.append(")\n");

    responseMessage.append(response.code()).append(' ').append(response.message()).append('\n');

    if (logHeaders) {
        Headers headers = response.headers();
        for (int i = 0, count = headers.size(); i < count; i++) {
            responseMessage.append(headers.name(i)).append(": ").append(headers.value(i)).append('\n');
        }

        if (!logBody || !HttpEngine.hasBody(response)) {
            responseMessage.append("<-- END HTTP\n");
        } else if (bodyEncoded(response.headers())) {
            responseMessage.append("<-- END HTTP (encoded body omitted)\n");
        } 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) {
                charset = contentType.charset(UTF8);
            }

            if (!isPlaintext(buffer)) {
                responseMessage.append('\n').append("<-- END HTTP (binary ").append(buffer.size())
                        .append("-byte body omitted)");
                logger.log(responseMessage.toString());
                return response;
            }

            if (contentLength != 0) {
                responseMessage.append('\n').append(buffer.clone().readString(charset)).append('\n');
            }

            responseMessage.append("<-- END HTTP (").append(buffer.size()).append("-byte body)\n");
        }
    }

    logger.log(responseMessage.substring(0, responseMessage.length() - 1));
    return response;
}

From source file:org.quantumbadger.redreader.http.okhttp.OKHTTPBackend.java

License:Open Source License

@Override
public Request prepareRequest(final Context context, final RequestDetails details) {

    final com.squareup.okhttp.Request.Builder builder = new com.squareup.okhttp.Request.Builder();

    builder.header("User-Agent", Constants.ua(context));

    final List<PostField> postFields = details.getPostFields();

    if (postFields != null) {
        builder.post(RequestBody.create(MediaType.parse("application/x-www-form-urlencoded"),
                PostField.encodeList(postFields)));

    } else {/*from  w w  w  . j ava2  s  .c o  m*/
        builder.get();
    }

    builder.url(details.getUrl().toString());
    builder.cacheControl(CacheControl.FORCE_NETWORK);

    final AtomicReference<Call> callRef = new AtomicReference<>();

    return new Request() {

        public void executeInThisThread(final Listener listener) {

            final Call call = mClient.newCall(builder.build());
            callRef.set(call);

            try {

                final Response response;

                try {
                    response = call.execute();
                } catch (IOException e) {
                    listener.onError(CacheRequest.REQUEST_FAILURE_CONNECTION, e, null);
                    return;
                }

                final int status = response.code();

                if (status == 200 || status == 202) {

                    final ResponseBody body = response.body();
                    final InputStream bodyStream;
                    final Long bodyBytes;

                    if (body != null) {
                        bodyStream = body.byteStream();
                        bodyBytes = body.contentLength();

                    } else {
                        // TODO error
                        bodyStream = null;
                        bodyBytes = null;
                    }

                    final String contentType = response.header("Content-Type");

                    listener.onSuccess(contentType, bodyBytes, bodyStream);

                } else {
                    listener.onError(CacheRequest.REQUEST_FAILURE_REQUEST, null, status);
                }

            } catch (Throwable t) {
                listener.onError(CacheRequest.REQUEST_FAILURE_CONNECTION, t, null);
            }
        }

        @Override
        public void cancel() {
            final Call call = callRef.getAndSet(null);
            if (call != null) {
                call.cancel();
            }
        }

        @Override
        public void addHeader(final String name, final String value) {
            builder.addHeader(name, value);
        }
    };
}

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  w  w .  j av a  2  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, ?> 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:retrofit.CallTest.java

License:Apache License

@Test
public void rawResponseContentTypeAndLengthButNoSource() throws IOException {
    Retrofit retrofit = new Retrofit.Builder().baseUrl(server.url("/"))
            .addConverterFactory(new ToStringConverterFactory()).build();
    Service example = retrofit.create(Service.class);

    server.enqueue(new MockResponse().setBody("Hi").addHeader("Content-Type", "text/greeting"));

    Response<String> response = example.getString().execute();
    assertThat(response.body()).isEqualTo("Hi");
    ResponseBody rawBody = response.raw().body();
    assertThat(rawBody.contentLength()).isEqualTo(2);
    assertThat(rawBody.contentType().toString()).isEqualTo("text/greeting");
    try {//from   w  w  w .j  a va  2s  . com
        rawBody.source();
        fail();
    } catch (IllegalStateException e) {
        assertThat(e).hasMessage("Cannot read raw response body of a converted body.");
    }
}

From source file:retrofit.CallTest.java

License:Apache License

@Test
public void emptyResponse() throws IOException {
    Retrofit retrofit = new Retrofit.Builder().baseUrl(server.url("/"))
            .addConverterFactory(new ToStringConverterFactory()).build();
    Service example = retrofit.create(Service.class);

    server.enqueue(new MockResponse().setBody("").addHeader("Content-Type", "text/stringy"));

    Response<String> response = example.getString().execute();
    assertThat(response.body()).isEqualTo("");
    ResponseBody rawBody = response.raw().body();
    assertThat(rawBody.contentLength()).isEqualTo(0);
    assertThat(rawBody.contentType().toString()).isEqualTo("text/stringy");
}

From source file:retrofit.KOkHttpCall.java

License:Apache License

private Response<T> parseResponse(com.squareup.okhttp.Response rawResponse, com.squareup.okhttp.Request request)
        throws IOException {
    ResponseBody rawBody = rawResponse.body();

    // Remove the body's source (the only stateful object) so we can pass the response along.
    rawResponse = rawResponse.newBuilder()
            .body(new NoContentResponseBody(rawBody.contentType(), rawBody.contentLength())).build();

    int code = rawResponse.code();
    if (code < 200 || code >= 300) {
        try {//from  ww w.j  a  v  a 2  s  .c  om
            // Buffer the entire body to avoid future I/O.
            ResponseBody bufferedBody = Utils.readBodyToBytesIfNecessary(rawBody);
            return Response.error(bufferedBody, rawResponse);
        } finally {
            closeQuietly(rawBody);
        }
    }

    if (code == 204 || code == 205) {
        return Response.success(null, rawResponse);
    }

    ExceptionCatchingRequestBody catchingBody = new ExceptionCatchingRequestBody(rawBody);
    try {

        T body;
        if (responseConverter instanceof KGsonConverter) {
            KGsonConverter<T> converter = (KGsonConverter<T>) responseConverter;
            body = converter.fromBody(catchingBody, request);
        } else {
            body = responseConverter.fromBody(catchingBody);
        }
        return Response.success(body, rawResponse);
    } catch (RuntimeException e) {
        // If the underlying source threw an exception, propagate that rather than indicating it was
        // a runtime exception.
        catchingBody.throwIfCaught();
        throw e;
    }
}

From source file:retrofit.OkHttpCall.java

License:Apache License

private Response<T> parseResponse(com.squareup.okhttp.Response rawResponse) throws IOException {
    ResponseBody rawBody = rawResponse.body();

    // Remove the body's source (the only stateful object) so we can pass the response along.
    rawResponse = rawResponse.newBuilder()
            .body(new NoContentResponseBody(rawBody.contentType(), rawBody.contentLength())).build();

    int code = rawResponse.code();
    if (code < 200 || code >= 300) {
        try {//  www . jav a2 s .  c  om
            // Buffer the entire body to avoid future I/O.
            ResponseBody bufferedBody = Utils.readBodyToBytesIfNecessary(rawBody);
            return Response.error(bufferedBody, rawResponse);
        } finally {
            closeQuietly(rawBody);
        }
    }

    if (code == 204 || code == 205) {
        return Response.success(null, rawResponse);
    }

    ExceptionCatchingRequestBody catchingBody = new ExceptionCatchingRequestBody(rawBody);
    try {
        T body = responseConverter.convert(catchingBody);
        return Response.success(body, rawResponse);
    } catch (RuntimeException e) {
        // If the underlying source threw an exception, propagate that rather than indicating it was
        // a runtime exception.
        catchingBody.throwIfCaught();
        throw e;
    }
}