Example usage for com.squareup.okhttp Request httpUrl

List of usage examples for com.squareup.okhttp Request httpUrl

Introduction

In this page you can find the example usage for com.squareup.okhttp Request httpUrl.

Prototype

public HttpUrl httpUrl() 

Source Link

Usage

From source file:io.fabric8.docker.client.utils.HttpClientUtils.java

License:Apache License

public static OkHttpClient createHttpClient(final Config config) {
    try {// w ww  .j ava2  s . co  m
        OkHttpClient httpClient = new OkHttpClient();

        httpClient.setConnectionPool(ConnectionPool.getDefault());
        // Follow any redirects
        httpClient.setFollowRedirects(true);
        httpClient.setFollowSslRedirects(true);

        if (config.isTrustCerts()) {
            httpClient.setHostnameVerifier(new HostnameVerifier() {
                @Override
                public boolean verify(String s, SSLSession sslSession) {
                    return true;
                }
            });
        }

        if (usesUnixSocket(config)) {
            URL masterURL = new URL(config.getDockerUrl().replaceFirst(UNIX_SCHEME, FILE_SCHEME));
            httpClient.setSocketFactory(new UnixSocketFactory(masterURL.getFile()));
            config.setDockerUrl(UNIX_FAKE_URL);
        }

        TrustManager[] trustManagers = SSLUtils.trustManagers(config);
        KeyManager[] keyManagers = SSLUtils.keyManagers(config);

        if (keyManagers != null || trustManagers != null || config.isTrustCerts()) {
            try {
                SSLContext sslContext = SSLUtils.sslContext(keyManagers, trustManagers, config.isTrustCerts());
                httpClient.setSslSocketFactory(sslContext.getSocketFactory());
            } catch (GeneralSecurityException e) {
                throw new AssertionError(); // The system has no TLS. Just give up.
            }
        }

        if (isNotNullOrEmpty(config.getUsername()) && isNotNullOrEmpty(config.getPassword())) {
            httpClient.setAuthenticator(new Authenticator() {

                @Override
                public Request authenticate(Proxy proxy, Response response) throws IOException {
                    List<Challenge> challenges = response.challenges();
                    Request request = response.request();
                    HttpUrl url = request.httpUrl();
                    for (int i = 0, size = challenges.size(); i < size; i++) {
                        Challenge challenge = challenges.get(i);
                        if (!"Basic".equalsIgnoreCase(challenge.getScheme()))
                            continue;

                        String credential = Credentials.basic(config.getUsername(), config.getPassword());
                        return request.newBuilder().header("Authorization", credential).build();
                    }
                    return null;
                }

                @Override
                public Request authenticateProxy(Proxy proxy, Response response) throws IOException {
                    return null;
                }
            });
        } else if (config.getOauthToken() != null) {
            httpClient.interceptors().add(new Interceptor() {
                @Override
                public Response intercept(Chain chain) throws IOException {
                    Request authReq = chain.request().newBuilder()
                            .addHeader("Authorization", "Bearer " + config.getOauthToken()).build();
                    return chain.proceed(authReq);
                }
            });
        }

        Logger reqLogger = LoggerFactory.getLogger(HttpLoggingInterceptor.class);
        if (reqLogger.isTraceEnabled()) {
            HttpLoggingInterceptor loggingInterceptor = new HttpLoggingInterceptor();
            loggingInterceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
            httpClient.networkInterceptors().add(loggingInterceptor);
        }

        if (config.getConnectionTimeout() > 0) {
            httpClient.setConnectTimeout(config.getConnectionTimeout(), TimeUnit.MILLISECONDS);
        }

        if (config.getRequestTimeout() > 0) {
            httpClient.setReadTimeout(config.getRequestTimeout(), TimeUnit.MILLISECONDS);
        }

        // Only check proxy if it's a full URL with protocol
        if (config.getDockerUrl().toLowerCase().startsWith(Config.HTTP_PROTOCOL_PREFIX)
                || config.getDockerUrl().startsWith(Config.HTTPS_PROTOCOL_PREFIX)) {
            try {
                URL proxyUrl = getProxyUrl(config);
                if (proxyUrl != null) {
                    httpClient.setProxy(new Proxy(Proxy.Type.HTTP,
                            new InetSocketAddress(proxyUrl.getHost(), proxyUrl.getPort())));
                }
            } catch (MalformedURLException e) {
                throw new DockerClientException("Invalid proxy server configuration", e);
            }
        }

        return httpClient;
    } catch (Exception e) {
        throw DockerClientException.launderThrowable(e);
    }
}

