Example usage for com.squareup.okhttp Request method

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

Introduction

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

Prototype

String method

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

Click Source Link

Usage

From source file:com.xing.api.CallSpecTest.java

License:Apache License

@Test
public void builderAttachesFormFields() throws Exception {
    CallSpec.Builder builder = builder(HttpMethod.PUT, "", true).responseAs(Object.class).formField("f",
            "true");
    // Build the CallSpec so that we don't test this behaviour twice.
    builder.build().formField("e", "false");

    Request request = builder.request();
    assertThat(request.method()).isEqualTo(HttpMethod.PUT.method());
    assertThat(request.httpUrl()).isEqualTo(httpUrl);
    assertThat(request.body()).isNotNull();

    RequestBody body = request.body();//from w ww . j  ava 2s . com
    assertThat(body.contentType()).isEqualTo(MediaType.parse("application/x-www-form-urlencoded"));

    Buffer buffer = new Buffer();
    body.writeTo(buffer);
    assertThat(buffer.readUtf8()).isEqualTo("f=true&e=false");
}

From source file:com.xing.api.CallSpecTest.java

License:Apache License

@Test
public void builderAttachesFormFieldsAsLists() throws Exception {
    CallSpec.Builder builder = builder(HttpMethod.PUT, "", true).responseAs(Object.class).formField("f",
            "test1", "test2");
    // Build the CallSpec so that we don't test this behaviour twice.
    List<String> field = new ArrayList<>(2);
    field.add("test3");
    field.add("test4");
    builder.build().formField("e", field).formField("d", "test5", "test6");

    Request request = builder.request();
    assertThat(request.method()).isEqualTo(HttpMethod.PUT.method());
    assertThat(request.httpUrl()).isEqualTo(httpUrl);
    assertThat(request.body()).isNotNull();

    RequestBody body = request.body();/*w ww.j av a2 s .c om*/
    assertThat(body.contentType()).isEqualTo(MediaType.parse("application/x-www-form-urlencoded"));

    Buffer buffer = new Buffer();
    body.writeTo(buffer);
    assertThat(buffer.readUtf8()).isEqualTo("f=test1%2C%20test2&e=test3%2C%20test4&d=test5%2C%20test6");
}

From source file:com.xing.api.CallSpecTest.java

License:Apache License

@Test
public void builderEnsuresEmptyBody() throws Exception {
    CallSpec.Builder builder = builder(HttpMethod.PUT, "", false).responseAs(Object.class);
    // Build the CallSpec so that we can build the request.
    builder.build();/*from   ww w .  ja  va  2  s . c om*/

    Request request = builder.request();
    assertThat(request.method()).isEqualTo(HttpMethod.PUT.method());
    assertThat(request.httpUrl()).isEqualTo(httpUrl);
    assertThat(request.body()).isNotNull();

    RequestBody body = request.body();
    assertThat(body.contentType()).isNull();
    assertThat(body.contentLength()).isEqualTo(0);

    Buffer buffer = new Buffer();
    body.writeTo(buffer);
    assertThat(buffer.readUtf8()).isEmpty();
}

From source file:com.xing.api.Oauth1SigningInterceptor.java

License:Apache License

