Search in sources :

Example 11 with BufferedSource

use of okio.BufferedSource in project Fast-Android-Networking by amitshekhariitbhu.

the class HttpLoggingInterceptor method intercept.

@Override
public Response intercept(Chain chain) throws IOException {
    Level level = this.level;
    Request request = chain.request();
    if (level == Level.NONE) {
        return chain.proceed(request);
    }
    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.protocol() : 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) {
            // 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 || !HttpHeaders.hasBody(response)) {
            logger.log("<-- END HTTP");
        } else if (bodyEncoded(response.headers())) {
            logger.log("<-- END HTTP (encoded body omitted)");
        } else {
            BufferedSource source = responseBody.source();
            // Buffer the entire body.
            source.request(Long.MAX_VALUE);
            Buffer buffer = source.buffer();
            Charset charset = UTF8;
            MediaType contentType = responseBody.contentType();
            if (contentType != null) {
                charset = contentType.charset(UTF8);
            }
            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;
}
Also used : Buffer(okio.Buffer) HttpHeaders(okhttp3.internal.http.HttpHeaders) Headers(okhttp3.Headers) Request(okhttp3.Request) Connection(okhttp3.Connection) Charset(java.nio.charset.Charset) IOException(java.io.IOException) EOFException(java.io.EOFException) ResponseBody(okhttp3.ResponseBody) Response(okhttp3.Response) MediaType(okhttp3.MediaType) Protocol(okhttp3.Protocol) RequestBody(okhttp3.RequestBody) BufferedSource(okio.BufferedSource)

Example 12 with BufferedSource

use of okio.BufferedSource in project okhttp by square.

the class ResponseBodyTest method sourceEmpty.

@Test
public void sourceEmpty() throws IOException {
    ResponseBody body = body("");
    BufferedSource source = body.source();
    assertTrue(source.exhausted());
    assertEquals("", source.readUtf8());
}
Also used : BufferedSource(okio.BufferedSource) Test(org.junit.Test)

Example 13 with BufferedSource

use of okio.BufferedSource in project okhttp by square.

the class SocksProxy method service.

private void service(final Socket from) {
    executor.execute(new NamedRunnable("SocksProxy %s", from.getRemoteSocketAddress()) {

        @Override
        protected void execute() {
            try {
                BufferedSource fromSource = Okio.buffer(Okio.source(from));
                BufferedSink fromSink = Okio.buffer(Okio.sink(from));
                hello(fromSource, fromSink);
                acceptCommand(from.getInetAddress(), fromSource, fromSink);
            } catch (IOException e) {
                logger.log(Level.WARNING, name + " failed", e);
                Util.closeQuietly(from);
            }
        }
    });
}
Also used : BufferedSink(okio.BufferedSink) IOException(java.io.IOException) NamedRunnable(okhttp3.internal.NamedRunnable) BufferedSource(okio.BufferedSource)

Example 14 with BufferedSource

use of okio.BufferedSource in project okhttp by square.

the class Response method peekBody.

/**
   * Peeks up to {@code byteCount} bytes from the response body and returns them as a new response
   * body. If fewer than {@code byteCount} bytes are in the response body, the full response body is
   * returned. If more than {@code byteCount} bytes are in the response body, the returned value
   * will be truncated to {@code byteCount} bytes.
   *
   * <p>It is an error to call this method after the body has been consumed.
   *
   * <p><strong>Warning:</strong> this method loads the requested bytes into memory. Most
   * applications should set a modest limit on {@code byteCount}, such as 1 MiB.
   */
public ResponseBody peekBody(long byteCount) throws IOException {
    BufferedSource source = body.source();
    source.request(byteCount);
    Buffer copy = source.buffer().clone();
    // There may be more than byteCount bytes in source.buffer(). If there is, return a prefix.
    Buffer result;
    if (copy.size() > byteCount) {
        result = new Buffer();
        result.write(copy, byteCount);
        copy.clear();
    } else {
        result = copy;
    }
    return ResponseBody.create(body.contentType(), result.size(), result);
}
Also used : Buffer(okio.Buffer) BufferedSource(okio.BufferedSource)

Example 15 with BufferedSource

use of okio.BufferedSource in project okhttp by square.

the class ResponseBody method bytes.

/**
   * Returns the response as a byte array.
   *
   * <p>This method loads entire response body into memory. If the response body is very large this
   * may trigger an {@link OutOfMemoryError}. Prefer to stream the response body if this is a
   * possibility for your response.
   */
public final byte[] bytes() throws IOException {
    long contentLength = contentLength();
    if (contentLength > Integer.MAX_VALUE) {
        throw new IOException("Cannot buffer entire body for content length: " + contentLength);
    }
    BufferedSource source = source();
    byte[] bytes;
    try {
        bytes = source.readByteArray();
    } finally {
        Util.closeQuietly(source);
    }
    if (contentLength != -1 && contentLength != bytes.length) {
        throw new IOException("Content-Length (" + contentLength + ") and stream length (" + bytes.length + ") disagree");
    }
    return bytes;
}
Also used : IOException(java.io.IOException) BufferedSource(okio.BufferedSource)

Aggregations

BufferedSource (okio.BufferedSource)72 Test (org.junit.Test)33 Buffer (okio.Buffer)21 IOException (java.io.IOException)19 Request (okhttp3.Request)8 Response (okhttp3.Response)8 BarCode (com.nytimes.android.external.store.base.impl.BarCode)7 MockResponse (okhttp3.mockwebserver.MockResponse)7 EOFException (java.io.EOFException)6 InputStream (java.io.InputStream)6 ResponseBody (okhttp3.ResponseBody)6 Gson (com.google.gson.Gson)4 File (java.io.File)4 Charset (java.nio.charset.Charset)4 Headers (okhttp3.Headers)4 MediaType (okhttp3.MediaType)4 RecordedRequest (okhttp3.mockwebserver.RecordedRequest)4 BufferedSink (okio.BufferedSink)4 Sink (okio.Sink)4 RequestBody (okhttp3.RequestBody)3