Search in sources :

Example 31 with RecordedRequest

use of okhttp3.mockwebserver.RecordedRequest in project okhttp by square.

the class InterceptorTest method rewriteRequestToServer.

private void rewriteRequestToServer(boolean network) throws Exception {
    server.enqueue(new MockResponse());
    addInterceptor(network, new Interceptor() {

        @Override
        public Response intercept(Chain chain) throws IOException {
            Request originalRequest = chain.request();
            return chain.proceed(originalRequest.newBuilder().method("POST", uppercase(originalRequest.body())).addHeader("OkHttp-Intercepted", "yep").build());
        }
    });
    Request request = new Request.Builder().url(server.url("/")).addHeader("Original-Header", "foo").method("PUT", RequestBody.create(MediaType.parse("text/plain"), "abc")).build();
    client.newCall(request).execute();
    RecordedRequest recordedRequest = server.takeRequest();
    assertEquals("ABC", recordedRequest.getBody().readUtf8());
    assertEquals("foo", recordedRequest.getHeader("Original-Header"));
    assertEquals("yep", recordedRequest.getHeader("OkHttp-Intercepted"));
    assertEquals("POST", recordedRequest.getMethod());
}
Also used : MockResponse(okhttp3.mockwebserver.MockResponse) RecordedRequest(okhttp3.mockwebserver.RecordedRequest) MockResponse(okhttp3.mockwebserver.MockResponse) RecordedRequest(okhttp3.mockwebserver.RecordedRequest) IOException(java.io.IOException)

Example 32 with RecordedRequest

use of okhttp3.mockwebserver.RecordedRequest in project okhttp by square.

the class InterceptorTest method multipleInterceptors.

private void multipleInterceptors(boolean network) throws Exception {
    server.enqueue(new MockResponse());
    addInterceptor(network, new Interceptor() {

        @Override
        public Response intercept(Chain chain) throws IOException {
            Request originalRequest = chain.request();
            Response originalResponse = chain.proceed(originalRequest.newBuilder().addHeader("Request-Interceptor", // 1. Added first.
            "Android").build());
            return originalResponse.newBuilder().addHeader("Response-Interceptor", // 4. Added last.
            "Donut").build();
        }
    });
    addInterceptor(network, new Interceptor() {

        @Override
        public Response intercept(Chain chain) throws IOException {
            Request originalRequest = chain.request();
            Response originalResponse = chain.proceed(originalRequest.newBuilder().addHeader("Request-Interceptor", // 2. Added second.
            "Bob").build());
            return originalResponse.newBuilder().addHeader("Response-Interceptor", // 3. Added third.
            "Cupcake").build();
        }
    });
    Request request = new Request.Builder().url(server.url("/")).build();
    Response response = client.newCall(request).execute();
    assertEquals(Arrays.asList("Cupcake", "Donut"), response.headers("Response-Interceptor"));
    RecordedRequest recordedRequest = server.takeRequest();
    assertEquals(Arrays.asList("Android", "Bob"), recordedRequest.getHeaders().values("Request-Interceptor"));
}
Also used : MockResponse(okhttp3.mockwebserver.MockResponse) RecordedRequest(okhttp3.mockwebserver.RecordedRequest) MockResponse(okhttp3.mockwebserver.MockResponse) RecordedRequest(okhttp3.mockwebserver.RecordedRequest) IOException(java.io.IOException)

Example 33 with RecordedRequest

use of okhttp3.mockwebserver.RecordedRequest in project retrofit by square.

the class ProtoConverterFactoryTest method serializeAndDeserialize.

@Test
public void serializeAndDeserialize() throws IOException, InterruptedException {
    ByteString encoded = ByteString.decodeBase64("Cg4oNTE5KSA4NjctNTMwOQ==");
    server.enqueue(new MockResponse().setBody(new Buffer().write(encoded)));
    Call<Phone> call = service.post(Phone.newBuilder().setNumber("(519) 867-5309").build());
    Response<Phone> response = call.execute();
    Phone body = response.body();
    assertThat(body.getNumber()).isEqualTo("(519) 867-5309");
    RecordedRequest request = server.takeRequest();
    assertThat(request.getBody().readByteString()).isEqualTo(encoded);
    assertThat(request.getHeader("Content-Type")).isEqualTo("application/x-protobuf");
}
Also used : Buffer(okio.Buffer) RecordedRequest(okhttp3.mockwebserver.RecordedRequest) MockResponse(okhttp3.mockwebserver.MockResponse) ByteString(okio.ByteString) Phone(retrofit2.converter.protobuf.PhoneProtos.Phone) Test(org.junit.Test)

