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:abtlibrary.utils.as24ApiClient.ApiClient.java

License:Apache License

/**
 * Deserialize response body to Java object, according to the return type and
 * the Content-Type response header.// w  w w . j a  va  2  s . c o m
 *
 * @param <T> Type
 * @param response HTTP response
 * @param returnType The type of the Java object
 * @return The deserialized Java object
 * @throws ApiException If fail to deserialize response body, i.e. cannot read response body
 *   or the Content-Type of the response is not supported.
 */
@SuppressWarnings("unchecked")
public <T> T deserialize(Response response, Type returnType) throws ApiException {
    if (response == null || returnType == null) {
        return null;
    }

    if ("byte[]".equals(returnType.toString())) {
        // Handle binary response (byte array).
        try {
            return (T) response.body().bytes();
        } catch (IOException e) {
            throw new ApiException(e);
        }
    } else if (returnType.equals(File.class)) {
        // Handle file downloading.
        return (T) downloadFileFromResponse(response);
    }

    String respBody;
    try {
        if (response.body() != null)
            respBody = response.body().string();
        else
            respBody = null;
    } catch (IOException e) {
        throw new ApiException(e);
    }

    if (respBody == null || "".equals(respBody)) {
        return null;
    }

    String contentType = response.headers().get("Content-Type");
    if (contentType == null) {
        // ensuring a default content type
        contentType = "application/json";
    }
    if (isJsonMime(contentType)) {
        return json.deserialize(respBody, returnType);
    } else if (returnType.equals(String.class)) {
        // Expecting string, return the raw response body.
        return (T) respBody;
    } else {
        throw new ApiException("Content type \"" + contentType + "\" is not supported for type: " + returnType,
                response.code(), response.headers().toMultimap(), respBody);
    }
}

From source file:abtlibrary.utils.as24ApiClient.ApiClient.java

License:Apache License

/**
 * Execute HTTP call and deserialize the HTTP response body into the given return type.
 *
 * @param returnType The return type used to deserialize HTTP response body
 * @param <T> The return type corresponding to (same with) returnType
 * @param call Call/*from  ww w  .java2s.  c  o m*/
 * @return ApiResponse object containing response status, headers and
 *   data, which is a Java object deserialized from response body and would be null
 *   when returnType is null.
 * @throws ApiException If fail to execute the call
 */
public <T> ApiResponse<T> execute(Call call, Type returnType) throws ApiException {
    try {
        Response response = call.execute();
        T data = handleResponse(response, returnType);
        return new ApiResponse<T>(response.code(), response.headers().toMultimap(), data);
    } catch (IOException e) {
        throw new ApiException(e);
    }
}

From source file:abtlibrary.utils.as24ApiClient.ApiClient.java

License:Apache License

/**
 * Execute HTTP call asynchronously./*w  ww  .j  av a2s .  c o m*/
 *
 * @see #execute(Call, Type)
 * @param <T> Type
 * @param call The callback to be executed when the API call finishes
 * @param returnType Return type
 * @param callback ApiCallback
 */
@SuppressWarnings("unchecked")
public <T> void executeAsync(Call call, final Type returnType, final ApiCallback<T> callback) {
    call.enqueue(new Callback() {
        @Override
        public void onFailure(Request request, IOException e) {
            callback.onFailure(new ApiException(e), 0, null);
        }

        @Override
        public void onResponse(Response response) throws IOException {
            T result;
            try {
                result = (T) handleResponse(response, returnType);
            } catch (ApiException e) {
                callback.onFailure(e, response.code(), response.headers().toMultimap());
                return;
            }
            callback.onSuccess(result, response.code(), response.headers().toMultimap());
        }
    });
}

From source file:abtlibrary.utils.as24ApiClient.ApiClient.java

License:Apache License

/**
 * Handle the given response, return the deserialized object when the response is successful.
 *
 * @param <T> Type/*  w  w w . j  a  va 2 s. c om*/
 * @param response Response
 * @param returnType Return type
 * @throws ApiException If the response has a unsuccessful status code or
 *   fail to deserialize the response body
 * @return Type
 */
