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.magnet.max.android.rest.qos.internal.CacheUtils.java

License:Apache License

public static String getRequestHash(Request request) {
    StringBuilder sb = new StringBuilder();
    //Method and URL
    sb.append(request.method()).append(request.urlString());
    //Headers//from  w  w w.  j ava 2  s . co  m
    if (null != request.headers()) {

    }
    //Body
    //Don't include body when it's multipart
    if (toHashBody(request)) {
        try {
            Buffer buffer = new Buffer();
            Request copy = request.newBuilder().build();
            copy.body().writeTo(buffer);
            sb.append(buffer.readUtf8());
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    return Util.md5Hex(sb.toString());
}

From source file:com.magnet.max.android.rest.qos.internal.CacheUtils.java

License:Apache License

private static boolean toHashBody(Request request) {
    if (null == request.body()) {
        return false;
    }/*www  . ja  v  a2  s . c o m*/

    if (null != request.body().contentType()) {
        String mediaType = request.body().contentType().type();
        if (StringUtil.isNotEmpty(mediaType)) {
            mediaType = mediaType.trim().toLowerCase();
            if ((mediaType.startsWith("multipart") || mediaType.startsWith("image")
                    || mediaType.startsWith("video") || mediaType.startsWith("audio"))) {
                return false;
            }
        }
    }

    try {
        long length = request.body().contentLength();
        if (length > MAX_CONTENT_LENGTH_TO_HASH) {
            return false;
        }
    } catch (IOException e) {
        Log.e(TAG, "Failed to get body length", e);
        return false;
    }

    return true;
}

From source file:com.parse.ParseOkHttpClient.java

License:Open Source License

private ParseHttpRequest getParseHttpRequest(Request okHttpRequest) {
    ParseHttpRequest.Builder parseRequestBuilder = new ParseHttpRequest.Builder();
    // Set method
    switch (okHttpRequest.method()) {
    case OKHTTP_GET:
        parseRequestBuilder.setMethod(ParseHttpRequest.Method.GET);
        break;/* w ww . ja va 2s.  c  o  m*/
    case OKHTTP_DELETE:
        parseRequestBuilder.setMethod(ParseHttpRequest.Method.DELETE);
        break;
    case OKHTTP_POST:
        parseRequestBuilder.setMethod(ParseHttpRequest.Method.POST);
        break;
    case OKHTTP_PUT:
        parseRequestBuilder.setMethod(ParseHttpRequest.Method.PUT);
        break;
    default:
        // This should never happen
        throw new IllegalArgumentException("Invalid http method " + okHttpRequest.method());
    }

    // Set url
    parseRequestBuilder.setUrl(okHttpRequest.urlString());

    // Set Header
    for (Map.Entry<String, List<String>> entry : okHttpRequest.headers().toMultimap().entrySet()) {
        parseRequestBuilder.addHeader(entry.getKey(), entry.getValue().get(0));
    }

    // Set Body
    ParseOkHttpRequestBody okHttpBody = (ParseOkHttpRequestBody) okHttpRequest.body();
    if (okHttpBody != null) {
        parseRequestBuilder.setBody(okHttpBody.getParseHttpBody());
    }
    return parseRequestBuilder.build();
}

From source file:com.parse.ParseOkHttpClientTest.java

License:Open Source License

@Test
public void testGetOkHttpRequest() throws IOException {
    Map<String, String> headers = new HashMap<>();
    String headerName = "name";
    String headerValue = "value";
    headers.put(headerName, headerValue);

    String url = "http://www.parse.com/";
    String content = "test";
    int contentLength = content.length();
    String contentType = "application/json";
    ParseHttpRequest parseRequest = new ParseHttpRequest.Builder().setUrl(url)
            .setMethod(ParseHttpRequest.Method.POST).setBody(new ParseByteArrayHttpBody(content, contentType))
            .setHeaders(headers).build();

    ParseOkHttpClient parseClient = new ParseOkHttpClient(10000, null);
    Request okHttpRequest = parseClient.getRequest(parseRequest);

    // Verify method
    assertEquals(ParseHttpRequest.Method.POST.toString(), okHttpRequest.method());
    // Verify URL
    assertEquals(url, okHttpRequest.urlString());
    // Verify Headers
    assertEquals(1, okHttpRequest.headers(headerName).size());
    assertEquals(headerValue, okHttpRequest.headers(headerName).get(0));
    // Verify Body
    RequestBody okHttpBody = okHttpRequest.body();
    assertEquals(contentLength, okHttpBody.contentLength());
    assertEquals(contentType, okHttpBody.contentType().toString());
    // Can not read parseRequest body to compare since it has been read during
    // creating okHttpRequest
    Buffer buffer = new Buffer();
    okHttpBody.writeTo(buffer);/*from w  w w.  j a  va 2s .c o  m*/
    ByteArrayOutputStream output = new ByteArrayOutputStream();
    buffer.copyTo(output);
    assertArrayEquals(content.getBytes(), output.toByteArray());
}

From source file:com.parse.ParseOkHttpClientTest.java

License:Open Source License

@Test
public void testGetOkHttpRequestWithEmptyContentType() throws Exception {
    String url = "http://www.parse.com/";
    String content = "test";
    ParseHttpRequest parseRequest = new ParseHttpRequest.Builder().setUrl(url)
            .setMethod(ParseHttpRequest.Method.POST).setBody(new ParseByteArrayHttpBody(content, null)).build();

    ParseOkHttpClient parseClient = new ParseOkHttpClient(10000, null);
    Request okHttpRequest = parseClient.getRequest(parseRequest);

    // Verify Content-Type
    assertNull(okHttpRequest.body().contentType());
}

From source file:com.rafagarcia.countries.backend.webapi.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  va 2s  . com*/

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

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

        String endMessage = "--> END " + request.method();
        if (logBody && hasRequestBody) {
            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));
        }

        if (logBody) {
            Buffer buffer = new Buffer();
            responseBody.source().readAll(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));
            }

            // Since we consumed the original, replace the one-shot body in the response with a new one.
            response = response.newBuilder()
                    .body(ResponseBody.create(contentType, responseBody.contentLength(), buffer)).build();
        }

        String endMessage = "<-- END HTTP";
        if (logBody) {
            endMessage += " (" + responseBody.contentLength() + "-byte body)";
        }
        logger.log(endMessage);
    }

    return response;
}

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

