Search in sources :

Example 21 with MockWebServer

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

the class JsonAndXmlConverters method main.

public static void main(String... args) throws IOException {
    MockWebServer server = new MockWebServer();
    server.start();
    server.enqueue(new MockResponse().setBody("{\"name\": \"Jason\"}"));
    server.enqueue(new MockResponse().setBody("<user name=\"Eximel\"/>"));
    Retrofit retrofit = new Retrofit.Builder().baseUrl(server.url("/")).addConverterFactory(new QualifiedTypeConverterFactory(GsonConverterFactory.create(), SimpleXmlConverterFactory.create())).build();
    Service service = retrofit.create(Service.class);
    User user1 = service.exampleJson().execute().body();
    System.out.println("User 1: " + user1.name);
    User user2 = service.exampleXml().execute().body();
    System.out.println("User 2: " + user2.name);
    server.shutdown();
}
Also used : MockResponse(okhttp3.mockwebserver.MockResponse) Retrofit(retrofit2.Retrofit) MockWebServer(okhttp3.mockwebserver.MockWebServer)

Example 22 with MockWebServer

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

the class JsonQueryParameters method main.

public static void main(String... args) throws IOException, InterruptedException {
    MockWebServer server = new MockWebServer();
    server.start();
    server.enqueue(new MockResponse());
    Retrofit retrofit = new Retrofit.Builder().baseUrl(server.url("/")).addConverterFactory(new JsonStringConverterFactory(GsonConverterFactory.create())).build();
    Service service = retrofit.create(Service.class);
    Call<ResponseBody> call = service.example(new Filter("123"));
    Response<ResponseBody> response = call.execute();
    // TODO handle user response...
    // Print the request path that the server saw to show the JSON query param:
    RecordedRequest recordedRequest = server.takeRequest();
    System.out.println(recordedRequest.getPath());
    server.shutdown();
}
Also used : RecordedRequest(okhttp3.mockwebserver.RecordedRequest) MockResponse(okhttp3.mockwebserver.MockResponse) Retrofit(retrofit2.Retrofit) MockWebServer(okhttp3.mockwebserver.MockWebServer) ResponseBody(okhttp3.ResponseBody)

Example 23 with MockWebServer

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

the class URLConnectionTest method redirectWithProxySelector.

@Test
public void redirectWithProxySelector() throws Exception {
    final List<URI> proxySelectionRequests = new ArrayList<>();
    urlFactory.setClient(urlFactory.client().newBuilder().proxySelector(new ProxySelector() {

        @Override
        public List<Proxy> select(URI uri) {
            proxySelectionRequests.add(uri);
            MockWebServer proxyServer = (uri.getPort() == server.getPort()) ? server : server2;
            return Arrays.asList(proxyServer.toProxyAddress());
        }

        @Override
        public void connectFailed(URI uri, SocketAddress address, IOException failure) {
            throw new AssertionError();
        }
    }).build());
    server2.enqueue(new MockResponse().setBody("This is the 2nd server!"));
    server.enqueue(new MockResponse().setResponseCode(HttpURLConnection.HTTP_MOVED_TEMP).addHeader("Location: " + server2.url("/b").url().toString()).setBody("This page has moved!"));
    assertContent("This is the 2nd server!", urlFactory.open(server.url("/a").url()));
    assertEquals(Arrays.asList(server.url("/").url().toURI(), server2.url("/").url().toURI()), proxySelectionRequests);
}
Also used : ProxySelector(java.net.ProxySelector) MockResponse(okhttp3.mockwebserver.MockResponse) ArrayList(java.util.ArrayList) MockWebServer(okhttp3.mockwebserver.MockWebServer) List(java.util.List) ArrayList(java.util.ArrayList) IOException(java.io.IOException) SocketAddress(java.net.SocketAddress) URI(java.net.URI) Test(org.junit.Test)

Example 24 with MockWebServer

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

the class URLConnectionTest method writeTimeouts.

/** Confirm that an unacknowledged write times out. */
@Test
public void writeTimeouts() throws IOException {
    MockWebServer server = new MockWebServer();
    // Sockets on some platforms can have large buffers that mean writes do not block when
    // required. These socket factories explicitly set the buffer sizes on sockets created.
    final int SOCKET_BUFFER_SIZE = 4 * 1024;
    server.setServerSocketFactory(new DelegatingServerSocketFactory(ServerSocketFactory.getDefault()) {

        @Override
        protected ServerSocket configureServerSocket(ServerSocket serverSocket) throws IOException {
            serverSocket.setReceiveBufferSize(SOCKET_BUFFER_SIZE);
            return serverSocket;
        }
    });
    urlFactory.setClient(urlFactory.client().newBuilder().socketFactory(new DelegatingSocketFactory(SocketFactory.getDefault()) {

        @Override
        protected Socket configureSocket(Socket socket) throws IOException {
            socket.setReceiveBufferSize(SOCKET_BUFFER_SIZE);
            socket.setSendBufferSize(SOCKET_BUFFER_SIZE);
            return socket;
        }
    }).writeTimeout(500, TimeUnit.MILLISECONDS).build());
    server.start();
    server.enqueue(new MockResponse().throttleBody(1, 1, // Prevent the server from reading!
    TimeUnit.SECONDS));
    connection = urlFactory.open(server.url("/").url());
    connection.setDoOutput(true);
    connection.setChunkedStreamingMode(0);
    OutputStream out = connection.getOutputStream();
    try {
        // 2 MiB.
        byte[] data = new byte[2 * 1024 * 1024];
        out.write(data);
        fail();
    } catch (SocketTimeoutException expected) {
    }
}
Also used : MockResponse(okhttp3.mockwebserver.MockResponse) SocketTimeoutException(java.net.SocketTimeoutException) OutputStream(java.io.OutputStream) MockWebServer(okhttp3.mockwebserver.MockWebServer) ServerSocket(java.net.ServerSocket) IOException(java.io.IOException) SSLSocket(javax.net.ssl.SSLSocket) ServerSocket(java.net.ServerSocket) Socket(java.net.Socket) Test(org.junit.Test)

Example 25 with MockWebServer

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

the class OAuthSessionFactory method start.

public void start() throws Exception {
    if (mockWebServer != null)
        throw new IllegalStateException();
    mockWebServer = new MockWebServer();
    mockWebServer.setDispatcher(this);
    mockWebServer.start(slackApi.port);
}
Also used : MockWebServer(okhttp3.mockwebserver.MockWebServer)

Aggregations

MockWebServer (okhttp3.mockwebserver.MockWebServer)48 MockResponse (okhttp3.mockwebserver.MockResponse)31 Test (org.junit.Test)20 RecordedRequest (okhttp3.mockwebserver.RecordedRequest)16 Before (org.junit.Before)14 IOException (java.io.IOException)9 CookieManager (java.net.CookieManager)7 HttpCookie (java.net.HttpCookie)5 Retrofit (retrofit2.Retrofit)5 ServerSocket (java.net.ServerSocket)4 Socket (java.net.Socket)4 Request (okhttp3.Request)4 OAuthRequest (com.github.scribejava.core.model.OAuthRequest)3 Response (com.github.scribejava.core.model.Response)3 InputStream (java.io.InputStream)3 InterruptedIOException (java.io.InterruptedIOException)3 HttpURLConnection (java.net.HttpURLConnection)3 URI (java.net.URI)3 URL (java.net.URL)3 List (java.util.List)3