Search in sources :

Example 1 with RealResponseBody

use of okhttp3.internal.http.RealResponseBody in project okhttp by square.

the class BridgeInterceptor method intercept.

@Override
public Response intercept(Chain chain) throws IOException {
    Request userRequest = chain.request();
    Request.Builder requestBuilder = userRequest.newBuilder();
    RequestBody body = userRequest.body();
    if (body != null) {
        MediaType contentType = body.contentType();
        if (contentType != null) {
            requestBuilder.header("Content-Type", contentType.toString());
        }
        long contentLength = body.contentLength();
        if (contentLength != -1) {
            requestBuilder.header("Content-Length", Long.toString(contentLength));
            requestBuilder.removeHeader("Transfer-Encoding");
        } else {
            requestBuilder.header("Transfer-Encoding", "chunked");
            requestBuilder.removeHeader("Content-Length");
        }
    }
    if (userRequest.header("Host") == null) {
        requestBuilder.header("Host", hostHeader(userRequest.url(), false));
    }
    if (userRequest.header("Connection") == null) {
        requestBuilder.header("Connection", "Keep-Alive");
    }
    // If we add an "Accept-Encoding: gzip" header field we're responsible for also decompressing
    // the transfer stream.
    boolean transparentGzip = false;
    if (userRequest.header("Accept-Encoding") == null && userRequest.header("Range") == null) {
        transparentGzip = true;
        requestBuilder.header("Accept-Encoding", "gzip");
    }
    List<Cookie> cookies = cookieJar.loadForRequest(userRequest.url());
    if (!cookies.isEmpty()) {
        requestBuilder.header("Cookie", cookieHeader(cookies));
    }
    if (userRequest.header("User-Agent") == null) {
        requestBuilder.header("User-Agent", Version.userAgent());
    }
    Response networkResponse = chain.proceed(requestBuilder.build());
    HttpHeaders.receiveHeaders(cookieJar, userRequest.url(), networkResponse.headers());
    Response.Builder responseBuilder = networkResponse.newBuilder().request(userRequest);
    if (transparentGzip && "gzip".equalsIgnoreCase(networkResponse.header("Content-Encoding")) && HttpHeaders.hasBody(networkResponse)) {
        GzipSource responseBody = new GzipSource(networkResponse.body().source());
        Headers strippedHeaders = networkResponse.headers().newBuilder().removeAll("Content-Encoding").removeAll("Content-Length").build();
        responseBuilder.headers(strippedHeaders);
        responseBuilder.body(new RealResponseBody(strippedHeaders, Okio.buffer(responseBody)));
    }
    return responseBuilder.build();
}
Also used : Cookie(okhttp3.Cookie) Headers(okhttp3.Headers) Request(okhttp3.Request) Response(okhttp3.Response) GzipSource(okio.GzipSource) MediaType(okhttp3.MediaType) RequestBody(okhttp3.RequestBody)

Example 2 with RealResponseBody

use of okhttp3.internal.http.RealResponseBody in project okhttp by square.

the class CacheInterceptor method cacheWritingResponse.

/**
   * Returns a new source that writes bytes to {@code cacheRequest} as they are read by the source
   * consumer. This is careful to discard bytes left over when the stream is closed; otherwise we
   * may never exhaust the source stream and therefore not complete the cached response.
   */
private Response cacheWritingResponse(final CacheRequest cacheRequest, Response response) throws IOException {
    // Some apps return a null body; for compatibility we treat that like a null cache request.
    if (cacheRequest == null)
        return response;
    Sink cacheBodyUnbuffered = cacheRequest.body();
    if (cacheBodyUnbuffered == null)
        return response;
    final BufferedSource source = response.body().source();
    final BufferedSink cacheBody = Okio.buffer(cacheBodyUnbuffered);
    Source cacheWritingSource = new Source() {

        boolean cacheRequestClosed;

        @Override
        public long read(Buffer sink, long byteCount) throws IOException {
            long bytesRead;
            try {
                bytesRead = source.read(sink, byteCount);
            } catch (IOException e) {
                if (!cacheRequestClosed) {
                    cacheRequestClosed = true;
                    // Failed to write a complete cache response.
                    cacheRequest.abort();
                }
                throw e;
            }
            if (bytesRead == -1) {
                if (!cacheRequestClosed) {
                    cacheRequestClosed = true;
                    // The cache response is complete!
                    cacheBody.close();
                }
                return -1;
            }
            sink.copyTo(cacheBody.buffer(), sink.size() - bytesRead, bytesRead);
            cacheBody.emitCompleteSegments();
            return bytesRead;
        }

        @Override
        public Timeout timeout() {
            return source.timeout();
        }

        @Override
        public void close() throws IOException {
            if (!cacheRequestClosed && !discard(this, HttpCodec.DISCARD_STREAM_TIMEOUT_MILLIS, MILLISECONDS)) {
                cacheRequestClosed = true;
                cacheRequest.abort();
            }
            source.close();
        }
    };
    return response.newBuilder().body(new RealResponseBody(response.headers(), Okio.buffer(cacheWritingSource))).build();
}
Also used : Buffer(okio.Buffer) Sink(okio.Sink) BufferedSink(okio.BufferedSink) RealResponseBody(okhttp3.internal.http.RealResponseBody) BufferedSink(okio.BufferedSink) IOException(java.io.IOException) Source(okio.Source) BufferedSource(okio.BufferedSource) BufferedSource(okio.BufferedSource)

Aggregations

IOException (java.io.IOException)1 Cookie (okhttp3.Cookie)1 Headers (okhttp3.Headers)1 MediaType (okhttp3.MediaType)1 Request (okhttp3.Request)1 RequestBody (okhttp3.RequestBody)1 Response (okhttp3.Response)1 RealResponseBody (okhttp3.internal.http.RealResponseBody)1 Buffer (okio.Buffer)1 BufferedSink (okio.BufferedSink)1 BufferedSource (okio.BufferedSource)1 GzipSource (okio.GzipSource)1 Sink (okio.Sink)1 Source (okio.Source)1