From source file:io.fabric8.kubernetes.client.utils.HttpClientUtils.java

License:Apache License

public static OkHttpClient createHttpClient(final Config config) {
    try {/*from ww w  .jav  a  2  s . com*/
        OkHttpClient httpClient = new OkHttpClient();

        // Follow any redirects
        httpClient.setFollowRedirects(true);
        httpClient.setFollowSslRedirects(true);

        if (config.isTrustCerts()) {
            httpClient.setHostnameVerifier(new HostnameVerifier() {
                @Override
                public boolean verify(String s, SSLSession sslSession) {
                    return true;
                }
            });
        }

        TrustManager[] trustManagers = SSLUtils.trustManagers(config);
        KeyManager[] keyManagers = SSLUtils.keyManagers(config);

        if (keyManagers != null || trustManagers != null || config.isTrustCerts()) {
            try {
                SSLContext sslContext = SSLUtils.sslContext(keyManagers, trustManagers, config.isTrustCerts());
                httpClient.setSslSocketFactory(sslContext.getSocketFactory());
            } catch (GeneralSecurityException e) {
                throw new AssertionError(); // The system has no TLS. Just give up.
            }
        }

        if (isNotNullOrEmpty(config.getUsername()) && isNotNullOrEmpty(config.getPassword())) {
            httpClient.setAuthenticator(new Authenticator() {

                @Override
                public Request authenticate(Proxy proxy, Response response) throws IOException {
                    List<Challenge> challenges = response.challenges();
                    Request request = response.request();
                    HttpUrl url = request.httpUrl();
                    for (int i = 0, size = challenges.size(); i < size; i++) {
                        Challenge challenge = challenges.get(i);
                        if (!"Basic".equalsIgnoreCase(challenge.getScheme()))
                            continue;

                        String credential = Credentials.basic(config.getUsername(), config.getPassword());
                        return request.newBuilder().header("Authorization", credential).build();
                    }
                    return null;
                }

                @Override
                public Request authenticateProxy(Proxy proxy, Response response) throws IOException {
                    return null;
                }
            });
        } else if (config.getOauthToken() != null) {
            httpClient.interceptors().add(new Interceptor() {
                @Override
                public Response intercept(Chain chain) throws IOException {
                    Request authReq = chain.request().newBuilder()
                            .addHeader("Authorization", "Bearer " + config.getOauthToken()).build();
                    return chain.proceed(authReq);
                }
            });
        }

        Logger reqLogger = LoggerFactory.getLogger(HttpLoggingInterceptor.class);
        if (reqLogger.isTraceEnabled()) {
            HttpLoggingInterceptor loggingInterceptor = new HttpLoggingInterceptor();
            loggingInterceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
            httpClient.networkInterceptors().add(loggingInterceptor);
        }

        if (config.getConnectionTimeout() > 0) {
            httpClient.setConnectTimeout(config.getConnectionTimeout(), TimeUnit.MILLISECONDS);
        }

        if (config.getRequestTimeout() > 0) {
            httpClient.setReadTimeout(config.getRequestTimeout(), TimeUnit.MILLISECONDS);
        }

        // Only check proxy if it's a full URL with protocol
        if (config.getMasterUrl().toLowerCase().startsWith(Config.HTTP_PROTOCOL_PREFIX)
                || config.getMasterUrl().startsWith(Config.HTTPS_PROTOCOL_PREFIX)) {
            try {
                URL proxyUrl = getProxyUrl(config);
                if (proxyUrl != null) {
                    httpClient.setProxy(new Proxy(Proxy.Type.HTTP,
                            new InetSocketAddress(proxyUrl.getHost(), proxyUrl.getPort())));
                }
            } catch (MalformedURLException e) {
                throw new KubernetesClientException("Invalid proxy server configuration", e);
            }
        }

        if (config.getUserAgent() != null && !config.getUserAgent().isEmpty()) {
            httpClient.networkInterceptors().add(new Interceptor() {
                @Override
                public Response intercept(Chain chain) throws IOException {
                    Request agent = chain.request().newBuilder().header("User-Agent", config.getUserAgent())
                            .build();
                    return chain.proceed(agent);
                }
            });
        }

        return httpClient;
    } catch (Exception e) {
        throw KubernetesClientException.launderThrowable(e);
    }
}

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);
    }//from  w w  w.  j a  v a  2 s.  c  o m

    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:io.minio.errors.ErrorResponseException.java

