Search in sources :

Example 36 with RequestBody

use of okhttp3.RequestBody in project retrofit by square.

the class RequestBuilderTest method bodyWithPathParams.

@Test
public void bodyWithPathParams() {
    class Example {

        //
        @POST("/foo/bar/{ping}/{kit}/")
        Call<ResponseBody> method(@Path("ping") String ping, @Body RequestBody body, @Path("kit") String kit) {
            return null;
        }
    }
    RequestBody body = RequestBody.create(TEXT_PLAIN, "Hi!");
    Request request = buildRequest(Example.class, "pong", body, "kat");
    assertThat(request.method()).isEqualTo("POST");
    assertThat(request.headers().size()).isZero();
    assertThat(request.url().toString()).isEqualTo("http://example.com/foo/bar/pong/kat/");
    assertBody(request.body(), "Hi!");
}
Also used : Path(retrofit2.http.Path) Request(okhttp3.Request) RequestBody(okhttp3.RequestBody) ResponseBody(okhttp3.ResponseBody) MultipartBody(okhttp3.MultipartBody) Body(retrofit2.http.Body) RequestBody(okhttp3.RequestBody) ResponseBody(okhttp3.ResponseBody) Test(org.junit.Test)

Example 37 with RequestBody

use of okhttp3.RequestBody in project okhttp by square.

the class URLConnectionTest method testResponseRedirectedWithPost.

private void testResponseRedirectedWithPost(int redirectCode, TransferKind transferKind) throws Exception {
    server.enqueue(new MockResponse().setResponseCode(redirectCode).addHeader("Location: /page2").setBody("This page has moved!"));
    server.enqueue(new MockResponse().setBody("Page 2"));
    connection = urlFactory.open(server.url("/page1").url());
    connection.setDoOutput(true);
    transferKind.setForRequest(connection, 4);
    byte[] requestBody = { 'A', 'B', 'C', 'D' };
    OutputStream outputStream = connection.getOutputStream();
    outputStream.write(requestBody);
    outputStream.close();
    assertEquals("Page 2", readAscii(connection.getInputStream(), Integer.MAX_VALUE));
    assertTrue(connection.getDoOutput());
    RecordedRequest page1 = server.takeRequest();
    assertEquals("POST /page1 HTTP/1.1", page1.getRequestLine());
    assertEquals("ABCD", page1.getBody().readUtf8());
    RecordedRequest page2 = server.takeRequest();
    assertEquals("GET /page2 HTTP/1.1", page2.getRequestLine());
}
Also used : RecordedRequest(okhttp3.mockwebserver.RecordedRequest) MockResponse(okhttp3.mockwebserver.MockResponse) OutputStream(java.io.OutputStream)

Example 38 with RequestBody

use of okhttp3.RequestBody in project okhttp by square.

the class URLConnectionTest method testAuthenticateWithStreamingPost.

private void testAuthenticateWithStreamingPost(StreamingMode streamingMode) throws Exception {
    MockResponse pleaseAuthenticate = new MockResponse().setResponseCode(401).addHeader("WWW-Authenticate: Basic realm=\"protected area\"").setBody("Please authenticate.");
    server.enqueue(pleaseAuthenticate);
    Authenticator.setDefault(new RecordingAuthenticator());
    urlFactory.setClient(urlFactory.client().newBuilder().authenticator(new JavaNetAuthenticator()).build());
    connection = urlFactory.open(server.url("/").url());
    connection.setDoOutput(true);
    byte[] requestBody = { 'A', 'B', 'C', 'D' };
    if (streamingMode == StreamingMode.FIXED_LENGTH) {
        connection.setFixedLengthStreamingMode(requestBody.length);
    } else if (streamingMode == StreamingMode.CHUNKED) {
        connection.setChunkedStreamingMode(0);
    }
    OutputStream outputStream = connection.getOutputStream();
    outputStream.write(requestBody);
    outputStream.close();
    try {
        connection.getInputStream();
        fail();
    } catch (HttpRetryException expected) {
    }
    // no authorization header for the request...
    RecordedRequest request = server.takeRequest();
    assertNull(request.getHeader("Authorization"));
    assertEquals("ABCD", request.getBody().readUtf8());
}
Also used : RecordedRequest(okhttp3.mockwebserver.RecordedRequest) MockResponse(okhttp3.mockwebserver.MockResponse) OutputStream(java.io.OutputStream) HttpRetryException(java.net.HttpRetryException) RecordingAuthenticator(okhttp3.internal.RecordingAuthenticator)

Example 39 with RequestBody

use of okhttp3.RequestBody in project okhttp by square.

the class URLConnectionTest method testRedirect.