License:Apache License

@Test
public void builderAcceptsPathParams() throws Exception {
    CallSpec.Builder builder = builder(HttpMethod.GET, "/{param1}/{param2}", false).responseAs(Object.class)
            .pathParam("param1", "test1").pathParam("param2", "test2");
    builder.build();// w ww. ja v a  2  s .c o m

    Request request = builder.request();
    assertThat(request.method()).isEqualTo(HttpMethod.GET.method());
    assertThat(request.urlString()).isEqualTo(httpUrl + "test1/test2");
    assertThat(request.body()).isNull();
}

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

License:Apache License

@Test
public void builderAcceptsPathParamsAsVarList() throws Exception {
    CallSpec.Builder builder = builder(HttpMethod.GET, "/{params}", false).responseAs(Object.class)
            .pathParam("params", "one", "two", "three");
    builder.build();//  w  w w.  j a v a  2  s . c  o  m

    Request request = builder.request();
    assertThat(request.method()).isEqualTo(HttpMethod.GET.method());
    assertThat(request.urlString()).isEqualTo(httpUrl + "one,two,three");
    assertThat(request.body()).isNull();
}

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

License:Apache License

@Test
public void builderAcceptsPathParamsAsList() throws Exception {
    List<String> params = new ArrayList<>(3);
    params.add("one");
    params.add("two");
    params.add("three");

    CallSpec.Builder builder = builder(HttpMethod.GET, "/{params}", false).responseAs(Object.class)
            .pathParam("params", params);
    builder.build();/*from   ww w .  j  a v a2  s . c  o m*/

    Request request = builder.request();
    assertThat(request.method()).isEqualTo(HttpMethod.GET.method());
    assertThat(request.urlString()).isEqualTo(httpUrl + "one,two,three");
    assertThat(request.body()).isNull();
}

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

License:Apache License

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

    Request request = builder.request();
    assertThat(request.method()).isEqualTo(HttpMethod.GET.method());
    assertThat(request.urlString()).isEqualTo(httpUrl + "?q=test1&w=test2");
    assertThat(request.body()).isNull();
}