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.ibm.mobilefirstplatform.clientsdk.android.security.mca.internal.AuthorizationHeaderHelper.java

License:Apache License

/**
 * A response is an OAuth error response only if,
 * 1. it's status is 401 or 403/*from   ww w  .  j  av  a  2  s .c  om*/
 * 2. The value of the "WWW-Authenticate" header contains 'Bearer'
 *
 * @param response to check the conditions for.
 * @return true if the response satisfies both conditions
 */
public static boolean isAuthorizationRequired(Response response) {
    return isAuthorizationRequired(response.code(), response.headers(WWW_AUTHENTICATE_HEADER));
}

From source file:com.ichg.service.volley.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));
    }/*from   ww w .  j av a  2s . co m*/
    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:com.inductiveautomation.ignition.examples.reporting.datasource.common.RestJsonDataSource.java

/**
 * Attempts to connect to a Url using {@link OkHttpClient} and return the body of the reply as a String, if it is
 * JSON mime type./*ww w  . j a  v a2  s  . co m*/
 * @param url String specifying the
 * @return the body of the http response received from the specified Url
 */
private String collectData(String url) throws IOException {
    OkHttpClient client = new OkHttpClient();
    Request request = new Request.Builder().url(url).build();

    Response response = client.newCall(request).execute();

    // get headers to check the content type out of
    Headers headers = null;
    if (response != null) {
        headers = response.headers();
    }

    // at least try to make sure we have JSON data.
    boolean isJSON = false;
    if (headers != null) {
        isJSON = MediaType.parse(headers.get("Content-Type")).equals(JSON);
    }

    return isJSON ? response.body().string() : "";
}

From source file:com.intuit.tank.okhttpclient.TankOkHttpClient.java

License:Open Source License

private void sendRequest(BaseRequest request, @Nonnull Request.Builder builder, String requestBody,
        String method) {//w  ww.  j  a  va  2 s . c  om
    String uri = null;
    long waitTime = 0L;
    try {
        setHeaders(request, builder, request.getHeaderInformation());

        List<String> cookies = new ArrayList<String>();
        if (((CookieManager) okHttpClient.getCookieHandler()).getCookieStore().getCookies() != null) {
            for (HttpCookie httpCookie : ((CookieManager) okHttpClient.getCookieHandler()).getCookieStore()
                    .getCookies()) {
                cookies.add("REQUEST COOKIE: " + httpCookie.toString());
            }
        }

        Request okRequest = builder.build();
        uri = okRequest.uri().toString();
        LOG.debug(request.getLogUtil().getLogMessage(
                "About to " + okRequest.method() + " request to " + uri + " with requestBody  " + requestBody,
                LogEventType.Informational));
        request.logRequest(uri, requestBody, okRequest.method(), request.getHeaderInformation(), cookies,
                false);

        Response response = okHttpClient.newCall(okRequest).execute();
        long startTime = Long.parseLong(response.header("OkHttp-Sent-Millis"));
        long endTime = Long.parseLong(response.header("OkHttp-Sent-Millis"));

        // read response body
        byte[] responseBody = new byte[0];
        // check for no content headers
        if (response.code() != 203 && response.code() != 202 && response.code() != 204) {
            try {
                responseBody = response.body().bytes();
            } catch (Exception e) {
                LOG.warn("could not get response body: " + e);
            }
        }

        processResponse(responseBody, startTime, endTime, request, response.message(), response.code(),
                response.headers());
        waitTime = endTime - startTime;
    } catch (Exception ex) {
        LOG.error(request.getLogUtil().getLogMessage(
                "Could not do " + method + " to url " + uri + " |  error: " + ex.toString(), LogEventType.IO),
                ex);
        throw new RuntimeException(ex);
    } finally {
        if (method.equalsIgnoreCase("post") && request.getLogUtil().getAgentConfig().getLogPostResponse()) {
            LOG.info(request.getLogUtil()
                    .getLogMessage("Response from POST to " + request.getRequestUrl() + " got status code "
                            + request.getResponse().getHttpCode() + " BODY { " + request.getResponse().getBody()
                            + " }", LogEventType.Informational));
        }
    }
    if (waitTime != 0) {
        doWaitDueToLongResponse(request, waitTime, uri);
    }
}

From source file:com.jaspersoft.android.jaspermobile.webview.intercept.okhttp.OkResponseMapper.java

License:Open Source License

private Map<String, String> extractHeaders(Response response) {
    Map<String, List<String>> headers = response.headers().toMultimap();
    Map<String, String> extractedHeaders = new HashMap<>();
    for (Map.Entry<String, List<String>> entry : headers.entrySet()) {
        List<String> value = entry.getValue();
        int size = value.size();
        extractedHeaders.put(entry.getKey(), value.get(size - 1));
    }// w  ww.  j  ava  2  s. co  m
    return extractedHeaders;
}

From source file:com.magnet.max.android.rest.qos.internal.CachedResponse.java

License:Apache License

public CachedResponse(Response response) {
    this.code = response.code();
    this.protocol = response.protocol().toString();
    this.message = response.message();

    parseHeaders(response.headers());

    if (null != response.body()) {
        try {/*from w ww  .j  a va2 s  .c  o  m*/
            Buffer buffer = new Buffer();
            response.body().source().readAll(buffer);
            body = CacheUtils.copyBody(buffer);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

From source file:com.microsoft.windowsazure.mobileservices.http.ServiceFilterResponseImpl.java

License:Open Source License

public static InputStream getUngzippedContent(Response response) throws IOException {

    InputStream responseStream = response.body().byteStream();

    if (responseStream == null)
        return responseStream;

    String contentEncoding = response.headers().get("content-encoding");

    if (contentEncoding == null) {
        return responseStream;
    }/* www . ja va2 s . co m*/

    if (contentEncoding.contains("gzip"))
        responseStream = new GZIPInputStream(responseStream);

    return responseStream;
}

From source file:com.moesif.android.okhttp2.MoesifOkHttp2Stack.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);
    client.networkInterceptors().add(new MoesifOkHttp2Interceptor());

    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));
    }//from   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, 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:com.parse.ParseOkHttpClient.java

License:Open Source License

@Override
/* package */ ParseHttpResponse getResponse(Response okHttpResponse) throws IOException {
    // Status code
    int statusCode = okHttpResponse.code();

    // Content/* w w w .  j  a  v a 2s  .co m*/
    InputStream content = okHttpResponse.body().byteStream();

    // Total size
    int totalSize = (int) okHttpResponse.body().contentLength();

    // Reason phrase
    String reasonPhrase = okHttpResponse.message();

    // Headers
    Map<String, String> headers = new HashMap<>();
    for (String name : okHttpResponse.headers().names()) {
        headers.put(name, okHttpResponse.header(name));
    }

    // Content type
    String contentType = null;
    ResponseBody body = okHttpResponse.body();
    if (body != null && body.contentType() != null) {
        contentType = body.contentType().toString();
    }

    return new ParseHttpResponse.Builder().setStatusCode(statusCode).setContent(content).setTotalSize(totalSize)
            .setReasonPhrase(reasonPhrase).setHeaders(headers).setContentType(contentType).build();
}

From source file:com.peach.masktime.module.net.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();
    LogUtils.i(TAG, "timeoutMs = " + timeoutMs);
    client.setProxy(Proxy.NO_PROXY);
    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 a v  a2 s.  c o  m*/
    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;
}