License:Apache License

@Override
public String toString() {
    Request request = response.request();
    return "error occured\n" + errorResponse.getString() + "\n" + "request={" + "method=" + request.method()
            + ", " + "url=" + request.httpUrl() + ", " + "headers=" + request.headers() + "}\n" + "response={"
            + "code=" + response.code() + ", " + "headers=" + response.headers() + "}\n";
}

From source file:io.minio.MinioClient.java

License:Apache License

/**
 * Executes given request parameters.//from  w ww . ja  v a2 s  .c  om
 *
 * @param method         HTTP method.
 * @param region         Amazon S3 region of the bucket.
 * @param bucketName     Bucket name.
 * @param objectName     Object name in the bucket.
 * @param headerMap      Map of HTTP headers for the request.
 * @param queryParamMap  Map of HTTP query parameters of the request.
 * @param contentType    Content type of the request body.
 * @param body           HTTP request body.
 * @param length         Length of HTTP request body.
 */
private HttpResponse execute(Method method, String region, String bucketName, String objectName,
        Map<String, String> headerMap, Map<String, String> queryParamMap, String contentType, Object body,
        int length) throws InvalidBucketNameException, NoSuchAlgorithmException, InsufficientDataException,
        IOException, InvalidKeyException, NoResponseException, XmlPullParserException, ErrorResponseException,
        InternalException {
    Request request = createRequest(method, bucketName, objectName, region, headerMap, queryParamMap,
            contentType, body, length);

    if (this.accessKey != null && this.secretKey != null) {
        request = Signer.signV4(request, region, accessKey, secretKey);
    }

    if (this.traceStream != null) {
        this.traceStream.println("---------START-HTTP---------");
        String encodedPath = request.httpUrl().encodedPath();
        String encodedQuery = request.httpUrl().encodedQuery();
        if (encodedQuery != null) {
            encodedPath += "?" + encodedQuery;
        }
        this.traceStream.println(request.method() + " " + encodedPath + " HTTP/1.1");
        String headers = request.headers().toString().replaceAll("Signature=([0-9a-f]+)",
                "Signature=*REDACTED*");
        this.traceStream.println(headers);
    }

    Response response = this.httpClient.newCall(request).execute();
    if (response == null) {
        if (this.traceStream != null) {
            this.traceStream.println("<NO RESPONSE>");
            this.traceStream.println(END_HTTP);
        }
        throw new NoResponseException();
    }

    if (this.traceStream != null) {
        this.traceStream.println(response.protocol().toString().toUpperCase() + " " + response.code());
        this.traceStream.println(response.headers());
    }

    ResponseHeader header = new ResponseHeader();
    HeaderParser.set(response.headers(), header);

    if (response.isSuccessful()) {
        if (this.traceStream != null) {
            this.traceStream.println(END_HTTP);
        }
        return new HttpResponse(header, response);
    }

    ErrorResponse errorResponse = null;

    // HEAD returns no body, and fails on parseXml
    if (!method.equals(Method.HEAD)) {
        try {
            String errorXml = "";

            // read entire body stream to string.
            Scanner scanner = new java.util.Scanner(response.body().charStream()).useDelimiter("\\A");
            if (scanner.hasNext()) {
                errorXml = scanner.next();
            }

            errorResponse = new ErrorResponse(new StringReader(errorXml));

            if (this.traceStream != null) {
                this.traceStream.println(errorXml);
            }
        } finally {
            response.body().close();
        }
    }

    if (this.traceStream != null) {
        this.traceStream.println(END_HTTP);
    }

    if (errorResponse == null) {
        ErrorCode ec;
        switch (response.code()) {
        case 400:
            ec = ErrorCode.INVALID_URI;
            break;
        case 404:
            if (objectName != null) {
                ec = ErrorCode.NO_SUCH_KEY;
            } else if (bucketName != null) {
                ec = ErrorCode.NO_SUCH_BUCKET;
            } else {
                ec = ErrorCode.RESOURCE_NOT_FOUND;
            }
            break;
        case 501:
        case 405:
            ec = ErrorCode.METHOD_NOT_ALLOWED;
            break;
        case 409:
            if (bucketName != null) {
                ec = ErrorCode.NO_SUCH_BUCKET;
            } else {
                ec = ErrorCode.RESOURCE_CONFLICT;
            }
            break;
        case 403:
            ec = ErrorCode.ACCESS_DENIED;
            break;
        default:
            throw new InternalException("unhandled HTTP code " + response.code()
                    + ".  Please report this issue at " + "https://github.com/minio/minio-java/issues");
        }

        errorResponse = new ErrorResponse(ec, bucketName, objectName, request.httpUrl().encodedPath(),
                header.xamzRequestId(), header.xamzId2());
    }

    // invalidate region cache if needed
    if (errorResponse.errorCode() == ErrorCode.NO_SUCH_BUCKET) {
        BucketRegionCache.INSTANCE.remove(bucketName);
        // TODO: handle for other cases as well
        // observation: on HEAD of a bucket with wrong region gives 400 without body
    }

    throw new ErrorResponseException(errorResponse, response);
}

