Search in sources :

Example 46 with MockWebServer

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

the class MockWebServer method start.

/**
   * Starts the server and binds to the given socket address.
   *
   * @param inetSocketAddress the socket address to bind the server on
   */
private synchronized void start(InetSocketAddress inetSocketAddress) throws IOException {
    if (started)
        throw new IllegalStateException("start() already called");
    started = true;
    executor = Executors.newCachedThreadPool(Util.threadFactory("MockWebServer", false));
    this.inetSocketAddress = inetSocketAddress;
    serverSocket = serverSocketFactory.createServerSocket();
    // Reuse if the user specified a port
    serverSocket.setReuseAddress(inetSocketAddress.getPort() != 0);
    serverSocket.bind(inetSocketAddress, 50);
    port = serverSocket.getLocalPort();
    executor.execute(new NamedRunnable("MockWebServer %s", port) {

        @Override
        protected void execute() {
            try {
                logger.info(MockWebServer.this + " starting to accept connections");
                acceptConnections();
            } catch (Throwable e) {
                logger.log(Level.WARNING, MockWebServer.this + " failed unexpectedly", e);
            }
            // Release all sockets and all threads, even if any close fails.
            closeQuietly(serverSocket);
            for (Iterator<Socket> s = openClientSockets.iterator(); s.hasNext(); ) {
                closeQuietly(s.next());
                s.remove();
            }
            for (Iterator<Http2Connection> s = openConnections.iterator(); s.hasNext(); ) {
                closeQuietly(s.next());
                s.remove();
            }
            dispatcher.shutdown();
            executor.shutdown();
        }

        private void acceptConnections() throws Exception {
            while (true) {
                Socket socket;
                try {
                    socket = serverSocket.accept();
                } catch (SocketException e) {
                    logger.info(MockWebServer.this + " done accepting connections: " + e.getMessage());
                    return;
                }
                SocketPolicy socketPolicy = dispatcher.peek().getSocketPolicy();
                if (socketPolicy == DISCONNECT_AT_START) {
                    dispatchBookkeepingRequest(0, socket);
                    socket.close();
                } else {
                    openClientSockets.add(socket);
                    serveConnection(socket);
                }
            }
        }
    });
}
Also used : SocketException(java.net.SocketException) Iterator(java.util.Iterator) NamedRunnable(okhttp3.internal.NamedRunnable) InterruptedIOException(java.io.InterruptedIOException) SocketException(java.net.SocketException) IOException(java.io.IOException) CertificateException(java.security.cert.CertificateException) ProtocolException(java.net.ProtocolException) SSLSocket(javax.net.ssl.SSLSocket) ServerSocket(java.net.ServerSocket) RealWebSocket(okhttp3.internal.ws.RealWebSocket) Socket(java.net.Socket)

Example 47 with MockWebServer

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

the class OkApacheClientTest method setUp.

@Before
public void setUp() throws IOException {
    client = new OkApacheClient();
    server = new MockWebServer();
    server.start();
}
Also used : MockWebServer(okhttp3.mockwebserver.MockWebServer) Before(org.junit.Before)

Example 48 with MockWebServer

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

the class CookiesTest method testCookiesSentIgnoresCase.

@Test
public void testCookiesSentIgnoresCase() throws Exception {
    client = client.newBuilder().cookieJar(new JavaNetCookieJar(new CookieManager() {

        @Override
        public Map<String, List<String>> get(URI uri, Map<String, List<String>> requestHeaders) throws IOException {
            Map<String, List<String>> result = new LinkedHashMap<>();
            result.put("COOKIE", Collections.singletonList("Bar=bar"));
            result.put("cooKIE2", Collections.singletonList("Baz=baz"));
            return result;
        }
    })).build();
    MockWebServer server = new MockWebServer();
    server.enqueue(new MockResponse());
    server.start();
    get(server.url("/"));
    RecordedRequest request = server.takeRequest();
    assertEquals("Bar=bar; Baz=baz", request.getHeader("Cookie"));
    assertNull(request.getHeader("Cookie2"));
    assertNull(request.getHeader("Quux"));
}
Also used : RecordedRequest(okhttp3.mockwebserver.RecordedRequest) MockResponse(okhttp3.mockwebserver.MockResponse) MockWebServer(okhttp3.mockwebserver.MockWebServer) List(java.util.List) URI(java.net.URI) LinkedHashMap(java.util.LinkedHashMap) Map(java.util.Map) CookieManager(java.net.CookieManager) LinkedHashMap(java.util.LinkedHashMap) Test(org.junit.Test)

Example 49 with MockWebServer

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

the class CookiesTest method receiveAndSendMultipleCookies.

@Test
public void receiveAndSendMultipleCookies() throws Exception {
    MockWebServer server = new MockWebServer();
    server.enqueue(new MockResponse().addHeader("Set-Cookie", "a=android").addHeader("Set-Cookie", "b=banana"));
    server.enqueue(new MockResponse());
    server.start();
    CookieManager cookieManager = new CookieManager(null, ACCEPT_ORIGINAL_SERVER);
    client = client.newBuilder().cookieJar(new JavaNetCookieJar(cookieManager)).build();
    get(urlWithIpAddress(server, "/"));
    RecordedRequest request1 = server.takeRequest();
    assertNull(request1.getHeader("Cookie"));
    get(urlWithIpAddress(server, "/"));
    RecordedRequest request2 = server.takeRequest();
    assertEquals("a=android; b=banana", request2.getHeader("Cookie"));
}
Also used : RecordedRequest(okhttp3.mockwebserver.RecordedRequest) MockResponse(okhttp3.mockwebserver.MockResponse) MockWebServer(okhttp3.mockwebserver.MockWebServer) CookieManager(java.net.CookieManager) Test(org.junit.Test)

Example 50 with MockWebServer

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

the class CookiesTest method cookieHandlerLikeAndroid.

@Test
public void cookieHandlerLikeAndroid() throws Exception {
    final MockWebServer server = new MockWebServer();
    server.enqueue(new MockResponse());
    server.start();
    final HttpUrl serverUrl = urlWithIpAddress(server, "/");
    CookieHandler androidCookieHandler = new CookieHandler() {

        @Override
        public Map<String, List<String>> get(URI uri, Map<String, List<String>> map) throws IOException {
            return Collections.singletonMap("Cookie", Collections.singletonList("$Version=\"1\"; " + "a=\"android\";$Path=\"/\";$Domain=\"" + serverUrl.host() + "\"; " + "b=\"banana\";$Path=\"/\";$Domain=\"" + serverUrl.host() + "\""));
        }

        @Override
        public void put(URI uri, Map<String, List<String>> map) throws IOException {
        }
    };
    client = client.newBuilder().cookieJar(new JavaNetCookieJar(androidCookieHandler)).build();
    get(serverUrl);
    RecordedRequest request = server.takeRequest();
    assertEquals("a=android; b=banana", request.getHeader("Cookie"));
}
Also used : RecordedRequest(okhttp3.mockwebserver.RecordedRequest) MockResponse(okhttp3.mockwebserver.MockResponse) MockWebServer(okhttp3.mockwebserver.MockWebServer) List(java.util.List) URI(java.net.URI) LinkedHashMap(java.util.LinkedHashMap) Map(java.util.Map) CookieHandler(java.net.CookieHandler) Test(org.junit.Test)

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