Search in sources :

Example 36 with RecordedRequest

use of com.google.mockwebserver.RecordedRequest in project android_frameworks_base by crdroidandroid.

the class AbstractProxyTest method testConnectViaHttpProxyToHttps.

private void testConnectViaHttpProxyToHttps(ProxyConfig proxyConfig) throws Exception {
    TestSSLContext testSSLContext = TestSSLContext.create();
    server.useHttps(testSSLContext.serverContext.getSocketFactory(), true);
    server.enqueue(new MockResponse().setSocketPolicy(SocketPolicy.UPGRADE_TO_SSL_AT_END).clearHeaders());
    server.enqueue(new MockResponse().setResponseCode(200).setBody("this response comes via a secure proxy"));
    server.play();
    HttpClient httpProxyClient = newHttpClient();
    SSLSocketFactory sslSocketFactory = newSslSocketFactory(testSSLContext);
    sslSocketFactory.setHostnameVerifier(new AllowAllHostnameVerifier());
    httpProxyClient.getConnectionManager().getSchemeRegistry().register(new Scheme("https", sslSocketFactory, 443));
    HttpGet request = new HttpGet("https://android.com/foo");
    proxyConfig.configure(server, httpProxyClient, request);
    HttpResponse response = httpProxyClient.execute(request);
    assertEquals("this response comes via a secure proxy", contentToString(response));
    RecordedRequest connect = server.takeRequest();
    assertEquals("Connect line failure on proxy " + proxyConfig, "CONNECT android.com:443 HTTP/1.1", connect.getRequestLine());
    assertContains(connect.getHeaders(), "Host: android.com");
    RecordedRequest get = server.takeRequest();
    assertEquals("GET /foo HTTP/1.1", get.getRequestLine());
    assertContains(get.getHeaders(), "Host: android.com");
}
Also used : RecordedRequest(com.google.mockwebserver.RecordedRequest) MockResponse(com.google.mockwebserver.MockResponse) Scheme(org.apache.http.conn.scheme.Scheme) AllowAllHostnameVerifier(org.apache.http.conn.ssl.AllowAllHostnameVerifier) HttpClient(org.apache.http.client.HttpClient) HttpGet(org.apache.http.client.methods.HttpGet) HttpResponse(org.apache.http.HttpResponse) TestSSLContext(libcore.javax.net.ssl.TestSSLContext) SSLSocketFactory(org.apache.http.conn.ssl.SSLSocketFactory)

Example 37 with RecordedRequest

use of com.google.mockwebserver.RecordedRequest in project j2objc by google.

the class CookiesTest method testCookiesSentIgnoresCase.

// TODO(tball): enable when libcore is updated with latest fixes.
/*
    public void testRedirectsDoNotIncludeTooManyCookies() throws Exception {
        MockWebServer redirectTarget = new MockWebServer();
        redirectTarget.enqueue(new MockResponse().setBody("A"));
        redirectTarget.play();

        MockWebServer redirectSource = new MockWebServer();
        redirectSource.enqueue(new MockResponse()
                .setResponseCode(HttpURLConnection.HTTP_MOVED_TEMP)
                .addHeader("Location: " + redirectTarget.getUrl("/")));
        redirectSource.play();

        CookieManager cookieManager = new CookieManager(null, ACCEPT_ORIGINAL_SERVER);
        HttpCookie cookie = createCookie("c", "cookie", redirectSource.getCookieDomain(), "/");
        String portList = Integer.toString(redirectSource.getPort());
        cookie.setPortlist(portList);
        cookieManager.getCookieStore().add(redirectSource.getUrl("/").toURI(), cookie);
        CookieHandler.setDefault(cookieManager);

        get(redirectSource, "/");
        RecordedRequest request = redirectSource.takeRequest();

        assertContains(request.getHeaders(), "Cookie: $Version=\"1\"; "
                + "c=\"cookie\";$Path=\"/\";$Domain=\"" + redirectSource.getCookieDomain()
                + "\";$Port=\"" + portList + "\"");

        for (String header : redirectTarget.takeRequest().getHeaders()) {
            if (header.startsWith("Cookie")) {
                fail(header);
            }
        }
    }
    */
