Search in sources :

Example 46 with RequestBody

use of okhttp3.RequestBody in project okhttp by square.

the class OkHttpURLConnection method getResponse.

/**
   * Aggressively tries to get the final HTTP response, potentially making many HTTP requests in the
   * process in order to cope with redirects and authentication.
   */
private Response getResponse(boolean networkResponseOnError) throws IOException {
    synchronized (lock) {
        if (response != null)
            return response;
        if (callFailure != null) {
            if (networkResponseOnError && networkResponse != null)
                return networkResponse;
            throw propagate(callFailure);
        }
    }
    Call call = buildCall();
    networkInterceptor.proceed();
    OutputStreamRequestBody requestBody = (OutputStreamRequestBody) call.request().body();
    if (requestBody != null)
        requestBody.outputStream().close();
    if (executed) {
        synchronized (lock) {
            try {
                while (response == null && callFailure == null) {
                    // Wait until the response is returned or the call fails.
                    lock.wait();
                }
            } catch (InterruptedException e) {
                throw new InterruptedIOException();
            }
        }
    } else {
        executed = true;
        try {
            onResponse(call, call.execute());
        } catch (IOException e) {
            onFailure(call, e);
        }
    }
    synchronized (lock) {
        if (callFailure != null)
            throw propagate(callFailure);
        if (response != null)
            return response;
    }
    throw new AssertionError();
}
Also used : Call(okhttp3.Call) InterruptedIOException(java.io.InterruptedIOException) InterruptedIOException(java.io.InterruptedIOException) IOException(java.io.IOException)

Example 47 with RequestBody

use of okhttp3.RequestBody in project Fast-Android-Networking by amitshekhariitbhu.

the class GzipRequestInterceptor method forceContentLength.

private RequestBody forceContentLength(final RequestBody requestBody) throws IOException {
    final Buffer buffer = new Buffer();
    requestBody.writeTo(buffer);
    return new RequestBody() {

        @Override
        public MediaType contentType() {
            return requestBody.contentType();
        }

        @Override
        public long contentLength() {
            return buffer.size();
        }

        @Override
        public void writeTo(BufferedSink sink) throws IOException {
            sink.write(buffer.snapshot());
        }
    };
}
Also used : Buffer(okio.Buffer) BufferedSink(okio.BufferedSink) RequestBody(okhttp3.RequestBody)

Example 48 with RequestBody

use of okhttp3.RequestBody in project Fast-Android-Networking by amitshekhariitbhu.

the class GzipRequestInterceptor method gzip.

private RequestBody gzip(final RequestBody body) {
    return new RequestBody() {

        @Override
        public MediaType contentType() {
            return body.contentType();
        }

        @Override
        public long contentLength() {
            // We don't know the compressed length in advance!
            return -1;
        }

        @Override
        public void writeTo(BufferedSink sink) throws IOException {
            BufferedSink gzipSink = Okio.buffer(new GzipSink(sink));
            body.writeTo(gzipSink);
            gzipSink.close();
        }
    };
}
Also used : GzipSink(okio.GzipSink) BufferedSink(okio.BufferedSink) RequestBody(okhttp3.RequestBody)

Example 49 with RequestBody

use of okhttp3.RequestBody 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 50 with RequestBody

use of okhttp3.RequestBody in project Fast-Android-Networking by amitshekhariitbhu.

the class InternalNetworking method performSimpleRequest.

public static Response performSimpleRequest(ANRequest request) throws ANError {
    Request okHttpRequest;
    Response okHttpResponse;
    try {
        Request.Builder builder = new Request.Builder().url(request.getUrl());
        addHeadersToRequestBuilder(builder, request);
        RequestBody requestBody = null;
        switch(request.getMethod()) {
            case GET:
                {
                    builder = builder.get();
                    break;
                }
            case POST:
                {
                    requestBody = request.getRequestBody();
                    builder = builder.post(requestBody);
                    break;
                }
            case PUT:
                {
                    requestBody = request.getRequestBody();
                    builder = builder.put(requestBody);
                    break;
                }
            case DELETE:
                {
                    requestBody = request.getRequestBody();
                    builder = builder.delete(requestBody);
                    break;
                }
            case HEAD:
                {
                    builder = builder.head();
                    break;
                }
            case PATCH:
                {
                    requestBody = request.getRequestBody();
                    builder = builder.patch(requestBody);
                    break;
                }
        }
        if (request.getCacheControl() != null) {
            builder.cacheControl(request.getCacheControl());
        }
        okHttpRequest = builder.build();
        if (request.getOkHttpClient() != null) {
            request.setCall(request.getOkHttpClient().newBuilder().cache(sHttpClient.cache()).build().newCall(okHttpRequest));
        } else {
            request.setCall(sHttpClient.newCall(okHttpRequest));
        }
        final long startTime = System.currentTimeMillis();
        final long startBytes = TrafficStats.getTotalRxBytes();
        okHttpResponse = request.getCall().execute();
        final long timeTaken = System.currentTimeMillis() - startTime;
        if (okHttpResponse.cacheResponse() == null) {
            final long finalBytes = TrafficStats.getTotalRxBytes();
            final long diffBytes;
            if (startBytes == TrafficStats.UNSUPPORTED || finalBytes == TrafficStats.UNSUPPORTED) {
                diffBytes = okHttpResponse.body().contentLength();
            } else {
                diffBytes = finalBytes - startBytes;
            }
            ConnectionClassManager.getInstance().updateBandwidth(diffBytes, timeTaken);
            Utils.sendAnalytics(request.getAnalyticsListener(), timeTaken, (requestBody != null && requestBody.contentLength() != 0) ? requestBody.contentLength() : -1, okHttpResponse.body().contentLength(), false);
        } else if (request.getAnalyticsListener() != null) {
            if (okHttpResponse.networkResponse() == null) {
                Utils.sendAnalytics(request.getAnalyticsListener(), timeTaken, 0, 0, true);
            } else {
                Utils.sendAnalytics(request.getAnalyticsListener(), timeTaken, (requestBody != null && requestBody.contentLength() != 0) ? requestBody.contentLength() : -1, 0, true);
            }
        }
    } catch (IOException ioe) {
        throw new ANError(ioe);
    }
    return okHttpResponse;
}
Also used : Response(okhttp3.Response) Request(okhttp3.Request) ANRequest(com.androidnetworking.common.ANRequest) IOException(java.io.IOException) ANError(com.androidnetworking.error.ANError) RequestBody(okhttp3.RequestBody)

Aggregations

RequestBody (okhttp3.RequestBody)178 Request (okhttp3.Request)141 IOException (java.io.IOException)75 Response (okhttp3.Response)74 Test (org.junit.Test)53 ResponseBody (okhttp3.ResponseBody)32 Call (okhttp3.Call)31 MultipartBody (okhttp3.MultipartBody)28 MediaType (okhttp3.MediaType)27 FormBody (okhttp3.FormBody)25 Callback (okhttp3.Callback)23 Buffer (okio.Buffer)23 MockResponse (okhttp3.mockwebserver.MockResponse)18 RecordedRequest (okhttp3.mockwebserver.RecordedRequest)16 TestClients.clientRequest (keywhiz.TestClients.clientRequest)15 BufferedSink (okio.BufferedSink)15 Headers (okhttp3.Headers)12 HttpUrl (okhttp3.HttpUrl)11 JSONObject (org.json.JSONObject)11 Body (retrofit2.http.Body)11