From source file:mobi.lab.sample_event_logging_library.service.LogPostService.java

License:Open Source License

@Override
public void onCreate() {
    super.onCreate();
    //TODO: starting from Android 5.0 we could use JobScheduler (currently not in support libraries)
    handler = new Handler();
    handler.postDelayed(timedRunnable, Config.MAX_TIME_INTERVAL_BETWEEN_REQUESTS);
    logEventsForRequest = new ArrayList<>();

    OkHttpClient client = new OkHttpClient();
    client.interceptors().add(new Interceptor() {
        @Override//from  w w w  .  j  a v a  2 s  .c o m
        public com.squareup.okhttp.Response intercept(Chain chain) throws IOException {
            Request request = chain.request();
            Log.d(TAG, String.format("\n\nrequest:%s\nheaders:%s\n" + "url:%s", request.body().toString(),
                    request.headers(), request.httpUrl().toString()));
            return chain.proceed(request);
        }
    });

    Retrofit retrofit = new Retrofit.Builder().baseUrl(Network.BASE_API_URL)
            .addConverterFactory(GsonConverterFactory.create()).client(client).build();

    logEventService = retrofit.create(LogEventRequest.class);

    if (checkCallingOrSelfPermission(
            Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED
            && checkCallingOrSelfPermission(
                    Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
        //TODO: ask for permission if not given
        Log.d(TAG, "location permission not granted");
        isLocationServicesEnabled = false;
        return;
    }
    isLocationServicesEnabled = true;
    final LocationManager locationManager = (LocationManager) getApplicationContext()
            .getSystemService(Context.LOCATION_SERVICE);
    final Criteria criteria = new Criteria();
    criteria.setAccuracy(Criteria.ACCURACY_FINE);
    Log.d(TAG, "requesting user location");
    locationManager.requestLocationUpdates(Config.LOCATION_UPDATES_MIN_TIME,
            Config.LOCATION_UPDATES_MIN_DISTANCE, criteria, this, null);
}

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);
    }/* w ww.  j ava  2s .  c  o m*/

    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:pedroscott.com.popularmoviesapp.rest.RestClientPublic.java

License:Apache License

private OkHttpClient getClient() {
    OkHttpClient client = new OkHttpClient();
    HttpLoggingInterceptor interceptor = new HttpLoggingInterceptor();
    interceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
    client.interceptors().add(interceptor);
    client.networkInterceptors().add(new Interceptor() {
        @Override/*from ww  w  .j  ava 2 s.c  o m*/
        public Response intercept(Chain chain) throws IOException {
            Request request = chain.request();
            HttpUrl url = request.httpUrl().newBuilder().addQueryParameter("api_key", key).build();
            request = request.newBuilder().url(url).build();
            return chain.proceed(request);
        }
    });
    client.networkInterceptors().add(new StethoInterceptor());
    return client;
}