Example usage for com.squareup.okhttp RequestBody writeTo

List of usage examples for com.squareup.okhttp RequestBody writeTo

Introduction

In this page you can find the example usage for com.squareup.okhttp RequestBody writeTo.

Prototype

public abstract void writeTo(BufferedSink sink) throws IOException;

Source Link

Document

Writes the content of this request to out .

Usage

From source file:com.ibm.watson.developer_cloud.service.RequestBuilderTest.java

License:Open Source License

/**
 * Test with form object array.// w  w w . j a v a 2s.com
 * 
 * @throws IOException Signals that an I/O exception has occurred.
 */
@Test
public void testWithFormObjectArray() throws IOException {
    final String body = "foo=bar&test1=test2";
    final Request request = RequestBuilder.post(urlWithQuery).withForm("foo", "bar", "test1", "test2").build();

    final RequestBody requestedBody = request.body();

    final Buffer buffer = new Buffer();
    requestedBody.writeTo(buffer);

    assertEquals(body, buffer.readUtf8());
    assertEquals(MediaType.parse(HttpMediaType.APPLICATION_FORM_URLENCODED), requestedBody.contentType());
}

From source file:com.liferay.mobile.android.auth.CookieSignIn.java

License:Open Source License

protected String getBody(String username, String password) throws IOException {

    RequestBody formBody = new FormEncodingBuilder().add("login", username).add("password", password).build();

    Buffer buffer = new Buffer();
    formBody.writeTo(buffer);

    return buffer.readUtf8();
}

From source file:com.liferay.mobile.sdk.auth.CookieSignIn.java

License:Open Source License

protected static String getBody(BasicAuthentication auth) throws IOException {

    RequestBody formBody = new FormEncodingBuilder().add("login", auth.username())
            .add("password", auth.password()).build();

    Buffer buffer = new Buffer();
    formBody.writeTo(buffer);

    return buffer.readUtf8();
}

From source file:com.magnet.max.android.tests.MagnetGsonConverterTest.java

License:Apache License

private void assertResponseBody(RequestBody requestBody, String str) {
    try {/*from   w  ww . j a va2s.c  om*/
        Buffer buffer = new Buffer();
        requestBody.writeTo(buffer);
        assertEquals(str, buffer.readUtf8());
    } catch (IOException e) {
        e.printStackTrace();
        fail(e.getMessage());
    }
}

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);
    ByteArrayOutputStream output = new ByteArrayOutputStream();
    buffer.copyTo(output);/*w  w  w. java  2s.  c om*/
    assertArrayEquals(content.getBytes(), output.toByteArray());
}

From source file:com.piusvelte.okoauth.RequestBuilder.java

License:Apache License

@Override
public Request.Builder method(String method, RequestBody body) {
    mMethod = method;//from w  ww  .  j  a v  a2 s . co m

    if (body != null && body.contentType().toString().startsWith("application/x-www-form-urlencoded")) {
        Buffer sink = new Buffer();
        try {
            body.writeTo(sink);
            mFormBody = sink.readUtf8();
        } catch (IOException e) {
            if (BuildConfig.DEBUG) {
                Log.e(TAG, "error getting form body", e);
            }
        }
    }

    return super.method(method, body);
}

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  www  .  ja v  a 2 s.  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.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();
    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();
    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 ww . j a v a 2s.c o  m

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