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: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);
    }/*from  www.jav 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() + ' ' + 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);
    }//from   www.jav  a2  s.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() + ' ' + 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

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

From source file:com.aix.city.comm.OkHttpStack.java

License:Open Source License

private static HttpEntity entityFromOkHttpResponse(Response r) throws IOException {
    BasicHttpEntity entity = new BasicHttpEntity();
    ResponseBody body = r.body();

    entity.setContent(body.byteStream());
    entity.setContentLength(body.contentLength());
    entity.setContentEncoding(r.header("Content-Encoding"));

    if (body.contentType() != null) {
        entity.setContentType(body.contentType().type());
    }//ww w . j ava  2  s .c o  m
    return entity;
}

From source file:com.androidso.lib.net.http.OkHttpStack.java

License:Open Source License

private static HttpEntity entityFromOkHttpResponse(Response r) throws IOException {
    BasicHttpEntity entity = new BasicHttpEntity() {
        @Override//from w  ww.j  a  v  a 2 s  . c o  m
        public void consumeContent() {
            //                getContent().close();

        }
    };
    ResponseBody body = r.body();

    entity.setContent(body.byteStream());
    entity.setContentLength(body.contentLength());
    entity.setContentEncoding(r.header("Content-Encoding"));

    if (body.contentType() != null) {
        entity.setContentType(body.contentType().type());
    }
    return entity;
}

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);
    }/*  ww  w.j a  va2  s  . com*/

    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.example.admin.angpangii.ext.OkHttpImageDownloader.java

License:Apache License

@Override
protected InputStream getStreamFromNetwork(String imageUri, Object extra) throws IOException {
    Request request = new Request.Builder().url(imageUri).build();
    ResponseBody responseBody = client.newCall(request).execute().body();
    InputStream inputStream = responseBody.byteStream();
    int contentLength = (int) responseBody.contentLength();
    return new ContentLengthInputStream(inputStream, contentLength);
}

From source file:com.example.ivy.picassodemo.MyOkHttpDownloader.java

License:Apache License

@Override
public Response load(Uri uri, int networkPolicy) throws IOException {
    CacheControl cacheControl = null;//from   ww w.  java  2s. co m
    if (networkPolicy != 0) {
        if (NetworkPolicy.isOfflineOnly(networkPolicy)) {
            cacheControl = CacheControl.FORCE_CACHE;
        } else {
            CacheControl.Builder builder = new CacheControl.Builder();
            if (!NetworkPolicy.shouldReadFromDiskCache(networkPolicy)) {
                builder.noCache();
            }
            if (!NetworkPolicy.shouldWriteToDiskCache(networkPolicy)) {
                builder.noStore();
            }
            cacheControl = builder.build();
        }
    }

    Request.Builder builder = new Request.Builder().url(uri.toString());
    if (cacheControl != null) {
        builder.cacheControl(cacheControl);
    }

    com.squareup.okhttp.Response response = client.newCall(builder.build()).execute();
    int responseCode = response.code();
    if (responseCode >= 300) {
        response.body().close();
        throw new ResponseException(responseCode + " " + response.message(), networkPolicy, responseCode);
    }

    boolean fromCache = response.cacheResponse() != null;

    ResponseBody responseBody = response.body();
    return new Response(responseBody.byteStream(), fromCache, responseBody.contentLength());
}

From source file:com.facebook.imagepipeline.backends.okhttp.OkHttpNetworkFetcher.java

License:Open Source License

@Override
public void fetch(final OkHttpNetworkFetchState fetchState, final Callback callback) {
    fetchState.submitTime = SystemClock.elapsedRealtime();
    final Uri uri = fetchState.getUri();
    final Request request = new Request.Builder().cacheControl(new CacheControl.Builder().noStore().build())
            .url(uri.toString()).get().build();
    final Call call = mOkHttpClient.newCall(request);

    fetchState.getContext().addCallbacks(new BaseProducerContextCallbacks() {
        @Override/*from  ww w .  j a  v a  2 s  . c  o  m*/
        public void onCancellationRequested() {
            if (Looper.myLooper() != Looper.getMainLooper()) {
                call.cancel();
            } else {
                mCancellationExecutor.execute(new Runnable() {
                    @Override
                    public void run() {
                        call.cancel();
                    }
                });
            }
        }
    });

    call.enqueue(new com.squareup.okhttp.Callback() {
        @Override
        public void onResponse(Response response) {
            fetchState.responseTime = SystemClock.elapsedRealtime();
            final ResponseBody body = response.body();
            try {
                long contentLength = body.contentLength();
                if (contentLength < 0) {
                    contentLength = 0;
                }
                callback.onResponse(body.byteStream(), (int) contentLength);
            } catch (Exception e) {
                handleException(call, e, callback);
            } finally {
                try {
                    body.close();
                } catch (Exception e) {
                    FLog.w(TAG, "Exception when closing response body", e);
                }
            }
        }

        @Override
        public void onFailure(final Request request, final IOException e) {
            handleException(call, e, callback);
        }
    });
}

From source file:com.facebook.imagepipeline.backends.okhttp.OkHttpNetworkFetchProducer.java

License:Open Source License

@Override
protected void fetchImage(final NfpRequestState requestState) {
    final Uri uri = requestState.getUri();
    final Request request = new Request.Builder().cacheControl(new CacheControl.Builder().noStore().build())
            .url(uri.toString()).get().build();
    final Call call = mOkHttpClient.newCall(request);

    if (mCancellable) {
        requestState.getContext().addCallbacks(new BaseProducerContextCallbacks() {
            @Override//from w  w  w .  j a  va  2  s. c o m
            public void onCancellationRequested() {
                call.cancel();
            }
        });
    }

    call.enqueue(new Callback() {
        @Override
        public void onResponse(Response response) {
            final ResponseBody body = response.body();
            try {
                long contentLength = body.contentLength();
                if (contentLength < 0) {
                    contentLength = 0;
                }
                processResult(requestState, body.byteStream(), (int) contentLength, false);
            } catch (IOException ioe) {
                handleException(call, requestState, ioe);
            } finally {
                try {
                    body.close();
                } catch (IOException ioe) {
                    FLog.w(TAG, "Exception when closing response body", ioe);
                }
            }
        }

        @Override
        public void onFailure(final Request request, final IOException e) {
            handleException(call, requestState, e);
        }
    });
}