Search in sources :

Example 26 with RecordedRequest

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

the class URLConnectionTest method testRedirected.

private void testRedirected(TransferKind transferKind, boolean reuse) throws Exception {
    MockResponse response = new MockResponse().setResponseCode(HttpURLConnection.HTTP_MOVED_TEMP).addHeader("Location: /foo");
    transferKind.setBody(response, "This page has moved!", 10);
    server.enqueue(response);
    server.enqueue(new MockResponse().setBody("This is the new location!"));
    server.play();
    URLConnection connection = server.getUrl("/").openConnection();
    assertEquals("This is the new location!", readAscii(connection.getInputStream(), Integer.MAX_VALUE));
    RecordedRequest first = server.takeRequest();
    assertEquals("GET / HTTP/1.1", first.getRequestLine());
    RecordedRequest retry = server.takeRequest();
    assertEquals("GET /foo HTTP/1.1", retry.getRequestLine());
    if (reuse) {
        assertEquals("Expected connection reuse", 1, retry.getSequenceNumber());
    }
}
Also used : RecordedRequest(com.google.mockwebserver.RecordedRequest) MockResponse(com.google.mockwebserver.MockResponse) HttpURLConnection(java.net.HttpURLConnection) URLConnection(java.net.URLConnection)

Example 27 with RecordedRequest

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

the class URLConnectionTest method testConnectViaProxy.

//  JVM failure.
//    public void testGetResponseCodeNoResponseBody() throws Exception {
//        server.enqueue(new MockResponse()
//                .addHeader("abc: def"));
//        server.play();
//
//        URL url = server.getUrl("/");
//        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
//        conn.setDoInput(false);
//        assertEquals("def", conn.getHeaderField("abc"));
//        assertEquals(200, conn.getResponseCode());
//        try {
//            conn.getInputStream();
//            fail();
//        } catch (ProtocolException expected) {
//        }
//    }
// TODO(tball): b/28067294
//    public void testConnectViaProxyUsingProxyArg() throws Exception {
//        testConnectViaProxy(ProxyConfig.CREATE_ARG);
//    }
// TODO(tball): b/28067294
//    public void testConnectViaProxyUsingProxySystemProperty() throws Exception {
//        testConnectViaProxy(ProxyConfig.PROXY_SYSTEM_PROPERTY);
//    }
private void testConnectViaProxy(ProxyConfig proxyConfig) throws Exception {
    MockResponse mockResponse = new MockResponse().setBody("this response comes via a proxy");
    server.enqueue(mockResponse);
    server.play();
    URL url = new URL("http://android.com/foo");
    HttpURLConnection connection = proxyConfig.connect(server, url);
    assertContent("this response comes via a proxy", connection);
    RecordedRequest request = server.takeRequest();
    assertEquals("GET http://android.com/foo HTTP/1.1", request.getRequestLine());
    assertContains(request.getHeaders(), "Host: android.com");
}
Also used : RecordedRequest(com.google.mockwebserver.RecordedRequest) MockResponse(com.google.mockwebserver.MockResponse) HttpURLConnection(java.net.HttpURLConnection) URL(java.net.URL)

Example 28 with RecordedRequest

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

the class URLConnectionTest method testClientConfiguredCustomContentEncoding.

