Example usage for com.squareup.okhttp Request body

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

Introduction

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

Prototype

RequestBody body

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

Click Source Link

Usage

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

License:Apache License

@Test
public void builderAttachesQueryParamsAsVarList() throws Exception {
    CallSpec.Builder builder = builder(HttpMethod.GET, "", false).responseAs(Object.class).queryParam("q",
            "testL", "testL");
    // Build the CallSpec so that we don't test this behaviour twice.
    builder.build().queryParam("w", "testL", "testL");

    Request request = builder.request();
    assertThat(request.method()).isEqualTo(HttpMethod.GET.method());
    assertThat(request.urlString()).isEqualTo(httpUrl + "?q=testL%2C%20testL&w=testL%2C%20testL");
    assertThat(request.body()).isNull();
}

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

License:Apache License

@Test
public void builderAttachesQueryParamsAsList() throws Exception {
    List<String> query = new ArrayList<>(2);
    query.add("testL");
    query.add("testL");

    CallSpec.Builder builder = builder(HttpMethod.GET, "", false).responseAs(Object.class).queryParam("q",
            query);//  w  w  w .j  av  a  2  s .co  m
    // Build the CallSpec so that we don't test this behaviour twice.
    builder.build().queryParam("w", query);

    Request request = builder.request();
    assertThat(request.method()).isEqualTo(HttpMethod.GET.method());
    assertThat(request.urlString()).isEqualTo(httpUrl + "?q=testL%2C%20testL&w=testL%2C%20testL");
    assertThat(request.body()).isNull();
}

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();//  w w w . j a  v a2 s  .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();//from   ww  w  . j  a v 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();//  w w w  . j  av  a 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.CallSpecTest.java

License:Apache License

@Test
public void builderAllowsRawBody() throws Exception {
    CallSpec.Builder builder = builder(HttpMethod.PUT, "", false).responseAs(Object.class)
            .body(RequestBody.create(MediaType.parse("application/text"), "Hey!"));
    // Build the CallSpec so that we can build the request.
    builder.build();/*from ww w  . j a  v a2  s .com*/

    Request request = builder.request();
    RequestBody body = request.body();
    assertThat(body.contentLength()).isEqualTo(4);
    assertThat(body.contentType().subtype()).isEqualTo("text");

    Buffer buffer = new Buffer();
    body.writeTo(buffer);
    assertThat(buffer.readUtf8()).isEqualTo("Hey!");
}

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

License:Apache License

private static void assertRequestHasBody(Request request, TestMsg expected, int contentLength)
        throws IOException {
    RequestBody body = request.body();
    assertThat(body.contentLength()).isEqualTo(contentLength);
    assertThat(body.contentType().subtype()).isEqualTo("json");

    Buffer buffer = new Buffer();
    body.writeTo(buffer);//  w ww  .j a v a 2 s.  c  o m
    assertThat(buffer.readUtf8()).contains("\"msg\":\"" + expected.msg + '"')
            .contains("\"code\":" + expected.code).startsWith("{").endsWith("}").hasSize(contentLength);
}

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 w ww. j av a 2  s .  co  m
    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);
        }//from   w ww  .j av a 2  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());//ww w.  j a  v a 2  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();
}