public <T> T handleResponse(Response response, Type returnType) throws ApiException {
    if (response.isSuccessful()) {
        if (returnType == null || response.code() == 204) {
            // returning null if the returnType is not defined,
            // or the status code is 204 (No Content)
            return null;
        } else {
            return deserialize(response, returnType);
        }
    } else {
        String respBody = null;
        if (response.body() != null) {
            try {
                respBody = response.body().string();
            } catch (IOException e) {
                throw new ApiException(response.message(), e, response.code(), response.headers().toMultimap());
            }
        }
        throw new ApiException(response.message(), response.code(), response.headers().toMultimap(), respBody);
    }
}

From source file:alberto.avengers.model.rest.utils.interceptors.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. j av  a2 s .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));
        }

        String endMessage = "--> END " + request.method();
        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));

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

        String endMessage = "<-- END HTTP";
        if (logBody) {
            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 (responseBody.contentLength() != 0) {
                logger.log("");
                logger.log(buffer.clone().readString(charset));
            }

            endMessage += " (" + buffer.size() + "-byte body)";
        }
        logger.log(endMessage);
    }

    return response;
}

From source file:at.bitfire.dav4android.BasicDigestAuthenticator.java

License:Open Source License

@Override
public Request authenticate(Proxy proxy, Response response) throws IOException {
    Request request = response.request();

    if (host != null && !request.httpUrl().host().equalsIgnoreCase(host)) {
        Constants.log.warn("Not authenticating against " + host + " for security reasons!");
        return null;
    }/* www  .j ava  2  s .  co  m*/

    // check whether this is the first authentication try with our credentials
    Response priorResponse = response.priorResponse();
    boolean triedBefore = priorResponse != null ? priorResponse.request().header(HEADER_AUTHORIZATION) != null
            : false;

    HttpUtils.AuthScheme basicAuth = null, digestAuth = null;
    for (HttpUtils.AuthScheme scheme : HttpUtils
            .parseWwwAuthenticate(response.headers(HEADER_AUTHENTICATE).toArray(new String[0])))
        if ("Basic".equalsIgnoreCase(scheme.name))
            basicAuth = scheme;
        else if ("Digest".equalsIgnoreCase(scheme.name))
            digestAuth = scheme;

    // we MUST prefer Digest auth [https://tools.ietf.org/html/rfc2617#section-4.6]
    if (digestAuth != null) {
        // Digest auth

        if (triedBefore && !"true".equalsIgnoreCase(digestAuth.params.get("stale")))
            // credentials didn't work last time, and they won't work now -> stop here
            return null;
        return authorizationRequest(request, digestAuth);

    } else if (basicAuth != null) {
        // Basic auth
        if (triedBefore) // credentials didn't work last time, and they won't work now -> stop here
            return null;

        return request.newBuilder().header(HEADER_AUTHORIZATION, Credentials.basic(username, password)).build();
    }

    // no supported auth scheme
    return null;
}

From source file:at.bitfire.dav4android.exception.HttpException.java

License:Open Source License

public HttpException(Response response) {
    super(response.code() + " " + response.message());

    status = response.code();//ww  w  .  java2  s  .c  o  m
    message = response.message();

    /* As we don't know the media type and character set of request and response body,
       only printable ASCII characters will be shown in clear text. Other octets will
       be shown as "[xx]" where xx is the hex value of the octet.
     */

    // format request
    Request request = response.request();
    StringBuilder formatted = new StringBuilder();
    formatted.append(request.method() + " " + request.urlString() + "\n");
    Headers headers = request.headers();
    for (String name : headers.names())
        for (String value : headers.values(name))
            formatted.append(name + ": " + value + "\n");
    if (request.body() != null)
        try {
            formatted.append("\n");
            Buffer buffer = new Buffer();
            request.body().writeTo(buffer);
            while (!buffer.exhausted())
                appendByte(formatted, buffer.readByte());
        } catch (IOException e) {
        }
    this.request = formatted.toString();

    // format response
    formatted = new StringBuilder();
    formatted.append(response.protocol() + " " + response.code() + " " + response.message() + "\n");
    headers = response.headers();
    for (String name : headers.names())
        for (String value : headers.values(name))
            formatted.append(name + ": " + value + "\n");
    if (response.body() != null)
        try {
            formatted.append("\n");
            for (byte b : response.body().bytes())
                appendByte(formatted, b);
        } catch (IOException e) {
        }
    this.response = formatted.toString();
}