// JVM failure.
//    /**
//     * This test checks whether connections are gzipped by default. This
//     * behavior in not required by the API, so a failure of this test does not
//     * imply a bug in the implementation.
//     */
//    public void testGzipEncodingEnabledByDefault() throws IOException, InterruptedException {
//        server.enqueue(new MockResponse()
//                .setBody(gzip("ABCABCABC".getBytes("UTF-8")))
//                .addHeader("Content-Encoding: gzip"));
//        server.play();
//
//        URLConnection connection = server.getUrl("/").openConnection();
//        assertEquals("ABCABCABC", readAscii(connection.getInputStream(), Integer.MAX_VALUE));
//        assertNull(connection.getContentEncoding());
//        assertEquals(-1, connection.getContentLength());
//
//        RecordedRequest request = server.takeRequest();
//        assertContains(request.getHeaders(), "Accept-Encoding: gzip");
//    }
// TODO(tball): b/28067294
//    public void testClientConfiguredGzipContentEncoding() throws Exception {
//        byte[] bodyBytes = gzip("ABCDEFGHIJKLMNOPQRSTUVWXYZ".getBytes("UTF-8"));
//        server.enqueue(new MockResponse()
//                .setBody(bodyBytes)
//                .addHeader("Content-Encoding: gzip")
//                .addHeader("Content-Length: " + bodyBytes.length));
//        server.play();
//
//        URLConnection connection = server.getUrl("/").openConnection();
//        connection.addRequestProperty("Accept-Encoding", "gzip");
//        InputStream gunzippedIn = new GZIPInputStream(connection.getInputStream());
//        assertEquals("ABCDEFGHIJKLMNOPQRSTUVWXYZ", readAscii(gunzippedIn, Integer.MAX_VALUE));
//        assertEquals(bodyBytes.length, connection.getContentLength());
//
//        RecordedRequest request = server.takeRequest();
//        assertContains(request.getHeaders(), "Accept-Encoding: gzip");
//        assertEquals("gzip", connection.getContentEncoding());
//    }
// TODO(tball): b/28067294
//    public void testGzipAndConnectionReuseWithFixedLength() throws Exception {
//        testClientConfiguredGzipContentEncodingAndConnectionReuse(TransferKind.FIXED_LENGTH);
//    }
// TODO(tball): b/28067294
//    public void testGzipAndConnectionReuseWithChunkedEncoding() throws Exception {
//        testClientConfiguredGzipContentEncodingAndConnectionReuse(TransferKind.CHUNKED);
//    }
public void testClientConfiguredCustomContentEncoding() throws Exception {
    server.enqueue(new MockResponse().setBody("ABCDE").addHeader("Content-Encoding: custom"));
    server.play();
    URLConnection connection = server.getUrl("/").openConnection();
    connection.addRequestProperty("Accept-Encoding", "custom");
    assertEquals("ABCDE", readAscii(connection.getInputStream(), Integer.MAX_VALUE));
    RecordedRequest request = server.takeRequest();
    assertContains(request.getHeaders(), "Accept-Encoding: custom");
}
Also used : RecordedRequest(com.google.mockwebserver.RecordedRequest) MockResponse(com.google.mockwebserver.MockResponse) HttpURLConnection(java.net.HttpURLConnection) URLConnection(java.net.URLConnection)

Example 29 with RecordedRequest

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

the class URLConnectionTest method testAuthenticateWithStreamingPost.

