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.citrus.retrofit.ReceivedCookiesInterceptor.java

License:Apache License

@Override
public Response intercept(Chain chain) throws IOException {
    Response originalResponse = chain.proceed(chain.request());
    // Logger.d("PREPAID COOKIE**" + originalResponse.header("prepaiduser-payauth"));
    if (!originalResponse.headers("Set-Cookie").isEmpty()) {
        HashSet<String> cookies = new HashSet<>();
        for (String header : originalResponse.headers("Set-Cookie")) {
            if (header.contains(Constants.HEADER_PREPAID_COOKIE)) {
                Logger.d("PREPAID COOKIE**" + header);
                EventBus.getDefault().post(new CookieEvents(header));
            }/*w  w  w.j a  v a 2  s  . c  om*/

        }

    } else {
        EventBus.getDefault().post(new CookieEvents(null));
    }
    RetroFitClient.removeInterCeptor();
    return originalResponse;
}

From source file:com.cml.rx.android.api.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 w w w.java 2  s  . c  o  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() + ' ' + request.url() + ' ' + protocol;
    if (!logHeaders && hasRequestBody) {
        requestStartMessage += " (" + requestBody.contentLength() + "-byte body)";
    }
    logger.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) {
                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 || !HttpEngine.hasBody(response)) {
            logger.log("<-- END HTTP");
        } else if (bodyEncoded(response.headers())) {
            logger.log("<-- END HTTP (encoded body omitted)");
        } 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) {
                try {
                    charset = contentType.charset(UTF8);
                } catch (UnsupportedCharsetException e) {
                    logger.log("");
                    logger.log("Couldn't decode the response body; charset is likely malformed.");
                    logger.log("<-- END HTTP");

                    return response;
                }
            }

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

From source file:com.datastore_android_sdk.okhttp.OkHttpStack.java

License:Open Source License

private URLHttpResponse responseFromConnection(Response okHttpResponse) throws IOException {
    URLHttpResponse response = new URLHttpResponse();
    //contentStream
    int responseCode = okHttpResponse.code();
    if (responseCode == -1) {
        throw new IOException("Could not retrieve response code from HttpUrlConnection.");
    }//from  w w  w  .j a  v  a 2s .  c o  m
    response.setResponseCode(responseCode);
    response.setResponseMessage(okHttpResponse.message());

    response.setContentStream(okHttpResponse.body().byteStream());

    response.setContentLength(okHttpResponse.body().contentLength());
    response.setContentEncoding(okHttpResponse.header("Content-Encoding"));
    if (okHttpResponse.body().contentType() != null) {
        response.setContentType(okHttpResponse.body().contentType().type());
    }

    //header
    HashMap<String, String> headerMap = new HashMap<>();
    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) {
            headerMap.put(name, value);
        }
    }
    response.setHeaders(headerMap);
    return response;
}

From source file:com.drjing.xibao.common.http.AsyncHttpResponseHandler.java

License:Apache License

protected void sendSuccessMessage(Response response) {
    try {//from  w  ww.j  ava  2s  .c o  m
        sendMessage(obtainMessage(SUCCESS_MESSAGE,
                new Object[] { new Integer(response.code()), response.headers(), response.body().string() }));
    } catch (IOException e) {
        e.printStackTrace();
    }
}

From source file:com.facebook.react.modules.network.NetworkingModule.java

License:Open Source License

