Example usage for com.squareup.okhttp Response headers

List of usage examples for com.squareup.okhttp Response headers

Introduction

In this page you can find the example usage for com.squareup.okhttp Response headers.

Prototype

Headers headers

To view the source code for com.squareup.okhttp Response headers.

Click Source Link

Usage

From source file:com.phattn.vnexpressnews.io.OkHttpStack.java

License:Open Source License

@Override
public HttpResponse performRequest(Request<?> request, Map<String, String> additionalHeaders)
        throws IOException, AuthFailureError {

    OkHttpClient client = mClient.clone();
    int timeoutMs = request.getTimeoutMs();
    client.setConnectTimeout(timeoutMs, TimeUnit.MILLISECONDS);
    client.setReadTimeout(timeoutMs, TimeUnit.MILLISECONDS);
    client.setWriteTimeout(timeoutMs, TimeUnit.MILLISECONDS);

    com.squareup.okhttp.Request.Builder okHttpRequestBuilder = new com.squareup.okhttp.Request.Builder();
    okHttpRequestBuilder.url(request.getUrl());

    Map<String, String> headers = request.getHeaders();
    for (final String name : headers.keySet()) {
        okHttpRequestBuilder.addHeader(name, headers.get(name));
    }/*w  w w .  j  av  a  2 s  .com*/
    for (final String name : additionalHeaders.keySet()) {
        okHttpRequestBuilder.addHeader(name, additionalHeaders.get(name));
    }

    setConnectionParametersForRequest(okHttpRequestBuilder, request);

    com.squareup.okhttp.Request okHttpRequest = okHttpRequestBuilder.build();
    Call okHttpCall = client.newCall(okHttpRequest);
    Response okHttpResponse = okHttpCall.execute();

    StatusLine responseStatus = new BasicStatusLine(parseProtocol(okHttpResponse.protocol()),
            okHttpResponse.code(), okHttpResponse.message());
    BasicHttpResponse response = new BasicHttpResponse(responseStatus);
    response.setEntity(entityFromOkHttpResponse(okHttpResponse));

    Headers responseHeaders = okHttpResponse.headers();
    for (int i = 0, length = responseHeaders.size(); i < length; i++) {
        final String name = responseHeaders.name(i);
        final String value = responseHeaders.value(i);
        if (name != null) {
            response.addHeader(new BasicHeader(name, value));
        }
    }

    return response;
}

From source file:com.rafagarcia.countries.backend.webapi.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  .j av a2s  .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() + ' ' + 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));
        }

        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));
        }

        String endMessage = "--> END " + request.method();
        if (logBody && hasRequestBody) {
            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));
        }

        if (logBody) {
            Buffer buffer = new Buffer();
            responseBody.source().readAll(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));
            }

            // Since we consumed the original, replace the one-shot body in the response with a new one.
            response = response.newBuilder()
                    .body(ResponseBody.create(contentType, responseBody.contentLength(), buffer)).build();
        }

        String endMessage = "<-- END HTTP";
        if (logBody) {
            endMessage += " (" + responseBody.contentLength() + "-byte body)";
        }
        logger.log(endMessage);
    }

    return response;
}

From source file:com.wecanstudio.xdsjs.save.Model.net.LoggingInterceptor.java

License:Open Source License

@Override
public Response intercept(Chain chain) throws IOException {
    Request request = chain.request();
    Log.e(TAG, String.format("%s\n%s", request, request.headers()));
    Response response = chain.proceed(request);
    Log.e(TAG, String.format("%s\n%s", response, response.headers()));
    return response;
}

From source file:com.yandex.disk.rest.LoggingInterceptor.java

License:Apache License