//  JVM failure.
//    /**
//     * Test that HEAD requests don't have a body regardless of the response
//     * headers. http://code.google.com/p/android/issues/detail?id=24672
//     */
//    public void testHeadAndContentLength() throws Exception {
//        server.enqueue(new MockResponse()
//                .clearHeaders()
//                .addHeader("Content-Length: 100"));
//        server.enqueue(new MockResponse().setBody("A"));
//        server.play();
//
//        HttpURLConnection connection1 = (HttpURLConnection) server.getUrl("/").openConnection();
//        connection1.setRequestMethod("HEAD");
//        assertEquals("100", connection1.getHeaderField("Content-Length"));
//        assertContent("", connection1);
//
//        HttpURLConnection connection2 = (HttpURLConnection) server.getUrl("/").openConnection();
//        assertEquals("A", readAscii(connection2.getInputStream(), Integer.MAX_VALUE));
//
//        assertEquals(0, server.takeRequest().getSequenceNumber());
//        assertEquals(1, server.takeRequest().getSequenceNumber());
//    }
// TODO(tball): b/28067294
//    /**
//     * Test that request body chunking works. This test has been relaxed from treating
//     * the {@link java.net.HttpURLConnection#setChunkedStreamingMode(int)}
//     * chunk length as being fixed because OkHttp no longer guarantees
//     * the fixed chunk size. Instead, we check that chunking takes place
//     * and we force the chunk size with flushes.
//     */
//    public void testSetChunkedStreamingMode() throws IOException, InterruptedException {
//        server.enqueue(new MockResponse());
//        server.play();
//
//        HttpURLConnection urlConnection = (HttpURLConnection) server.getUrl("/").openConnection();
//        // Later releases of Android ignore the value for chunkLength if it is > 0 and default to
//        // a fixed chunkLength. During the change-over period while the chunkLength indicates the
//        // chunk buffer size (inc. header) the chunkLength has to be >= 8. This enables the flush()
//        // to dictate the size of the chunks.
//        urlConnection.setChunkedStreamingMode(50 /* chunkLength */);
//        urlConnection.setDoOutput(true);
//        OutputStream outputStream = urlConnection.getOutputStream();
//        String outputString = "ABCDEFGH";
//        byte[] outputBytes = outputString.getBytes("US-ASCII");
//        int targetChunkSize = 3;
//        for (int i = 0; i < outputBytes.length; i += targetChunkSize) {
//            int count = i + targetChunkSize < outputBytes.length ? 3 : outputBytes.length - i;
//            outputStream.write(outputBytes, i, count);
//            outputStream.flush();
//        }
//        assertEquals(200, urlConnection.getResponseCode());
//
//        RecordedRequest request = server.takeRequest();
//        assertEquals(outputString, new String(request.getBody(), "US-ASCII"));
//        assertEquals(Arrays.asList(3, 3, 2), request.getChunkSizes());
//    }
// TODO(tball): b/28067294
//    public void testAuthenticateWithFixedLengthStreaming() throws Exception {
//        testAuthenticateWithStreamingPost(StreamingMode.FIXED_LENGTH);
//    }
// TODO(tball): b/28067294
//    public void testAuthenticateWithChunkedStreaming() throws Exception {
//        testAuthenticateWithStreamingPost(StreamingMode.CHUNKED);
//    }
private void testAuthenticateWithStreamingPost(StreamingMode streamingMode) throws Exception {
    MockResponse pleaseAuthenticate = new MockResponse().setResponseCode(401).addHeader("WWW-Authenticate: Basic realm=\"protected area\"").setBody("Please authenticate.");
    server.enqueue(pleaseAuthenticate);
    server.play();
    Authenticator.setDefault(new SimpleAuthenticator());
    HttpURLConnection connection = (HttpURLConnection) server.getUrl("/").openConnection();
    connection.setDoOutput(true);
    byte[] requestBody = { 'A', 'B', 'C', 'D' };
    if (streamingMode == StreamingMode.FIXED_LENGTH) {
        connection.setFixedLengthStreamingMode(requestBody.length);
    } else if (streamingMode == StreamingMode.CHUNKED) {
        connection.setChunkedStreamingMode(0);
    }
    OutputStream outputStream = connection.getOutputStream();
    outputStream.write(requestBody);
    outputStream.close();
    try {
        connection.getInputStream();
        fail();
    } catch (HttpRetryException expected) {
    }
    // no authorization header for the request...
    RecordedRequest request = server.takeRequest();
    assertContainsNoneMatching(request.getHeaders(), "Authorization: Basic .*");
    assertEquals(Arrays.toString(requestBody), Arrays.toString(request.getBody()));
}
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) HttpRetryException(java.net.HttpRetryException)

Example 30 with RecordedRequest

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

the class URLConnectionTest method testUrlContainsQueryButNoPath.

// http://b/4361656
public void testUrlContainsQueryButNoPath() throws Exception {
    server.enqueue(new MockResponse().setBody("A"));
    server.play();
    URL url = new URL("http", server.getHostName(), server.getPort(), "?query");
    assertEquals("A", readAscii(url.openConnection().getInputStream(), Integer.MAX_VALUE));
    RecordedRequest request = server.takeRequest();
    assertEquals("GET /?query HTTP/1.1", request.getRequestLine());
}
Also used : RecordedRequest(com.google.mockwebserver.RecordedRequest) MockResponse(com.google.mockwebserver.MockResponse) URL(java.net.URL)

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