@ReactMethod
public void sendRequest(String method, String url, int requestId, ReadableArray headers, ReadableMap data,
        final Callback callback) {
    // We need to call the callback to avoid leaking memory on JS even when input for sending
    // request is erroneous or insufficient. For non-http based failures we use code 0, which is
    // interpreted as a transport error.
    // Callback accepts following arguments: responseCode, headersString, responseBody

    Request.Builder requestBuilder = new Request.Builder().url(url);

    if (requestId != 0) {
        requestBuilder.tag(requestId);//ww  w.j  a va 2  s. c om
    }

    Headers requestHeaders = extractHeaders(headers, data);
    if (requestHeaders == null) {
        callback.invoke(0, null, "Unrecognized headers format");
        return;
    }
    String contentType = requestHeaders.get(CONTENT_TYPE_HEADER_NAME);
    String contentEncoding = requestHeaders.get(CONTENT_ENCODING_HEADER_NAME);
    requestBuilder.headers(requestHeaders);

    if (data == null) {
        requestBuilder.method(method, null);
    } else if (data.hasKey(REQUEST_BODY_KEY_STRING)) {
        if (contentType == null) {
            callback.invoke(0, null, "Payload is set but no content-type header specified");
            return;
        }
        String body = data.getString(REQUEST_BODY_KEY_STRING);
        MediaType contentMediaType = MediaType.parse(contentType);
        if (RequestBodyUtil.isGzipEncoding(contentEncoding)) {
            RequestBody requestBody = RequestBodyUtil.createGzip(contentMediaType, body);
            if (requestBody == null) {
                callback.invoke(0, null, "Failed to gzip request body");
                return;
            }
            requestBuilder.method(method, requestBody);
        } else {
            requestBuilder.method(method, RequestBody.create(contentMediaType, body));
        }
    } else if (data.hasKey(REQUEST_BODY_KEY_URI)) {
        if (contentType == null) {
            callback.invoke(0, null, "Payload is set but no content-type header specified");
            return;
        }
        String uri = data.getString(REQUEST_BODY_KEY_URI);
        InputStream fileInputStream = RequestBodyUtil.getFileInputStream(getReactApplicationContext(), uri);
        if (fileInputStream == null) {
            callback.invoke(0, null, "Could not retrieve file for uri " + uri);
            return;
        }
        requestBuilder.method(method, RequestBodyUtil.create(MediaType.parse(contentType), fileInputStream));
    } else if (data.hasKey(REQUEST_BODY_KEY_FORMDATA)) {
        if (contentType == null) {
            contentType = "multipart/form-data";
        }
        ReadableArray parts = data.getArray(REQUEST_BODY_KEY_FORMDATA);
        MultipartBuilder multipartBuilder = constructMultipartBody(parts, contentType, callback);
        if (multipartBuilder == null) {
            return;
        }
        requestBuilder.method(method, multipartBuilder.build());
    } else {
        // Nothing in data payload, at least nothing we could understand anyway.
        // Ignore and treat it as if it were null.
        requestBuilder.method(method, null);
    }

    mClient.newCall(requestBuilder.build()).enqueue(new com.squareup.okhttp.Callback() {
        @Override
        public void onFailure(Request request, IOException e) {
            if (mShuttingDown) {
                return;
            }
            // We need to call the callback to avoid leaking memory on JS even when input for
            // sending request is erronous or insufficient. For non-http based failures we use
            // code 0, which is interpreted as a transport error
            callback.invoke(0, null, e.getMessage());
        }

        @Override
        public void onResponse(Response response) throws IOException {
            if (mShuttingDown) {
                return;
            }
            String responseBody;
            try {
                responseBody = response.body().string();
            } catch (IOException e) {
                // The stream has been cancelled or closed, nothing we can do
                callback.invoke(0, null, e.getMessage());
                return;
            }

            WritableMap responseHeaders = Arguments.createMap();
            Headers headers = response.headers();
            for (int i = 0; i < headers.size(); i++) {
                String headerName = headers.name(i);
                // multiple values for the same header
                if (responseHeaders.hasKey(headerName)) {
                    responseHeaders.putString(headerName,
                            responseHeaders.getString(headerName) + ", " + headers.value(i));
                } else {
                    responseHeaders.putString(headerName, headers.value(i));
                }
            }

            callback.invoke(response.code(), responseHeaders, responseBody);
        }
    });
}

From source file:com.frostwire.util.http.OKHTTPClient.java

License:Open Source License

@Override
public int head(String url, int connectTimeoutInMillis, Map<String, List<String>> outputHeaders)
        throws IOException {
    final OkHttpClient okHttpClient = newOkHttpClient();
    okHttpClient.setConnectTimeout(connectTimeoutInMillis, TimeUnit.MILLISECONDS);
    okHttpClient.setFollowRedirects(false);
    Request req = new Request.Builder().url(url).header("User-Agent", DEFAULT_USER_AGENT).head().build();
    Response resp = okHttpClient.newCall(req).execute();
    copyMultiMap(resp.headers().toMultimap(), outputHeaders);
    return resp.code();
}

From source file:com.frostwire.util.http.OKHTTPClient.java

License:Open Source License

