Example usage for com.squareup.okhttp Response body

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

Introduction

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

Prototype

ResponseBody body

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

Click Source Link

Usage

From source file:co.paralleluniverse.fibers.okhttp.CallTest.java

License:Open Source License

@Test
public void redirectsDoNotIncludeTooManyCookies() throws Exception {
    server2.enqueue(new MockResponse().setBody("Page 2"));
    server.enqueue(new MockResponse().setResponseCode(HttpURLConnection.HTTP_MOVED_TEMP)
            .addHeader("Location: " + server2.getUrl("/")));

    CookieManager cookieManager = new CookieManager(null, ACCEPT_ORIGINAL_SERVER);
    HttpCookie cookie = new HttpCookie("c", "cookie");
    cookie.setDomain(server.get().getCookieDomain());
    cookie.setPath("/");
    String portList = Integer.toString(server.getPort());
    cookie.setPortlist(portList);//from   w w w .j a  v a 2s.  c o  m
    cookieManager.getCookieStore().add(server.getUrl("/").toURI(), cookie);
    client.setCookieHandler(cookieManager);

    Response response = FiberOkHttpUtil.executeInFiber(client,
            new Request.Builder().url(server.getUrl("/page1")).build());
    assertEquals("Page 2", response.body().string());

    RecordedRequest request1 = server.takeRequest();
    assertEquals("$Version=\"1\"; c=\"cookie\";$Path=\"/\";$Domain=\"" + server.get().getCookieDomain()
            + "\";$Port=\"" + portList + "\"", request1.getHeader("Cookie"));

    RecordedRequest request2 = server2.takeRequest();
    assertNull(request2.getHeader("Cookie"));
}

From source file:co.paralleluniverse.fibers.okhttp.CallTest.java

License:Open Source License

@Test
public void redirectsDoNotIncludeTooManyAuthHeaders() throws Exception {
    server2.enqueue(new MockResponse().setBody("Page 2"));
    server.enqueue(new MockResponse().setResponseCode(401));
    server.enqueue(new MockResponse().setResponseCode(302).addHeader("Location: " + server2.getUrl("/b")));

    client.setAuthenticator(new RecordingOkAuthenticator(Credentials.basic("jesse", "secret")));

    Request request = new Request.Builder().url(server.getUrl("/a")).build();
    Response response = FiberOkHttpUtil.executeInFiber(client, request);
    assertEquals("Page 2", response.body().string());

    RecordedRequest redirectRequest = server2.takeRequest();
    assertNull(redirectRequest.getHeader("Authorization"));
    assertEquals("/b", redirectRequest.getPath());
}

From source file:co.paralleluniverse.fibers.okhttp.CallTest.java

License:Open Source License

/**
 * There's a race condition where the cancel may apply after the stream has already been
 * processed./*ww w  .ja  va2s  .  c o  m*/
 */
@Test
public void canceledAfterResponseIsDeliveredBreaksStreamButSignalsOnce() throws Exception {
    server.enqueue(new MockResponse().setBody("A"));

    final CountDownLatch latch = new CountDownLatch(1);
    final AtomicReference<String> bodyRef = new AtomicReference<>();
    final AtomicBoolean failureRef = new AtomicBoolean();

    Request request = new Request.Builder().url(server.getUrl("/a")).tag("request A").build();
    final Call call = client.newCall(request);
    call.enqueue(new Callback() {
        @Override
        public void onFailure(Request request, IOException e) {
            failureRef.set(true);
            latch.countDown();
        }

        @Override
        public void onResponse(Response response) throws IOException {
            call.cancel();
            try {
                bodyRef.set(response.body().string());
            } catch (IOException e) { // It is ok if this broke the stream.
                bodyRef.set("A");
                throw e; // We expect to not loop into onFailure in this case.
            } finally {
                latch.countDown();
            }
        }
    });

    latch.await();
    assertEquals("A", bodyRef.get());
    assertFalse(failureRef.get());
}

From source file:co.paralleluniverse.fibers.okhttp.CallTest.java

License:Open Source License

@Test
public void asyncResponseCanBeConsumedLater() throws Exception {
    server.enqueue(new MockResponse().setBody("abc"));
    server.enqueue(new MockResponse().setBody("def"));

    Request request = new Request.Builder().url(server.getUrl("/")).header("User-Agent", "SyncApiTest").build();

    final BlockingQueue<Response> responseRef = new SynchronousQueue<>();
    client.newCall(request).enqueue(new Callback() {
        @Override/*from  www.  jav  a 2 s  .  c o m*/
        public void onFailure(Request request, IOException e) {
            throw new AssertionError();
        }

        @Override
        public void onResponse(Response response) throws IOException {
            try {
                responseRef.put(response);
            } catch (InterruptedException e) {
                throw new AssertionError();
            }
        }
    });

    Response response = responseRef.take();
    assertEquals(200, response.code());
    assertEquals("abc", response.body().string());

    // Make another request just to confirm that that connection can be reused...
    FiberOkHttpTestUtil.executeInFiberRecorded(client, new Request.Builder().url(server.getUrl("/")).build())
            .assertBody("def");
    assertEquals(0, server.takeRequest().getSequenceNumber()); // New connection.
    assertEquals(1, server.takeRequest().getSequenceNumber()); // Connection reused.

    // ... even before we close the response body!
    response.body().close();
}