private void testRedirect(boolean temporary, String method) throws Exception {
    MockResponse response1 = new MockResponse().setResponseCode(temporary ? HTTP_TEMP_REDIRECT : HTTP_PERM_REDIRECT).addHeader("Location: /page2");
    if (!method.equals("HEAD")) {
        response1.setBody("This page has moved!");
    }
    server.enqueue(response1);
    server.enqueue(new MockResponse().setBody("Page 2"));
    connection = urlFactory.open(server.url("/page1").url());
    connection.setRequestMethod(method);
    byte[] requestBody = { 'A', 'B', 'C', 'D' };
    if (method.equals("POST")) {
        connection.setDoOutput(true);
        OutputStream outputStream = connection.getOutputStream();
        outputStream.write(requestBody);
        outputStream.close();
    }
    String response = readAscii(connection.getInputStream(), Integer.MAX_VALUE);
    RecordedRequest page1 = server.takeRequest();
    assertEquals(method + " /page1 HTTP/1.1", page1.getRequestLine());
    if (method.equals("GET")) {
        assertEquals("Page 2", response);
    } else if (method.equals("HEAD")) {
        assertEquals("", response);
    } else {
        // Methods other than GET/HEAD shouldn't follow the redirect
        if (method.equals("POST")) {
            assertTrue(connection.getDoOutput());
            assertEquals("ABCD", page1.getBody().readUtf8());
        }
        assertEquals(1, server.getRequestCount());
        assertEquals("This page has moved!", response);
        return;
    }
    // GET/HEAD requests should have followed the redirect with the same method
    assertFalse(connection.getDoOutput());
    assertEquals(2, server.getRequestCount());
    RecordedRequest page2 = server.takeRequest();
    assertEquals(method + " /page2 HTTP/1.1", page2.getRequestLine());
}
Also used : RecordedRequest(okhttp3.mockwebserver.RecordedRequest) MockResponse(okhttp3.mockwebserver.MockResponse) OutputStream(java.io.OutputStream)

Example 40 with RequestBody

use of okhttp3.RequestBody in project okhttp by square.

the class URLConnectionTest method reusedConnectionFailsWithPost.

private void reusedConnectionFailsWithPost(TransferKind transferKind, int requestSize) throws Exception {
    server.enqueue(new MockResponse().setBody("A").setSocketPolicy(DISCONNECT_AT_END));
    server.enqueue(new MockResponse().setBody("B"));
    server.enqueue(new MockResponse().setBody("C"));
    assertContent("A", urlFactory.open(server.url("/a").url()));
    // Give the server time to disconnect.
    Thread.sleep(500);
    // If the request body is larger than OkHttp's replay buffer, the failure may still occur.
    byte[] requestBody = new byte[requestSize];
    new Random(0).nextBytes(requestBody);
    for (int j = 0; j < 2; j++) {
        try {
            connection = urlFactory.open(server.url("/b").url());
            connection.setRequestMethod("POST");
            transferKind.setForRequest(connection, requestBody.length);
            for (int i = 0; i < requestBody.length; i += 1024) {
                connection.getOutputStream().write(requestBody, i, 1024);
            }
            connection.getOutputStream().close();
            assertContent("B", connection);
            break;
        } catch (IOException socketException) {
            // If there's a socket exception, this must have a streamed request body.
            assertEquals(0, j);
            assertTrue(transferKind == TransferKind.CHUNKED || transferKind == TransferKind.FIXED_LENGTH);
        }
    }
    RecordedRequest requestA = server.takeRequest();
    assertEquals("/a", requestA.getPath());
    RecordedRequest requestB = server.takeRequest();
    assertEquals("/b", requestB.getPath());
    assertEquals(Arrays.toString(requestBody), Arrays.toString(requestB.getBody().readByteArray()));
}
Also used : RecordedRequest(okhttp3.mockwebserver.RecordedRequest) MockResponse(okhttp3.mockwebserver.MockResponse) Random(java.util.Random) IOException(java.io.IOException)

Aggregations

RequestBody (okhttp3.RequestBody)178 Request (okhttp3.Request)141 IOException (java.io.IOException)75 Response (okhttp3.Response)74 Test (org.junit.Test)53 ResponseBody (okhttp3.ResponseBody)32 Call (okhttp3.Call)31 MultipartBody (okhttp3.MultipartBody)28 MediaType (okhttp3.MediaType)27 FormBody (okhttp3.FormBody)25 Callback (okhttp3.Callback)23 Buffer (okio.Buffer)23 MockResponse (okhttp3.mockwebserver.MockResponse)18 RecordedRequest (okhttp3.mockwebserver.RecordedRequest)16 TestClients.clientRequest (keywhiz.TestClients.clientRequest)15 BufferedSink (okio.BufferedSink)15 Headers (okhttp3.Headers)12 HttpUrl (okhttp3.HttpUrl)11 JSONObject (org.json.JSONObject)11 Body (retrofit2.http.Body)11