@Override
public void save(String url, File file, boolean resume, int timeout, String userAgent, String referrer)
        throws IOException {
    FileOutputStream fos;//from w  w w  .j  a v a  2  s.  c o m
    long rangeStart;
    canceled = false;
    if (resume && file.exists()) {
        fos = new FileOutputStream(file, true);
        rangeStart = file.length();
    } else {
        fos = new FileOutputStream(file, false);
        rangeStart = -1;
    }

    final OkHttpClient okHttpClient = newOkHttpClient();
    final Request.Builder builder = prepareRequestBuilder(okHttpClient, url, timeout, userAgent, referrer,
            null);
    addRangeHeader(rangeStart, -1, builder);
    final Response response = getSyncResponse(okHttpClient, builder);
    final Headers headers = response.headers();
    onHeaders(headers);
    final InputStream in = response.body().byteStream();

    byte[] b = new byte[4096];
    int n;
    while (!canceled && (n = in.read(b, 0, b.length)) != -1) {
        if (!canceled) {
            fos.write(b, 0, n);
            onData(b, 0, n);
        }
    }
    closeQuietly(fos);
    if (canceled) {
        onCancel();
    } else {
        onComplete();
    }
}

From source file:com.gezhii.fitgroup.network.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();
    int timeoutMs = 30000;
    Log.i("timeoutMs", timeoutMs);
    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 a va2 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:com.groupon.odo.bmp.BrowserMobProxyHandler.java

License:Apache License

protected long proxyPlainTextRequest(final URL url, String pathInContext, String pathParams,
        HttpRequest request, final HttpResponse response) throws IOException {
    try {/*  w ww. ja v a 2 s  .  com*/
        String urlStr = url.toString();

        if (urlStr.toLowerCase().startsWith(Constants.ODO_INTERNAL_WEBAPP_URL)) {
            urlStr = "http://localhost:" + com.groupon.odo.proxylib.Utils.getSystemPort(Constants.SYS_HTTP_PORT)
                    + "/odo";
        }

        // setup okhttp to ignore ssl issues
        OkHttpClient okHttpClient = getUnsafeOkHttpClient();
        okHttpClient.setFollowRedirects(false);
        okHttpClient.setFollowSslRedirects(false);

        Request.Builder okRequestBuilder = new Request.Builder();

        /*
         * urlStr.indexOf(":") == urlStr.lastIndexOf(":") verifies that the url does not have a port
         * by checking it only has a : as part of http://
         */
        if (urlStr.startsWith("http://") && urlStr.indexOf(":") == urlStr.lastIndexOf(":")) {
            int httpPort = com.groupon.odo.proxylib.Utils.getSystemPort(Constants.SYS_HTTP_PORT);
            urlStr = urlStr.replace(getHostNameFromURL(urlStr), localIP + ":" + httpPort);
        }

        okRequestBuilder = okRequestBuilder.url(urlStr);

        // copy request headers
        Enumeration<?> enm = request.getFieldNames();
        boolean isGet = "GET".equals(request.getMethod());
        boolean hasContent = false;
        boolean usedContentLength = false;
        long contentLength = 0;
        while (enm.hasMoreElements()) {
            String hdr = (String) enm.nextElement();

            if (!isGet && HttpFields.__ContentType.equals(hdr)) {
                hasContent = true;
            }
            if (!isGet && HttpFields.__ContentLength.equals(hdr)) {
                contentLength = Long.parseLong(request.getField(hdr));
                usedContentLength = true;
            }

            Enumeration<?> vals = request.getFieldValues(hdr);
            while (vals.hasMoreElements()) {
                String val = (String) vals.nextElement();
                if (val != null) {
                    if (!isGet && HttpFields.__ContentLength.equals(hdr) && Integer.parseInt(val) > 0) {
                        hasContent = true;
                    }

                    if (!_DontProxyHeaders.containsKey(hdr)) {
                        okRequestBuilder = okRequestBuilder.addHeader(hdr, val);
                        //httpReq.addRequestHeader(hdr, val);
                    }
                }
            }
        }

        if ("GET".equals(request.getMethod())) {
            // don't need to do anything else
        } else if ("POST".equals(request.getMethod()) || "PUT".equals(request.getMethod())
                || "DELETE".equals(request.getMethod())) {
            RequestBody okRequestBody = null;
            if (hasContent) {
                final String contentType = request.getContentType();
                final byte[] bytes = IOUtils.toByteArray(request.getInputStream());

                okRequestBody = new RequestBody() {
                    @Override
                    public MediaType contentType() {
                        MediaType.parse(contentType);
                        return null;
                    }

                    @Override
                    public void writeTo(BufferedSink bufferedSink) throws IOException {
                        bufferedSink.write(bytes);
                    }
                };

                // we need to add some ODO specific headers to give ODO a hint for content-length vs transfer-encoding
                // since okHTTP will automatically chunk even if the request was not chunked
                // this allows Odo to set the appropriate headers when the server request is made
                if (usedContentLength) {
                    okRequestBuilder = okRequestBuilder.addHeader("ODO-POST-TYPE",
                            "content-length:" + contentLength);
                }
            } else {
                okRequestBody = RequestBody.create(null, new byte[0]);
            }

            if ("POST".equals(request.getMethod())) {
                okRequestBuilder = okRequestBuilder.post(okRequestBody);
            } else if ("PUT".equals(request.getMethod())) {
                okRequestBuilder = okRequestBuilder.put(okRequestBody);
            } else if ("DELETE".equals(request.getMethod())) {
                okRequestBuilder = okRequestBuilder.delete(okRequestBody);
            }
        } else if ("OPTIONS".equals(request.getMethod())) {
            // NOT SUPPORTED
        } else if ("HEAD".equals(request.getMethod())) {
            okRequestBuilder = okRequestBuilder.head();
        } else {
            LOG.warn("Unexpected request method %s, giving up", request.getMethod());
            request.setHandled(true);
            return -1;
        }

        Request okRequest = okRequestBuilder.build();
        Response okResponse = okHttpClient.newCall(okRequest).execute();

        // Set status and response message
        response.setStatus(okResponse.code());
        response.setReason(okResponse.message());

        // copy response headers
        for (int headerNum = 0; headerNum < okResponse.headers().size(); headerNum++) {
            String headerName = okResponse.headers().name(headerNum);
            if (!_DontProxyHeaders.containsKey(headerName) && !_ProxyAuthHeaders.containsKey(headerName)) {
                response.addField(headerName, okResponse.headers().value(headerNum));
            }
        }

        // write output to response output stream
        try {
            IOUtils.copy(okResponse.body().byteStream(), response.getOutputStream());
        } catch (Exception e) {
            // ignoring this until we refactor the proxy
            // The copy occasionally fails due to an issue where okResponse has more data in the body than it's supposed to
            // The client still gets all of the data it was expecting
        }

        request.setHandled(true);
        return okResponse.body().contentLength();
    } catch (Exception e) {
        LOG.warn("Caught exception proxying: ", e);
        reportError(e, url, response);
        request.setHandled(true);
        return -1;
    }
}