// TODO(tball): enable when libcore is updated with latest fixes.
/**
     * Test which headers show up where. The cookie manager should be notified
     * of both user-specified and derived headers like {@code Host}. Headers
     * named {@code Cookie} or {@code Cookie2} that are returned by the cookie
     * manager should show up in the request and in {@code
     * getRequestProperties}.
     *
    public void testHeadersSentToCookieHandler() throws IOException, InterruptedException {
        final Map<String, List<String>> cookieHandlerHeaders = new HashMap<String, List<String>>();
        CookieHandler.setDefault(new CookieManager() {
            @Override
            public Map<String, List<String>> get(URI uri,
                    Map<String, List<String>> requestHeaders) throws IOException {
                cookieHandlerHeaders.putAll(requestHeaders);
                Map<String, List<String>> result = new HashMap<String, List<String>>();
                result.put("Cookie", Collections.singletonList("Bar=bar"));
                result.put("Cookie2", Collections.singletonList("Baz=baz"));
                result.put("Quux", Collections.singletonList("quux"));
                return result;
            }
        });
        MockWebServer server = new MockWebServer();
        server.enqueue(new MockResponse());
        server.play();

        HttpURLConnection connection = (HttpURLConnection) server.getUrl("/").openConnection();
        assertEquals(Collections.<String, List<String>>emptyMap(),
                connection.getRequestProperties());

        connection.setRequestProperty("Foo", "foo");
        connection.setDoOutput(true);
        connection.getOutputStream().write(5);
        connection.getOutputStream().close();
        connection.getInputStream().close();

        RecordedRequest request = server.takeRequest();

        assertContainsAll(cookieHandlerHeaders.keySet(), "Foo");
        assertContainsAll(cookieHandlerHeaders.keySet(),
                "Content-Type", "User-Agent", "Connection", "Host");
        assertFalse(cookieHandlerHeaders.containsKey("Cookie"));

        /*
         * The API specifies that calling getRequestProperties() on a connected instance should fail
         * with an IllegalStateException, but the RI violates the spec and returns a valid map.
         * http://www.mail-archive.com/net-dev@openjdk.java.net/msg01768.html
         *
        try {
            assertContainsAll(connection.getRequestProperties().keySet(), "Foo");
            assertContainsAll(connection.getRequestProperties().keySet(),
                    "Content-Type", "Content-Length", "User-Agent", "Connection", "Host");
            assertContainsAll(connection.getRequestProperties().keySet(), "Cookie", "Cookie2");
            assertFalse(connection.getRequestProperties().containsKey("Quux"));
        } catch (IllegalStateException expected) {
        }

        assertContainsAll(request.getHeaders(), "Foo: foo", "Cookie: Bar=bar", "Cookie2: Baz=baz");
        assertFalse(request.getHeaders().contains("Quux: quux"));
    }
    */
public void testCookiesSentIgnoresCase() throws Exception {
    CookieHandler.setDefault(new CookieManager() {

        @Override
        public Map<String, List<String>> get(URI uri, Map<String, List<String>> requestHeaders) throws IOException {
            Map<String, List<String>> result = new HashMap<String, List<String>>();
            result.put("COOKIE", Collections.singletonList("Bar=bar"));
            result.put("cooKIE2", Collections.singletonList("Baz=baz"));
            return result;
        }
    });
    MockWebServer server = new MockWebServer();
    server.enqueue(new MockResponse());
    server.play();
    get(server, "/");
    RecordedRequest request = server.takeRequest();
    assertContainsAll(request.getHeaders(), "COOKIE: Bar=bar", "cooKIE2: Baz=baz");
    assertFalse(request.getHeaders().contains("Quux: quux"));
}
Also used : RecordedRequest(com.google.mockwebserver.RecordedRequest) MockResponse(com.google.mockwebserver.MockResponse) MockWebServer(com.google.mockwebserver.MockWebServer) ArrayList(java.util.ArrayList) List(java.util.List) IOException(java.io.IOException) URI(java.net.URI) HashMap(java.util.HashMap) Map(java.util.Map) CookieManager(java.net.CookieManager)

Example 38 with RecordedRequest

use of com.google.mockwebserver.RecordedRequest in project j2objc by google.

the class CookiesTest method testSendingCookiesFromStore.

public void testSendingCookiesFromStore() throws Exception {
    MockWebServer server = new MockWebServer();
    server.enqueue(new MockResponse());
    server.play();
    CookieManager cookieManager = new CookieManager(null, ACCEPT_ORIGINAL_SERVER);
    HttpCookie cookieA = createCookie("a", "android", server.getCookieDomain(), "/");
    cookieManager.getCookieStore().add(server.getUrl("/").toURI(), cookieA);
    HttpCookie cookieB = createCookie("b", "banana", server.getCookieDomain(), "/");
    cookieManager.getCookieStore().add(server.getUrl("/").toURI(), cookieB);
    CookieHandler.setDefault(cookieManager);
    get(server, "/");
    RecordedRequest request = server.takeRequest();
    List<String> receivedHeaders = request.getHeaders();
    assertContains(receivedHeaders, "Cookie: $Version=\"1\"; " + "a=\"android\";$Path=\"/\";$Domain=\"" + server.getCookieDomain() + "\"; " + "b=\"banana\";$Path=\"/\";$Domain=\"" + server.getCookieDomain() + "\"");
}
Also used : RecordedRequest(com.google.mockwebserver.RecordedRequest) MockResponse(com.google.mockwebserver.MockResponse) MockWebServer(com.google.mockwebserver.MockWebServer) HttpCookie(java.net.HttpCookie) CookieManager(java.net.CookieManager)

Example 39 with RecordedRequest

use of com.google.mockwebserver.RecordedRequest in project j2objc by google.

the class URLConnectionTest method testSetChunkedEncodingAsRequestProperty.