@Override
public Response intercept(Chain chain) throws IOException {
    Request request = chain.request();
    String hash = Integer.toHexString(chain.hashCode());
    String sendPrefix = hash + SEND_PREFIX;
    String receivePrefix = hash + RECEIVE_PREFIX;

    if (logWire) {
        RequestBody requestBody = request.body();
        if (requestBody != null) {
            logger.info(sendPrefix + "request: " + requestBody);
            Buffer buffer = new Buffer();
            requestBody.writeTo(buffer);
            byte[] requestBuffer = ByteStreams.toByteArray(buffer.inputStream());
            logBuffer(sendPrefix, requestBuffer);
        }/*from  w  ww.j  ava  2 s. c  o m*/
        request = request.newBuilder().removeHeader("Accept-Encoding").addHeader("Accept-Encoding", "").build();
    }

    logger.info(sendPrefix + request.method() + " " + request.url());
    logger.info(sendPrefix + "on " + chain.connection());
    logHeaders(sendPrefix, request.headers());

    Response response = chain.proceed(request);
    logger.info(receivePrefix + response.protocol() + " " + response.code() + " " + response.message());
    logHeaders(receivePrefix, response.headers());

    if (logWire) {
        ResponseBody body = response.body();
        byte[] responseBuffer = ByteStreams.toByteArray(body.byteStream());
        response = response.newBuilder().body(ResponseBody.create(body.contentType(), responseBuffer)).build();
        logBuffer(receivePrefix, responseBuffer);
    }

    return response;
}

From source file:com.ydh.gva.util.net.volley.toolbox.OkHttpStack.java

License:Open Source License

@Override
public HttpResponse performRequest(Request<?> request, Map<String, String> additionalHeaders)
        throws IOException, AuthFailureError {

    OkHttpClient client = mClient.clone();
    int timeoutMs = request.getTimeoutMs();
    client.setConnectTimeout(timeoutMs, TimeUnit.MILLISECONDS);
    client.setReadTimeout(timeoutMs, TimeUnit.MILLISECONDS);
    client.setWriteTimeout(timeoutMs, TimeUnit.MILLISECONDS);

    com.squareup.okhttp.Request.Builder okHttpRequestBuilder = new com.squareup.okhttp.Request.Builder();
    okHttpRequestBuilder.url(request.getUrl());

    Map<String, String> headers = request.getHeaders();
    okHttpRequestBuilder.addHeader("clientos", "101");
    okHttpRequestBuilder.addHeader("osversion", SystemVal.sdk + "");
    okHttpRequestBuilder.addHeader("clientphone", SystemVal.model + "");
    okHttpRequestBuilder.addHeader("weiLeversion", SystemVal.versionCode + "");

    for (final String name : headers.keySet()) {
        okHttpRequestBuilder.addHeader(name, headers.get(name));
    }// w  w  w. j  a  v a2 s .  c om

    for (final String name : additionalHeaders.keySet()) {
        okHttpRequestBuilder.addHeader(name, additionalHeaders.get(name));
    }

    setConnectionParametersForRequest(okHttpRequestBuilder, request);

    com.squareup.okhttp.Request okHttpRequest = okHttpRequestBuilder.build();
    Call okHttpCall = client.newCall(okHttpRequest);
    Response okHttpResponse = okHttpCall.execute();

    StatusLine responseStatus = new BasicStatusLine(parseProtocol(okHttpResponse.protocol()),
            okHttpResponse.code(), okHttpResponse.message());
    BasicHttpResponse response = new BasicHttpResponse(responseStatus);
    response.setEntity(entityFromOkHttpResponse(okHttpResponse));

    Headers responseHeaders = okHttpResponse.headers();
    for (int i = 0, len = responseHeaders.size(); i < len; i++) {
        final String name = responseHeaders.name(i), value = responseHeaders.value(i);
        if (name != null) {
            response.addHeader(new BasicHeader(name, value));
        }
    }

    return response;
}

From source file:de.schildbach.wallet.data.DynamicFeeLoader.java

License:Open Source License