Example 34 with RecordedRequest

use of okhttp3.mockwebserver.RecordedRequest in project retrofit by square.

the class SimpleXmlConverterFactoryTest method bodyWays.

@Test
public void bodyWays() throws IOException, InterruptedException {
    server.enqueue(new MockResponse().setBody("<my-object><message>hello world</message><count>10</count></my-object>"));
    Call<MyObject> call = service.post(new MyObject("hello world", 10));
    Response<MyObject> response = call.execute();
    MyObject body = response.body();
    assertThat(body.getMessage()).isEqualTo("hello world");
    assertThat(body.getCount()).isEqualTo(10);
    RecordedRequest request = server.takeRequest();
    assertThat(request.getBody().readUtf8()).isIn("<my-object><message>hello world</message><count>10</count></my-object>", "<my-object><count>10</count><message>hello world</message></my-object>");
    assertThat(request.getHeader("Content-Type")).isEqualTo("application/xml; charset=UTF-8");
}
Also used : RecordedRequest(okhttp3.mockwebserver.RecordedRequest) MockResponse(okhttp3.mockwebserver.MockResponse) Test(org.junit.Test)

Example 35 with RecordedRequest

use of okhttp3.mockwebserver.RecordedRequest in project okhttp by square.

the class MockWebServer method handleWebSocketUpgrade.

private void handleWebSocketUpgrade(Socket socket, BufferedSource source, BufferedSink sink, RecordedRequest request, MockResponse response) throws IOException {
    String key = request.getHeader("Sec-WebSocket-Key");
    response.setHeader("Sec-WebSocket-Accept", WebSocketProtocol.acceptHeader(key));
    writeHttpResponse(socket, sink, response);
    // Adapt the request and response into our Request and Response domain model.
    String scheme = request.getTlsVersion() != null ? "https" : "http";
    // Has host and port.
    String authority = request.getHeader("Host");
    final Request fancyRequest = new Request.Builder().url(scheme + "://" + authority + "/").headers(request.getHeaders()).build();
    final Response fancyResponse = new Response.Builder().code(Integer.parseInt(response.getStatus().split(" ")[1])).message(response.getStatus().split(" ", 3)[2]).headers(response.getHeaders()).request(fancyRequest).protocol(Protocol.HTTP_1_1).build();
    final CountDownLatch connectionClose = new CountDownLatch(1);
    RealWebSocket.Streams streams = new RealWebSocket.Streams(false, source, sink) {

        @Override
        public void close() {
            connectionClose.countDown();
        }
    };
    RealWebSocket webSocket = new RealWebSocket(fancyRequest, response.getWebSocketListener(), new SecureRandom());
    response.getWebSocketListener().onOpen(webSocket, fancyResponse);
    String name = "MockWebServer WebSocket " + request.getPath();
    webSocket.initReaderAndWriter(name, 0, streams);
    try {
        webSocket.loopReader();
        // Even if messages are no longer being read we need to wait for the connection close signal.
        try {
            connectionClose.await();
        } catch (InterruptedException ignored) {
        }
    } catch (IOException e) {
        webSocket.failWebSocket(e, null);
    } finally {
        closeQuietly(sink);
        closeQuietly(source);
    }
}
Also used : Response(okhttp3.Response) RealWebSocket(okhttp3.internal.ws.RealWebSocket) Request(okhttp3.Request) SecureRandom(java.security.SecureRandom) ByteString(okio.ByteString) InterruptedIOException(java.io.InterruptedIOException) IOException(java.io.IOException) CountDownLatch(java.util.concurrent.CountDownLatch)

Aggregations

RecordedRequest (okhttp3.mockwebserver.RecordedRequest)206 MockResponse (okhttp3.mockwebserver.MockResponse)188 Test (org.junit.Test)168 HttpURLConnection (java.net.HttpURLConnection)18 MockWebServer (okhttp3.mockwebserver.MockWebServer)14 IOException (java.io.IOException)13 URL (java.net.URL)13 OutputStream (java.io.OutputStream)12 Response (okhttp3.Response)12 OkHttpURLConnection (okhttp3.internal.huc.OkHttpURLConnection)12 AbstractTest (org.openstack4j.api.AbstractTest)12 Test (org.testng.annotations.Test)12 Call (okhttp3.Call)11 Buffer (okio.Buffer)11 Request (okhttp3.Request)8 RecordingOkAuthenticator (okhttp3.internal.RecordingOkAuthenticator)7 Dispatcher (okhttp3.mockwebserver.Dispatcher)6 ByteString (okio.ByteString)6 CookieManager (java.net.CookieManager)5 URLConnection (java.net.URLConnection)5