Example usage for com.squareup.okhttp Request headers

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

Introduction

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

Prototype

Headers headers

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

Click Source Link

Usage

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.xing.api.CallSpecTest.java

License:Apache License

@Test
public void builderAcceptsHeaders() throws Exception {
    CallSpec.Builder builder = builder(HttpMethod.GET, "/", false).responseAs(Object.class)
            .header("Test1", "hello").header("Test2", "hm");
    builder.build();/*from  w  w  w  .  ja v a 2  s  .  com*/

    Request request = builder.request();
    assertThat(request.method()).isEqualTo(HttpMethod.GET.method());
    assertThat(request.headers().names()).contains("Test1").contains("Test2");
    assertThat(request.headers().values("Test1")).isNotEmpty().hasSize(1).contains("hello");
    assertThat(request.headers().values("Test2")).isNotEmpty().hasSize(1).contains("hm");
}

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 ww  w.j  a  v  a2  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:feign.okhttp.OkHttpClient.java

License:Apache License

static Request toOkHttpRequest(feign.Request input) {
    Request.Builder requestBuilder = new Request.Builder();
    requestBuilder.url(input.url());/*from  www  . j  av  a2 s .  c  o  m*/

    MediaType mediaType = null;
    boolean hasAcceptHeader = false;
    for (String field : input.headers().keySet()) {
        if (field.equalsIgnoreCase("Accept")) {
            hasAcceptHeader = true;
        }

        for (String value : input.headers().get(field)) {
            if (field.equalsIgnoreCase("Content-Type")) {
                mediaType = MediaType.parse(value);
                if (input.charset() != null) {
                    mediaType.charset(input.charset());
                }
            } else {
                requestBuilder.addHeader(field, value);
            }
        }
    }
    // Some servers choke on the default accept string.
    if (!hasAcceptHeader) {
        requestBuilder.addHeader("Accept", "*/*");
    }

    RequestBody body = input.body() != null ? RequestBody.create(mediaType, input.body()) : null;
    requestBuilder.method(input.method(), body);
    return requestBuilder.build();
}

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

License:Apache License

/**
 * Aggressively tries to get the final HTTP response, potentially making
 * many HTTP requests in the process in order to cope with redirects and
 * authentication./*  w ww  .j  a va  2  s.c  o  m*/
 */
private HttpEngine getResponse() throws IOException {
    initHttpEngine();

    if (httpEngine.hasResponse()) {
        return httpEngine;
    }

    while (true) {
        if (!execute(true)) {
            continue;
        }

        Response response = httpEngine.getResponse();
        Request followUp = httpEngine.followUpRequest();

        if (followUp == null) {
            httpEngine.releaseConnection();
            return httpEngine;
        }

        if (++followUpCount > HttpEngine.MAX_FOLLOW_UPS) {
            throw new ProtocolException("Too many follow-up requests: " + followUpCount);
        }

        // The first request was insufficient. Prepare for another...
        url = followUp.url();
        requestHeaders = followUp.headers().newBuilder();

        // Although RFC 2616 10.3.2 specifies that a HTTP_MOVED_PERM redirect
        // should keep the same method, Chrome, Firefox and the RI all issue GETs
        // when following any redirect.
        Sink requestBody = httpEngine.getRequestBody();
        if (!followUp.method().equals(method)) {
            requestBody = null;
        }

        if (requestBody != null && !(requestBody instanceof RetryableSink)) {
            throw new HttpRetryException("Cannot retry streamed HTTP body", responseCode);
        }

        if (!httpEngine.sameConnection(followUp.url())) {
            httpEngine.releaseConnection();
        }

        Connection connection = httpEngine.close();
        httpEngine = newHttpEngine(followUp.method(), connection, (RetryableSink) requestBody, response);
    }
}

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);
    }//from  w w  w . ja  va2  s .  c  o  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.minio.errors.ErrorResponseException.java

License:Apache License

@Override
public String toString() {
    Request request = response.request();
    return "error occured\n" + errorResponse.getString() + "\n" + "request={" + "method=" + request.method()
            + ", " + "url=" + request.httpUrl() + ", " + "headers=" + request.headers() + "}\n" + "response={"
            + "code=" + response.code() + ", " + "headers=" + response.headers() + "}\n";
}

From source file:io.minio.MinioClient.java

License:Apache License

/**
 * Executes given request parameters./*from  w w w. j  a  v a 2 s .c o 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:io.minio.RequestSigner.java

License:Apache License

private String getSignedHeaders(Request request) {
    StringBuilder builder = new StringBuilder();
    boolean printSeparator = false;
    for (String header : request.headers().names()) {
        if (!ignoredHeaders.contains(header.toLowerCase().trim())) {
            if (printSeparator) {
                builder.append(';');
            } else {
                printSeparator = true;//  ww  w  .j av  a2 s.c o m
            }
            builder.append(header);
        }
    }
    return builder.toString();
}

From source file:io.minio.RequestSigner.java

License:Apache License

private Map<String, String> getCanonicalHeaders(Request request) throws IOException {
    Map<String, String> map = new TreeMap<String, String>(String.CASE_INSENSITIVE_ORDER);
    for (String s : request.headers().names()) {
        String val = request.headers().get(s);
        if (val != null) {
            String headerKey = s.toLowerCase().trim();
            String headerValue = val.trim();
            if (!ignoredHeaders.contains(headerKey)) {
                map.put(headerKey, headerValue);
            }/*from   w ww .  ja  v a2s.  com*/
        }
    }
    return map;
}