private static void fetchDynamicFees(final HttpUrl url, final File tempFile, final File targetFile,
        final String userAgent) {
    final Stopwatch watch = Stopwatch.createStarted();

    final Request.Builder request = new Request.Builder();
    request.url(url);/*from w ww .  jav  a 2s . c  o m*/
    request.header("User-Agent", userAgent);
    if (targetFile.exists())
        request.header("If-Modified-Since", HttpDate.format(new Date(targetFile.lastModified())));

    final OkHttpClient httpClient = Constants.HTTP_CLIENT.clone();
    httpClient.setConnectTimeout(5, TimeUnit.SECONDS);
    httpClient.setWriteTimeout(5, TimeUnit.SECONDS);
    httpClient.setReadTimeout(5, TimeUnit.SECONDS);
    final Call call = httpClient.newCall(request.build());
    try {
        final Response response = call.execute();
        final int status = response.code();
        if (status == HttpURLConnection.HTTP_NOT_MODIFIED) {
            log.info("Dynamic fees not modified at {}, took {}", url, watch);
        } else if (status == HttpURLConnection.HTTP_OK) {
            final ResponseBody body = response.body();
            final FileOutputStream os = new FileOutputStream(tempFile);
            Io.copy(body.byteStream(), os);
            os.close();
            final Date lastModified = response.headers().getDate("Last-Modified");
            if (lastModified != null)
                tempFile.setLastModified(lastModified.getTime());
            body.close();
            if (!tempFile.renameTo(targetFile))
                throw new IllegalStateException("Cannot rename " + tempFile + " to " + targetFile);
            watch.stop();
            log.info("Dynamic fees fetched from {}, took {}", url, watch);
        } else {
            log.warn("HTTP status {} when fetching dynamic fees from {}", response.code(), url);
        }
    } catch (final Exception x) {
        log.warn("Problem when fetching dynamic fees rates from " + url, x);
    }
}

From source file:de.schildbach.wallet.ui.AlertDialogsFragment.java

License:Open Source License

@Override
public void onActivityCreated(final Bundle savedInstanceState) {
    super.onActivityCreated(savedInstanceState);

    log.debug("querying \"{}\"...", versionUrl);
    final Request.Builder request = new Request.Builder();
    request.url(versionUrl);/*from   w ww .  j  a v a  2 s  . co  m*/
    request.header("Accept-Charset", "utf-8");
    final String userAgent = application.httpUserAgent();
    if (userAgent != null)
        request.header("User-Agent", userAgent);

    final Call call = Constants.HTTP_CLIENT.newCall(request.build());

    backgroundHandler.post(new Runnable() {
        @Override
        public void run() {
            boolean abort = false;
            try {
                final Response response = call.execute();
                if (response.isSuccessful()) {
                    final long serverTime = response.headers().getDate("Date").getTime();
                    try (final BufferedReader reader = new BufferedReader(response.body().charStream())) {
                        abort = handleServerTime(serverTime);

                        while (true) {
                            final String line = reader.readLine();
                            if (line == null)
                                break;
                            if (line.charAt(0) == '#')
                                continue;

                            final Splitter splitter = Splitter.on('=').trimResults();
                            final Iterator<String> split = splitter.split(line).iterator();
                            if (!split.hasNext())
                                continue;
                            final String key = split.next();
                            if (!split.hasNext()) {
                                abort = handleLine(key);
                                if (abort)
                                    break;
                                continue;
                            }
                            final String value = split.next();
                            if (!split.hasNext()) {
                                abort = handleProperty(key, value);
                                if (abort)
                                    break;
                                continue;
                            }
                            log.info("Ignoring line: {}", line);
                        }
                    }
                }
            } catch (final Exception x) {
                handleException(x);
            }
            if (!abort)
                handleCatchAll();
        }
    });
}

From source file:de.schildbach.wallet.util.HttpGetThread.java

License:Open Source License

@Override
public void run() {
    log.debug("querying \"{}\"...", url);

    final Request.Builder request = new Request.Builder();
    request.url(url);/*ww  w  . jav  a2s.c  om*/
    request.header("Accept-Charset", "utf-8");
    if (userAgent != null)
        request.header("User-Agent", userAgent);

    final Call call = Constants.HTTP_CLIENT.newCall(request.build());
    try {
        final Response response = call.execute();
        if (response.isSuccessful()) {
            final long serverTime = response.headers().getDate("Date").getTime();
            final BufferedReader reader = new BufferedReader(response.body().charStream());
            final String line = reader.readLine().trim();
            reader.close();

            handleLine(line, serverTime);
        }
    } catch (final Exception x) {
        handleException(x);
    }
}