From source file:co.paralleluniverse.fibers.okhttp.CallTest.java

License:Open Source License

private RecordedResponse executeSynchronously(Request request) throws IOException {
    Response response = client.newCall(request).execute();
    return new RecordedResponse(request, response, null, response.body().string(), null);
}

From source file:co.paralleluniverse.fibers.okhttp.FiberOkHttpTestUtil.java

License:Open Source License

public static RecordedResponse executeInFiberRecorded(final FiberOkHttpClient client, final Request request)
        throws InterruptedException, IOException, ExecutionException {
    final Response response = FiberOkHttpUtil.executeInFiber(client.newCall(request));
    return new RecordedResponse(request, response, null, response.body().string(), null);
}

From source file:co.paralleluniverse.fibers.okhttp.FiberOkHttpUtils.java

License:Open Source License

public static RecordedResponse executeSynchronouslyRecorded(final FiberOkHttpClient client,
        final Request request) throws InterruptedException, IOException, ExecutionException {
    final Response response = executeSynchronously(client.newCall(request));
    return new RecordedResponse(request, response, null, response.body().string(), null);
}

From source file:co.paralleluniverse.fibers.okhttp.InterceptorTest.java

License:Open Source License

@Test
public void networkInterceptorsObserveNetworkHeaders() throws Exception {
    server.enqueue(new MockResponse().setBody(gzip("abcabcabc")).addHeader("Content-Encoding: gzip"));

    client.networkInterceptors().add(new Interceptor() {
        @Override//from   w  w  w .  j  av  a2 s . co m
        public Response intercept(Chain chain) throws IOException {
            // The network request has everything: User-Agent, Host, Accept-Encoding.
            Request networkRequest = chain.request();
            assertNotNull(networkRequest.header("User-Agent"));
            assertEquals(server.get().getHostName() + ":" + server.get().getPort(),
                    networkRequest.header("Host"));
            assertNotNull(networkRequest.header("Accept-Encoding"));

            // The network response also has everything, including the raw gzipped content.
            Response networkResponse = chain.proceed(networkRequest);
            assertEquals("gzip", networkResponse.header("Content-Encoding"));
            return networkResponse;
        }
    });

    Request request = new Request.Builder().url(server.getUrl("/")).build();

    // No extra headers in the application's request.
    assertNull(request.header("User-Agent"));
    assertNull(request.header("Host"));
    assertNull(request.header("Accept-Encoding"));

    // No extra headers in the application's response.
    Response response = FiberOkHttpUtil.executeInFiber(client, request);
    assertNull(request.header("Content-Encoding"));
    assertEquals("abcabcabc", response.body().string());
}

From source file:co.paralleluniverse.fibers.okhttp.InterceptorTest.java

License:Open Source License

private void rewriteResponseFromServer(List<Interceptor> interceptors) throws Exception {
    server.enqueue(new MockResponse().addHeader("Original-Header: foo").setBody("abc"));

    interceptors.add(new Interceptor() {
        @Override/*  ww  w.j  a va  2 s .  c o  m*/
        public Response intercept(Chain chain) throws IOException {
            Response originalResponse = chain.proceed(chain.request());
            return originalResponse.newBuilder().body(uppercase(originalResponse.body()))
                    .addHeader("OkHttp-Intercepted", "yep").build();
        }
    });

    Request request = new Request.Builder().url(server.getUrl("/")).build();

    Response response = FiberOkHttpUtil.executeInFiber(client, request);
    assertEquals("ABC", response.body().string());
    assertEquals("yep", response.header("OkHttp-Intercepted"));
    assertEquals("foo", response.header("Original-Header"));
}

From source file:co.paralleluniverse.fibers.okhttp.InterceptorTest.java

License:Open Source License

@Test
public void applicationInterceptorsCanMakeMultipleRequestsToServer() throws Exception {
    server.enqueue(new MockResponse().setBody("a"));
    server.enqueue(new MockResponse().setBody("b"));

    client.interceptors().add(new Interceptor() {
        @Override/* ww  w .j a  v  a 2  s .c  o m*/
        public Response intercept(Chain chain) throws IOException {
            chain.proceed(chain.request());
            return chain.proceed(chain.request());
        }
    });

    Request request = new Request.Builder().url(server.getUrl("/")).build();

    Response response = FiberOkHttpUtil.executeInFiber(client, request);
    assertEquals(response.body().string(), "b");
}