public Request signRequest(Request request) throws IOException {
    byte[] nonce = new byte[NUANCE_BYTES];
    random.nextBytes(nonce);/*from ww w. ja  va2s  . c om*/
    String oauthNonce = CHARACTER_PATTERN.matcher(ByteString.of(nonce).base64()).replaceAll("");
    String oauthTimestamp = clock.millis();

    String consumerKeyValue = UrlEscapeUtils.escape(consumerKey);
    String accessTokenValue = UrlEscapeUtils.escape(accessToken);

    SortedMap<String, String> parameters = new TreeMap<>();
    parameters.put(OAUTH_CONSUMER_KEY, consumerKeyValue);
    parameters.put(OAUTH_ACCESS_TOKEN, accessTokenValue);
    parameters.put(OAUTH_NONCE, oauthNonce);
    parameters.put(OAUTH_TIMESTAMP, oauthTimestamp);
    parameters.put(OAUTH_SIGNATURE_METHOD, OAUTH_SIGNATURE_METHOD_VALUE);
    parameters.put(OAUTH_VERSION, OAUTH_VERSION_VALUE);

    HttpUrl url = request.httpUrl();
    for (int i = 0; i < url.querySize(); i++) {
        parameters.put(UrlEscapeUtils.escape(url.queryParameterName(i)),
                UrlEscapeUtils.escape(url.queryParameterValue(i)));
    }

    Buffer body = new Buffer();
    RequestBody requestBody = request.body();
    if (requestBody != null) {
        requestBody.writeTo(body);
    }

    while (!body.exhausted()) {
        long keyEnd = body.indexOf((byte) '=');
        if (keyEnd == -1) {
            throw new IllegalStateException("Key with no value: " + body.readUtf8());
        }
        String key = body.readUtf8(keyEnd);
        body.skip(1); // Equals.

        long valueEnd = body.indexOf((byte) '&');
        String value = valueEnd == -1 ? body.readUtf8() : body.readUtf8(valueEnd);
        if (valueEnd != -1) {
            body.skip(1); // Ampersand.
        }

        parameters.put(key, value);
    }

    Buffer base = new Buffer();
    String method = request.method();
    base.writeUtf8(method);
    base.writeByte('&');
    base.writeUtf8(UrlEscapeUtils.escape(request.httpUrl().newBuilder().query(null).build().toString()));
    base.writeByte('&');

    boolean first = true;
    for (Entry<String, String> entry : parameters.entrySet()) {
        if (!first) {
            base.writeUtf8(UrlEscapeUtils.escape("&"));
        }
        first = false;
        base.writeUtf8(UrlEscapeUtils.escape(entry.getKey()));
        base.writeUtf8(UrlEscapeUtils.escape("="));
        base.writeUtf8(UrlEscapeUtils.escape(entry.getValue()));
    }

    String signingKey = UrlEscapeUtils.escape(consumerSecret) + '&' + UrlEscapeUtils.escape(accessSecret);
    SecretKeySpec keySpec = new SecretKeySpec(signingKey.getBytes(), "HmacSHA1");
    Mac mac;
    try {
        mac = Mac.getInstance("HmacSHA1");
        mac.init(keySpec);
    } catch (NoSuchAlgorithmException | InvalidKeyException e) {
        throw new IllegalStateException(e);
    }
    byte[] result = mac.doFinal(base.readByteArray());
    String signature = ByteString.of(result).base64();

    String authorization = "OAuth " //
            + OAUTH_CONSUMER_KEY + "=\"" + consumerKeyValue + "\", " //
            + OAUTH_NONCE + "=\"" + oauthNonce + "\", " //
            + OAUTH_SIGNATURE + "=\"" + UrlEscapeUtils.escape(signature) + "\", " //
            + OAUTH_SIGNATURE_METHOD + "=\"" + OAUTH_SIGNATURE_METHOD_VALUE + "\", " //
            + OAUTH_TIMESTAMP + "=\"" + oauthTimestamp + "\", " //
            + OAUTH_ACCESS_TOKEN + "=\"" + accessTokenValue + "\", " //
            + OAUTH_VERSION + "=\"" + OAUTH_VERSION_VALUE + '"';

    return request.newBuilder().addHeader("Authorization", authorization).build();
}

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);
        }/*  w  w  w.jav  a  2s  .  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());//w  ww  .  j  a va2 s.  co 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.//  www.j  a  v  a 2s.  c om
 */
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.appium.uiautomator2.unittest.test.internal.Client.java

License:Apache License

private static Response execute(final Request request) {
    try {//from w  w  w  . j  a  va2 s.co  m
        return new Response(HTTP_CLIENT.newCall(request).execute());
    } catch (IOException e) {
        throw new UiAutomator2Exception(request.method() + " \"" + request.urlString() + "\" " + "failed. ", e);
    }
}

From source file:io.fabric8.docker.client.impl.OperationSupport.java

License:Apache License

DockerClientException requestFailure(Request request, Response response) {
    StringBuilder sb = new StringBuilder();
    sb.append("Failure executing: ").append(request.method()).append(" at: ").append(request.urlString())
            .append(".").append(" Status:").append(response.code()).append(".").append(" Message: ")
            .append(response.message()).append(".");
    try {//  w  ww.  j a  v  a2s  .  c  o  m
        String body = response.body().string();
        sb.append(" Body: ").append(body);
    } catch (Throwable t) {
        sb.append(" Body: <unreadable>");
    }
    return new DockerClientException(sb.toString(), response.code());
}

From source file:io.fabric8.docker.client.impl.OperationSupport.java

License:Apache License

DockerClientException requestException(Request request, Exception e) {
    StringBuilder sb = new StringBuilder();
    sb.append("Error executing: ").append(request.method()).append(" at: ").append(request.urlString())
            .append(". Cause: ").append(e.getMessage());

    return new DockerClientException(sb.toString(), e);
}