From source file:com.ibm.mobilefirstplatform.clientsdk.android.core.api.Request.java

License:Apache License

@Override
protected Callback getCallback(final ResponseListener listener) {
    final RequestBody requestBody = savedRequestBody;
    final Request request = this;
    final Context ctx = this.context;

    return new Callback() {
        @Override/*w w w .  j a  va 2 s .c om*/
        public void onFailure(com.squareup.okhttp.Request request, IOException e) {
            if (listener != null) {
                listener.onFailure(null, e, null);
            }
        }

        @Override
        public void onResponse(com.squareup.okhttp.Response response) throws IOException {
            if (listener == null) {
                return;
            }

            AuthorizationManager authorizationManager = BMSClient.getInstance().getAuthorizationManager();
            int responseCode = response.code();
            Map<String, List<String>> responseHeaders = response.headers().toMultimap();
            boolean isAuthorizationRequired = authorizationManager.isAuthorizationRequired(responseCode,
                    responseHeaders);

            if (isAuthorizationRequired) {
                if (oauthFailCounter++ < 2) {
                    authorizationManager.obtainAuthorization(ctx, new ResponseListener() {
                        @Override
                        public void onSuccess(Response response) {
                            // this will take the auth hader that has been cached by obtainAuthorizationHeader
                            request.sendRequest(listener, requestBody);
                        }

                        @Override
                        public void onFailure(Response response, Throwable t, JSONObject extendedInfo) {
                            listener.onFailure(response, t, extendedInfo);
                        }
                    });
                } else {
                    listener.onFailure(new ResponseImpl(response), null, null);
                }
            } else {
                if (response.isSuccessful() || response.isRedirect()) {
                    listener.onSuccess(new ResponseImpl(response));
                } else {
                    listener.onFailure(new ResponseImpl(response), null, null);
                }
            }
        }
    };
}