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.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);/* w ww  .j  a v  a 2  s.  c  o m*/
    ByteArrayOutputStream output = new ByteArrayOutputStream();
    buffer.copyTo(output);
    assertArrayEquals(content.getBytes(), output.toByteArray());
}

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);
    }//from ww w .j a va  2s.  c om

    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.spotify.apollo.http.client.HttpClient.java

License:Apache License

@Override
public CompletionStage<com.spotify.apollo.Response<ByteString>> send(com.spotify.apollo.Request apolloRequest,
        Optional<com.spotify.apollo.Request> apolloIncomingRequest) {

    final Optional<RequestBody> requestBody = apolloRequest.payload().map(payload -> {
        final MediaType contentType = apolloRequest.header("Content-Type").map(MediaType::parse)
                .orElse(DEFAULT_CONTENT_TYPE);
        return RequestBody.create(contentType, payload);
    });/*  w w  w  .j a v  a  2 s  . c o  m*/

    Headers.Builder headersBuilder = new Headers.Builder();
    apolloRequest.headers().asMap().forEach((k, v) -> headersBuilder.add(k, v));

    apolloIncomingRequest.flatMap(req -> req.header(AUTHORIZATION_HEADER))
            .ifPresent(header -> headersBuilder.add(AUTHORIZATION_HEADER, header));

    final Request request = new Request.Builder().method(apolloRequest.method(), requestBody.orElse(null))
            .url(apolloRequest.uri()).headers(headersBuilder.build()).build();

    final CompletableFuture<com.spotify.apollo.Response<ByteString>> result = new CompletableFuture<>();

    //https://github.com/square/okhttp/wiki/Recipes#per-call-configuration
    OkHttpClient finalClient = client;
    if (apolloRequest.ttl().isPresent() && client.getReadTimeout() != apolloRequest.ttl().get().toMillis()) {
        finalClient = client.clone();
        finalClient.setReadTimeout(apolloRequest.ttl().get().toMillis(), TimeUnit.MILLISECONDS);
    }

    finalClient.newCall(request).enqueue(TransformingCallback.create(result));

    return result;
}

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();//from w w w  .  j av  a2s  .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();/*from   www  .j ava 2  s . co  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();/* ww w . j  a  v  a  2  s .  c om*/

    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 builderAcceptsHeaders() throws Exception {
    CallSpec.Builder builder = builder(HttpMethod.GET, "/", false).responseAs(Object.class)
            .header("Test1", "hello").header("Test2", "hm");
    builder.build();/*from www. j  a va2s.  c o m*/

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

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.  ja  va  2  s  . c o 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();
}