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:feign.okhttp.OkHttpClient.java

License:Apache License

private static feign.Response toFeignResponse(Response input) {
    return feign.Response.create(input.code(), input.message(), toMap(input.headers()), toBody(input.body()));
}

From source file:io.apiman.gateway.platforms.servlet.connectors.ok.HttpURLConnectionImpl.java

License:Apache License

private Headers getHeaders() throws IOException {
    if (responseHeaders == null) {
        Response response = getResponse().getResponse();
        Headers headers = response.headers();

        responseHeaders = headers.newBuilder()
                .add(Platform.get().getPrefix() + "-Response-Source", responseSourceHeader(response)).build();
    }//from w  w  w .  j a  v  a2  s  .  co  m
    return responseHeaders;
}

From source file:io.apptik.comm.jus.okhttp.OkHttpStack.java

License:Apache License

@Override
public NetworkResponse performRequest(Request<?> request, Headers additionalHeaders,
        ByteArrayPool byteArrayPool) throws IOException {

    //clone to be able to set timeouts per call
    OkHttpClient client = this.client.clone();
    client.setConnectTimeout(request.getRetryPolicy().getCurrentConnectTimeout(), TimeUnit.MILLISECONDS);
    client.setReadTimeout(request.getRetryPolicy().getCurrentReadTimeout(), TimeUnit.MILLISECONDS);
    com.squareup.okhttp.Request okRequest = new com.squareup.okhttp.Request.Builder()
            .url(request.getUrlString()).headers(JusOk.okHeaders(request.getHeaders(), additionalHeaders))
            .tag(request.getTag()).method(request.getMethod(), JusOk.okBody(request.getNetworkRequest()))
            .build();//from  ww  w  .j  a v a 2 s .  com

    long requestStart = System.nanoTime();

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

    byte[] data = null;
    if (NetworkDispatcher.hasResponseBody(request.getMethod(), response.code())) {
        data = getContentBytes(response.body().source(), byteArrayPool, (int) response.body().contentLength());
    } else {
        // Add 0 byte response as a way of honestly representing a
        // no-content request.
        data = new byte[0];
    }
    return new NetworkResponse.Builder().setHeaders(JusOk.jusHeaders(response.headers()))
            .setStatusCode(response.code()).setBody(data).setNetworkTimeNs(System.nanoTime() - requestStart)
            .build();
}

From source file:io.kubernetes.client.util.Watch.java

License:Apache License

/**
 * Creates a watch on a TYPENAME (T) using an API Client and a Call object.
 * @param client the API client//from  w w w  .j  a  v  a2 s .  c om
 * @param call the call object returned by api.{ListOperation}Call(...)
 *             method. Make sure watch flag is set in the call.
 * @param watchType The type of the WatchResponse&lt;T&gt;. Use something like
 *                  new TypeToken&lt;Watch.Response&lt;TYPENAME&gt;&gt;(){}.getType()
 * @param <T> TYPENAME.
 * @return Watch object on TYPENAME
 * @throws ApiException on IO exceptions.
 */
public static <T> Watch<T> createWatch(ApiClient client, Call call, Type watchType) throws ApiException {
    try {
        com.squareup.okhttp.Response response = call.execute();
        if (!response.isSuccessful()) {
            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);
        }
        return new Watch<>(client.getJSON(), response.body(), watchType);
    } catch (IOException e) {
        throw new ApiException(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);
    }// w  w w .  j  a v a  2  s . co  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.macgyver.core.okhttp.LoggingInterceptor.java

License:Apache License

private boolean isResponseBodyPrintable(Response response) {
    String contentType = response.headers().get("Content-type");
    if (contentType != null) {
        if (contentType.contains("image") || contentType.contains("octet-stream")) {
            return false;
        }/*from   w w  w. j  ava 2  s .  co m*/
    }
    if (!isResponseBodySizeWithinLimit(response)) {
        return false;
    }

    return true;
}

From source file:io.minio.MinioClient.java

License:Apache License

/**
 * Executes given request parameters./*from ww w  .j a  v a2s.co  m*/
 *
 * @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:it.smartcommunitylab.ApiClient.java

License:Apache License

/**
 * Handle the given response, return the deserialized object when the response is successful.
 *
 * @param <T> Type//from w w  w . j a va2 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)
            if (response.body() != null) {
                try {
                    response.body().close();
                } catch (IOException e) {
                    throw new ApiException(response.message(), e, response.code(),
                            response.headers().toMultimap());
                }
            }
            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:keywhiz.service.resources.SessionLoginResourceIntegrationTest.java

License:Apache License

@Test
public void setsValidCookieForValidCredentials() throws Exception {
    Request post = buildLoginPost(DbSeedCommand.defaultUser, DbSeedCommand.defaultPassword);

    Response response = client.newCall(post).execute();
    assertThat(response.code()).isEqualTo(303);

    List<String> cookieNames = Lists.newArrayList();
    String sessionCookie = null;/*  ww w .j a va  2 s .  co  m*/

    for (String cookieString : response.headers(HttpHeaders.SET_COOKIE)) {
        cookieString = cookieString.substring(0, cookieString.indexOf(";"));
        String cookieName = cookieString.substring(0, cookieString.indexOf("="));
        cookieNames.add(cookieName);

        if (cookieName.equals("session")) {
            sessionCookie = cookieString;
        }
    }

    assertThat(cookieNames).containsOnly("session", "XSRF-TOKEN");

    Pattern pattern = Pattern.compile("^session=(.+)$");
    assertThat(sessionCookie).matches(pattern);
}

From source file:keywhiz.service.resources.SessionLogoutResourceIntegrationTest.java

License:Apache License

@Test
public void sendsExpiredCookie() throws Exception {
    Request request = new Request.Builder().post(RequestBody.create(MediaType.parse("text/plain"), ""))
            .url(testUrl("/admin/logout")).build();

    Response response = client.newCall(request).execute();
    assertThat(response.code()).isEqualTo(303);

    List<String> cookies = response.headers(HttpHeaders.SET_COOKIE);
    assertThat(cookies).hasSize(1);//from  www. java 2s .c om

    NewCookie cookie = NewCookie.valueOf(cookies.get(0));
    assertThat(cookie.getName()).isEqualTo("session");
    assertThat(cookie.getValue()).isEqualTo("expired");
    assertThat(cookie.getVersion()).isEqualTo(1);
    assertThat(cookie.getPath()).isEqualTo("/admin");
    assertThat(cookie.isSecure()).isTrue();
    assertThat(cookie.isHttpOnly()).isTrue();
    assertThat(cookie.getExpiry()).isEqualTo(new Date(0));
}