From source file:cn.com.canon.darwin.modules.service.api.interceptor.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);
    }/*  w w w  .  j  a  v  a2 s .  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() + ' ' + 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:cn.finalteam.okhttpfinal.HttpTask.java

License:Apache License

@Override
protected ResponseData doInBackground(Void... voids) {
    Response response = null;
    ResponseData responseData = new ResponseData();
    try {//from   www. j av a 2s. c  o  m
        //OkHttpClient client = OkHttpFactory.getOkHttpClientFactory(timeout);
        String srcUrl = url;
        //Request
        Request.Builder builder = new Request.Builder();

        switch (method) {
        case GET:
            url = Utils.getFullUrl(url, params.getUrlParams());
            builder.get();
            break;
        case DELETE:
            url = Utils.getFullUrl(url, params.getUrlParams());
            builder.delete();
            break;
        case HEAD:
            url = Utils.getFullUrl(url, params.getUrlParams());
            builder.head();
            break;
        case POST:
            RequestBody body = params.getRequestBody();
            if (body != null) {
                builder.post(new ProgressRequestBody(body, callback));
            }
            break;
        case PUT:
            RequestBody bodyPut = params.getRequestBody();
            if (bodyPut != null) {
                builder.put(new ProgressRequestBody(bodyPut, callback));
            }
            break;

        case PATCH:
            RequestBody bodyPatch = params.getRequestBody();
            if (bodyPatch != null) {
                builder.put(new ProgressRequestBody(bodyPatch, callback));
            }
            break;
        }

        builder.url(url).tag(srcUrl).headers(headers);
        Request request = builder.build();
        if (Constants.DEBUG) {
            Logger.d("url=" + url + "?" + params.toString());
        }
        //
        response = okHttpClient.newCall(request).execute();
    } catch (Exception e) {
        if (Constants.DEBUG) {
            Logger.e("Exception=", e);
        }
        if (e instanceof SocketTimeoutException) {
            responseData.setTimeout(true);
        } else if (e instanceof InterruptedIOException && TextUtils.equals(e.getMessage(), "timeout")) {
            responseData.setTimeout(true);
        }
    }

    //?
    if (response != null) {
        responseData.setResponseNull(false);
        responseData.setCode(response.code());
        responseData.setMessage(response.message());
        responseData.setSuccess(response.isSuccessful());
        String respBody = "";
        try {
            respBody = response.body().string();
        } catch (IOException e) {
            e.printStackTrace();
        }
        responseData.setResponse(respBody);
        responseData.setHeaders(response.headers());
    } else {
        responseData.setResponseNull(true);
    }
    return responseData;
}

From source file:co.paralleluniverse.fibers.okhttp.InterceptorTest.java

License:Open Source License

private void multipleInterceptors(List<Interceptor> interceptors) throws Exception {
    server.enqueue(new MockResponse());

    interceptors.add(new Interceptor() {
        @Override//from  w  w w  .  j a  v a  2  s. c  om
        public Response intercept(Chain chain) throws IOException {
            Request originalRequest = chain.request();
            Response originalResponse = chain
                    .proceed(originalRequest.newBuilder().addHeader("Request-Interceptor", "Android") // 1. Added first.
                            .build());
            return originalResponse.newBuilder().addHeader("Response-Interceptor", "Donut") // 4. Added last.
                    .build();
        }
    });
    interceptors.add(new Interceptor() {
        @Override
        public Response intercept(Chain chain) throws IOException {
            Request originalRequest = chain.request();
            Response originalResponse = chain
                    .proceed(originalRequest.newBuilder().addHeader("Request-Interceptor", "Bob") // 2. Added second.
                            .build());
            return originalResponse.newBuilder().addHeader("Response-Interceptor", "Cupcake") // 3. Added third.
                    .build();
        }
    });

    Request request = new Request.Builder().url(server.getUrl("/")).build();

    Response response = FiberOkHttpUtil.executeInFiber(client, request);
    assertEquals(Arrays.asList("Cupcake", "Donut"), response.headers("Response-Interceptor"));

    RecordedRequest recordedRequest = server.takeRequest();
    assertEquals(Arrays.asList("Android", "Bob"), recordedRequest.getHeaders().values("Request-Interceptor"));
}