//  JVM failure.
//    public void testResponse305UseProxy() throws Exception {
//        server.play();
//        server.enqueue(new MockResponse()
//                .setResponseCode(HttpURLConnection.HTTP_USE_PROXY)
//                .addHeader("Location: " + server.getUrl("/"))
//                .setBody("This page has moved!"));
//        server.enqueue(new MockResponse().setBody("Proxy Response"));
//
//        HttpURLConnection connection = (HttpURLConnection) server.getUrl("/foo").openConnection();
//        // Fails on the RI, which gets "Proxy Response"
//        assertEquals("This page has moved!",
//                readAscii(connection.getInputStream(), Integer.MAX_VALUE));
//
//        RecordedRequest page1 = server.takeRequest();
//        assertEquals("GET /foo HTTP/1.1", page1.getRequestLine());
//        assertEquals(1, server.getRequestCount());
//    }
// TODO(tball): b/28067294
//    public void testReadTimeouts() throws IOException {
//        /*
//         * This relies on the fact that MockWebServer doesn't close the
//         * connection after a response has been sent. This causes the client to
//         * try to read more bytes than are sent, which results in a timeout.
//         */
//        MockResponse timeout = new MockResponse()
//                .setBody("ABC")
//                .clearHeaders()
//                .addHeader("Content-Length: 4");
//        server.enqueue(timeout);
//        server.enqueue(new MockResponse().setBody("unused")); // to keep the server alive
//        server.play();
//
//        URLConnection urlConnection = server.getUrl("/").openConnection();
//        urlConnection.setReadTimeout(1000);
//        InputStream in = urlConnection.getInputStream();
//        assertEquals('A', in.read());
//        assertEquals('B', in.read());
//        assertEquals('C', in.read());
//        try {
//            in.read(); // if Content-Length was accurate, this would return -1 immediately
//            fail();
//        } catch (SocketTimeoutException expected) {
//        }
//    }
public void testSetChunkedEncodingAsRequestProperty() throws IOException, InterruptedException {
    server.enqueue(new MockResponse());
    server.play();
    HttpURLConnection urlConnection = (HttpURLConnection) server.getUrl("/").openConnection();
    urlConnection.setRequestProperty("Transfer-encoding", "chunked");
    urlConnection.setDoOutput(true);
    urlConnection.getOutputStream().write("ABC".getBytes("UTF-8"));
    assertEquals(200, urlConnection.getResponseCode());
    RecordedRequest request = server.takeRequest();
    assertEquals("ABC", new String(request.getBody(), "UTF-8"));
}
Also used : RecordedRequest(com.google.mockwebserver.RecordedRequest) MockResponse(com.google.mockwebserver.MockResponse) HttpURLConnection(java.net.HttpURLConnection)

Example 40 with RecordedRequest

use of com.google.mockwebserver.RecordedRequest in project j2objc by google.

the class URLConnectionTest method testResponseRedirectedWithPost.

private void testResponseRedirectedWithPost(int redirectCode) throws Exception {
    server.enqueue(new MockResponse().setResponseCode(redirectCode).addHeader("Location: /page2").setBody("This page has moved!"));
    server.enqueue(new MockResponse().setBody("Page 2"));
    server.play();
    HttpURLConnection connection = (HttpURLConnection) server.getUrl("/page1").openConnection();
    connection.setDoOutput(true);
    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(Arrays.toString(requestBody), Arrays.toString(page1.getBody()));
    RecordedRequest page2 = server.takeRequest();
    assertEquals("GET /page2 HTTP/1.1", page2.getRequestLine());
}
Also used : RecordedRequest(com.google.mockwebserver.RecordedRequest) MockResponse(com.google.mockwebserver.MockResponse) HttpURLConnection(java.net.HttpURLConnection) ByteArrayOutputStream(java.io.ByteArrayOutputStream) OutputStream(java.io.OutputStream) GZIPOutputStream(java.util.zip.GZIPOutputStream)

Aggregations

MockResponse (com.google.mockwebserver.MockResponse)80 RecordedRequest (com.google.mockwebserver.RecordedRequest)80 HttpResponse (org.apache.http.HttpResponse)36 HttpClient (org.apache.http.client.HttpClient)36 HttpGet (org.apache.http.client.methods.HttpGet)36 HttpURLConnection (java.net.HttpURLConnection)26 TestSSLContext (libcore.javax.net.ssl.TestSSLContext)22 HttpsURLConnection (javax.net.ssl.HttpsURLConnection)15 MockWebServer (com.google.mockwebserver.MockWebServer)14 Scheme (org.apache.http.conn.scheme.Scheme)12 AllowAllHostnameVerifier (org.apache.http.conn.ssl.AllowAllHostnameVerifier)12 SSLSocketFactory (org.apache.http.conn.ssl.SSLSocketFactory)12 ByteArrayOutputStream (java.io.ByteArrayOutputStream)11 OutputStream (java.io.OutputStream)11 GZIPOutputStream (java.util.zip.GZIPOutputStream)11 URL (java.net.URL)9 URLConnection (java.net.URLConnection)8 CookieManager (java.net.CookieManager)6 HttpHost (org.apache.http.HttpHost)6 DefaultHttpClient (org.apache.http.impl.client.DefaultHttpClient)6