From source file:es.upv.grycap.opengateway.examples.test.AppDaemonTest.java

License:Apache License

private void testGetObject(final String id, final Waiter waiter)
        throws URISyntaxException, MalformedURLException {
    final Http2Client client = isolatedHttp2Client();
    client.asyncGetJson(String.format("%s/%s/%s", uri, path, id), false, new Callback() {
        @Override/*w  w  w.ja  va2 s .  c  om*/
        public void onResponse(final Response response) throws IOException {
            waiter.assertTrue(response.isSuccessful());
            // check response headers
            final Headers headers = response.headers();
            waiter.assertNotNull(headers);
            waiter.assertNotNull(headers.names());
            waiter.assertThat(headers.names().size(), greaterThan(0));
            // check response body
            waiter.assertThat(response.body().contentLength(), greaterThan(0l));
            final String payload = response.body().source().readUtf8();
            waiter.assertThat(payload, allOf(notNullValue(), not(equalTo(""))));
            pw.println(" >> Abbreviated response: " + abbreviate(payload, 32));
            // parse and check
            final Gson gson = new Gson();
            if (path.contains("products")) {
                final Product product = gson.fromJson(payload, Product.class);
                waiter.assertNotNull(product);
                waiter.assertThat(product, allOf(notNullValue(), equalTo(getProducts().get(id))));
                pw.println(" >> Object response: " + product);
            } else if (path.contains("shipping")) {
                final Shipping shipping = gson.fromJson(payload, Shipping.class);
                waiter.assertNotNull(shipping);
                waiter.assertThat(shipping, allOf(notNullValue(), equalTo(getShipping().get(id))));
                pw.println(" >> Object response: " + shipping);
            }
            waiter.resume();
        }

        @Override
        public void onFailure(final Request request, final IOException throwable) {
            waiter.fail(throwable);
        }
    });
}

From source file:es.upv.grycap.opengateway.examples.test.AppDaemonTest.java

License:Apache License

private void testGetList(final Waiter waiter) {
    final Http2Client client = isolatedHttp2Client();
    client.asyncGetJson(String.format("%s/%s", uri, path), false, new Callback() {
        @Override//from   w  w  w  .j a  va 2  s . c o m
        public void onResponse(final Response response) throws IOException {
            waiter.assertTrue(response.isSuccessful());
            // check response headers
            final Headers headers = response.headers();
            waiter.assertNotNull(headers);
            waiter.assertNotNull(headers.names());
            waiter.assertThat(headers.names().size(), greaterThan(0));
            // check response body
            waiter.assertThat(response.body().contentLength(), greaterThan(0l));
            final String payload = response.body().source().readUtf8();
            waiter.assertThat(payload, allOf(notNullValue(), not(equalTo(""))));
            pw.println(" >> Abbreviated response: " + abbreviate(payload, 32));
            // parse and check
            final Gson gson = new Gson();
            if (path.contains("products")) {
                final Type collectionType = new TypeToken<List<Product>>() {
                }.getType();
                final List<Product> products = gson.fromJson(payload, collectionType);
                waiter.assertNotNull(products);
                waiter.assertThat(products,
                        allOf(notNullValue(), containsInAnyOrder(getProducts().values().toArray())));
                pw.println(" >> Object response: " + products);
            } else if (path.contains("shipping")) {
                final Type collectionType = new TypeToken<List<Shipping>>() {
                }.getType();
                final List<Shipping> shipping = gson.fromJson(payload, collectionType);
                waiter.assertNotNull(shipping);
                waiter.assertThat(shipping,
                        allOf(notNullValue(), containsInAnyOrder(getShipping().values().toArray())));
                pw.println(" >> Object response: " + shipping);
            }
            waiter.resume();
        }

        @Override
        public void onFailure(final Request request, final IOException throwable) {
            waiter.fail(throwable);
        }
    });
}