URLConnectionTest.java revision df29c7dc69965462cd19de8910b04c8cb463e57f
1e40c9e3935a5024c0f3ebfb3f1441fcd5c48ed86Elliott Hughes/*
2e40c9e3935a5024c0f3ebfb3f1441fcd5c48ed86Elliott Hughes * Copyright (C) 2009 The Android Open Source Project
3f33eae7e84eb6d3b0f4e86b59605bb3de73009f3Elliott Hughes *
4e40c9e3935a5024c0f3ebfb3f1441fcd5c48ed86Elliott Hughes * Licensed under the Apache License, Version 2.0 (the "License");
5e40c9e3935a5024c0f3ebfb3f1441fcd5c48ed86Elliott Hughes * you may not use this file except in compliance with the License.
6e40c9e3935a5024c0f3ebfb3f1441fcd5c48ed86Elliott Hughes * You may obtain a copy of the License at
7f33eae7e84eb6d3b0f4e86b59605bb3de73009f3Elliott Hughes *
8e40c9e3935a5024c0f3ebfb3f1441fcd5c48ed86Elliott Hughes *      http://www.apache.org/licenses/LICENSE-2.0
9f33eae7e84eb6d3b0f4e86b59605bb3de73009f3Elliott Hughes *
10e40c9e3935a5024c0f3ebfb3f1441fcd5c48ed86Elliott Hughes * Unless required by applicable law or agreed to in writing, software
11e40c9e3935a5024c0f3ebfb3f1441fcd5c48ed86Elliott Hughes * distributed under the License is distributed on an "AS IS" BASIS,
12e40c9e3935a5024c0f3ebfb3f1441fcd5c48ed86Elliott Hughes * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13e40c9e3935a5024c0f3ebfb3f1441fcd5c48ed86Elliott Hughes * See the License for the specific language governing permissions and
14e40c9e3935a5024c0f3ebfb3f1441fcd5c48ed86Elliott Hughes * limitations under the License.
15e40c9e3935a5024c0f3ebfb3f1441fcd5c48ed86Elliott Hughes */
16e40c9e3935a5024c0f3ebfb3f1441fcd5c48ed86Elliott Hughes
174557728efb66c455a52b7669a8eefef7a9e54854Jesse Wilsonpackage libcore.java.net;
18e40c9e3935a5024c0f3ebfb3f1441fcd5c48ed86Elliott Hughes
1909336c914b4fc813e493acc82469b9ad89fd8694Jesse Wilsonimport com.google.mockwebserver.MockResponse;
2009336c914b4fc813e493acc82469b9ad89fd8694Jesse Wilsonimport com.google.mockwebserver.MockWebServer;
2109336c914b4fc813e493acc82469b9ad89fd8694Jesse Wilsonimport com.google.mockwebserver.RecordedRequest;
2209336c914b4fc813e493acc82469b9ad89fd8694Jesse Wilsonimport com.google.mockwebserver.SocketPolicy;
2309336c914b4fc813e493acc82469b9ad89fd8694Jesse Wilsonimport static com.google.mockwebserver.SocketPolicy.DISCONNECT_AT_END;
2409336c914b4fc813e493acc82469b9ad89fd8694Jesse Wilsonimport static com.google.mockwebserver.SocketPolicy.DISCONNECT_AT_START;
2509336c914b4fc813e493acc82469b9ad89fd8694Jesse Wilsonimport static com.google.mockwebserver.SocketPolicy.SHUTDOWN_INPUT_AT_END;
2609336c914b4fc813e493acc82469b9ad89fd8694Jesse Wilsonimport static com.google.mockwebserver.SocketPolicy.SHUTDOWN_OUTPUT_AT_END;
27c8977f474b30c5f3807398859a6b16687af6fc7bJesse Wilsonimport java.io.ByteArrayOutputStream;
286247987eb505a482a67f5f19678260d9e7240a5fElliott Hughesimport java.io.IOException;
2951e468abf2628ce964d3657042f3ac8f2c947504Jesse Wilsonimport java.io.InputStream;
3002f0cb2eb84a112fcf644d7d1fd0b5f94ea2f03bElliott Hughesimport java.io.OutputStream;
314557728efb66c455a52b7669a8eefef7a9e54854Jesse Wilsonimport java.net.Authenticator;
324557728efb66c455a52b7669a8eefef7a9e54854Jesse Wilsonimport java.net.CacheRequest;
334557728efb66c455a52b7669a8eefef7a9e54854Jesse Wilsonimport java.net.CacheResponse;
34b7f4d6c3968c372767b2510f38a3d506067aced6Jesse Wilsonimport java.net.ConnectException;
354557728efb66c455a52b7669a8eefef7a9e54854Jesse Wilsonimport java.net.HttpRetryException;
364557728efb66c455a52b7669a8eefef7a9e54854Jesse Wilsonimport java.net.HttpURLConnection;
372d9fa917aae6a6da38e9d1eda05841ffdf8855bbJesse Wilsonimport java.net.InetAddress;
384557728efb66c455a52b7669a8eefef7a9e54854Jesse Wilsonimport java.net.PasswordAuthentication;
39f14bee4dbf9f724a177a85a7b73f7b0bc6df1ec0Jesse Wilsonimport java.net.ProtocolException;
40f02c695ed03e708623d9365dec26d533356ef2d0Brian Carlstromimport java.net.Proxy;
414557728efb66c455a52b7669a8eefef7a9e54854Jesse Wilsonimport java.net.ResponseCache;
424557728efb66c455a52b7669a8eefef7a9e54854Jesse Wilsonimport java.net.SocketTimeoutException;
434557728efb66c455a52b7669a8eefef7a9e54854Jesse Wilsonimport java.net.URI;
444557728efb66c455a52b7669a8eefef7a9e54854Jesse Wilsonimport java.net.URL;
454557728efb66c455a52b7669a8eefef7a9e54854Jesse Wilsonimport java.net.URLConnection;
46d0d626655f1d452070d3116678037e8759f807f4Jesse Wilsonimport java.net.UnknownHostException;
47c0372d90016d241ac979faa6fa1731f30b6f2a03Jesse Wilsonimport java.security.cert.CertificateException;
48c0372d90016d241ac979faa6fa1731f30b6f2a03Jesse Wilsonimport java.security.cert.X509Certificate;
4951e468abf2628ce964d3657042f3ac8f2c947504Jesse Wilsonimport java.util.ArrayList;
5002f0cb2eb84a112fcf644d7d1fd0b5f94ea2f03bElliott Hughesimport java.util.Arrays;
5151e468abf2628ce964d3657042f3ac8f2c947504Jesse Wilsonimport java.util.Collections;
5283a47d4d0c536e06fc53eda9d5a1a5d93f9accc6Jesse Wilsonimport java.util.HashSet;
5351e468abf2628ce964d3657042f3ac8f2c947504Jesse Wilsonimport java.util.Iterator;
546247987eb505a482a67f5f19678260d9e7240a5fElliott Hughesimport java.util.List;
5583a47d4d0c536e06fc53eda9d5a1a5d93f9accc6Jesse Wilsonimport java.util.Map;
5651e468abf2628ce964d3657042f3ac8f2c947504Jesse Wilsonimport java.util.Set;
57afd9b157f467b7c4f2f0b5592dca72f18d844602Jesse Wilsonimport java.util.concurrent.atomic.AtomicBoolean;
5883a47d4d0c536e06fc53eda9d5a1a5d93f9accc6Jesse Wilsonimport java.util.concurrent.atomic.AtomicReference;
59deb236fb06f2a14861e7d40dea959f181cd5cf28Jesse Wilsonimport java.util.zip.GZIPInputStream;
60deb236fb06f2a14861e7d40dea959f181cd5cf28Jesse Wilsonimport java.util.zip.GZIPOutputStream;
6160476787f0e0f052366d8031c74e507ffd3d16a3Jesse Wilsonimport javax.net.ssl.HostnameVerifier;
6260476787f0e0f052366d8031c74e507ffd3d16a3Jesse Wilsonimport javax.net.ssl.HttpsURLConnection;
63c0372d90016d241ac979faa6fa1731f30b6f2a03Jesse Wilsonimport javax.net.ssl.SSLContext;
64096aac7b8a607d3da237900f52cab1c5066bf992Jesse Wilsonimport javax.net.ssl.SSLException;
652915378e253f08e47fe5a9bfd026cd1ca7c6c351Brian Carlstromimport javax.net.ssl.SSLHandshakeException;
6660476787f0e0f052366d8031c74e507ffd3d16a3Jesse Wilsonimport javax.net.ssl.SSLSession;
67c0372d90016d241ac979faa6fa1731f30b6f2a03Jesse Wilsonimport javax.net.ssl.SSLSocketFactory;
68c0372d90016d241ac979faa6fa1731f30b6f2a03Jesse Wilsonimport javax.net.ssl.TrustManager;
69c0372d90016d241ac979faa6fa1731f30b6f2a03Jesse Wilsonimport javax.net.ssl.X509TrustManager;
70ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilsonimport junit.framework.TestCase;
712915378e253f08e47fe5a9bfd026cd1ca7c6c351Brian Carlstromimport libcore.java.security.TestKeyStore;
7250ae32218918eae80298bd1ab8e4f588bbbabdb2Jesse Wilsonimport libcore.javax.net.ssl.TestSSLContext;
735fc5dde4c719c1dfdac46b67d5d2e4884d07721eElliott Hughesimport tests.net.StuckServer;
74e40c9e3935a5024c0f3ebfb3f1441fcd5c48ed86Elliott Hughes
75ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilsonpublic final class URLConnectionTest extends TestCase {
7651e468abf2628ce964d3657042f3ac8f2c947504Jesse Wilson    private MockWebServer server = new MockWebServer();
770c2fd828abec671333b8b88281825fd27a783723Jesse Wilson    private String hostName;
7800feece22909b7dc79fc96d666d157390b93858eJesse Wilson
7900feece22909b7dc79fc96d666d157390b93858eJesse Wilson    @Override protected void setUp() throws Exception {
8000feece22909b7dc79fc96d666d157390b93858eJesse Wilson        super.setUp();
810c2fd828abec671333b8b88281825fd27a783723Jesse Wilson        hostName = server.getHostName();
8200feece22909b7dc79fc96d666d157390b93858eJesse Wilson    }
8351e468abf2628ce964d3657042f3ac8f2c947504Jesse Wilson
8451e468abf2628ce964d3657042f3ac8f2c947504Jesse Wilson    @Override protected void tearDown() throws Exception {
8551e468abf2628ce964d3657042f3ac8f2c947504Jesse Wilson        ResponseCache.setDefault(null);
86ffd579b668428272b78f5c6c64f9c89766f37c1aJesse Wilson        Authenticator.setDefault(null);
87984fcff696380abd6ea14e80030f9fd2d09dbad0Jesse Wilson        System.clearProperty("proxyHost");
88984fcff696380abd6ea14e80030f9fd2d09dbad0Jesse Wilson        System.clearProperty("proxyPort");
89984fcff696380abd6ea14e80030f9fd2d09dbad0Jesse Wilson        System.clearProperty("http.proxyHost");
90984fcff696380abd6ea14e80030f9fd2d09dbad0Jesse Wilson        System.clearProperty("http.proxyPort");
91984fcff696380abd6ea14e80030f9fd2d09dbad0Jesse Wilson        System.clearProperty("https.proxyHost");
92984fcff696380abd6ea14e80030f9fd2d09dbad0Jesse Wilson        System.clearProperty("https.proxyPort");
9351e468abf2628ce964d3657042f3ac8f2c947504Jesse Wilson        server.shutdown();
9400feece22909b7dc79fc96d666d157390b93858eJesse Wilson        super.tearDown();
9551e468abf2628ce964d3657042f3ac8f2c947504Jesse Wilson    }
9651e468abf2628ce964d3657042f3ac8f2c947504Jesse Wilson
9783a47d4d0c536e06fc53eda9d5a1a5d93f9accc6Jesse Wilson    public void testRequestHeaders() throws IOException, InterruptedException {
9883a47d4d0c536e06fc53eda9d5a1a5d93f9accc6Jesse Wilson        server.enqueue(new MockResponse());
9983a47d4d0c536e06fc53eda9d5a1a5d93f9accc6Jesse Wilson        server.play();
10083a47d4d0c536e06fc53eda9d5a1a5d93f9accc6Jesse Wilson
10183a47d4d0c536e06fc53eda9d5a1a5d93f9accc6Jesse Wilson        HttpURLConnection urlConnection = (HttpURLConnection) server.getUrl("/").openConnection();
10283a47d4d0c536e06fc53eda9d5a1a5d93f9accc6Jesse Wilson        urlConnection.addRequestProperty("D", "e");
10383a47d4d0c536e06fc53eda9d5a1a5d93f9accc6Jesse Wilson        urlConnection.addRequestProperty("D", "f");
104ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson        assertEquals("f", urlConnection.getRequestProperty("D"));
105ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson        assertEquals("f", urlConnection.getRequestProperty("d"));
10683a47d4d0c536e06fc53eda9d5a1a5d93f9accc6Jesse Wilson        Map<String, List<String>> requestHeaders = urlConnection.getRequestProperties();
10783a47d4d0c536e06fc53eda9d5a1a5d93f9accc6Jesse Wilson        assertEquals(newSet("e", "f"), new HashSet<String>(requestHeaders.get("D")));
108ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson        assertEquals(newSet("e", "f"), new HashSet<String>(requestHeaders.get("d")));
10983a47d4d0c536e06fc53eda9d5a1a5d93f9accc6Jesse Wilson        try {
11083a47d4d0c536e06fc53eda9d5a1a5d93f9accc6Jesse Wilson            requestHeaders.put("G", Arrays.asList("h"));
11183a47d4d0c536e06fc53eda9d5a1a5d93f9accc6Jesse Wilson            fail("Modified an unmodifiable view.");
11283a47d4d0c536e06fc53eda9d5a1a5d93f9accc6Jesse Wilson        } catch (UnsupportedOperationException expected) {
11383a47d4d0c536e06fc53eda9d5a1a5d93f9accc6Jesse Wilson        }
11483a47d4d0c536e06fc53eda9d5a1a5d93f9accc6Jesse Wilson        try {
11583a47d4d0c536e06fc53eda9d5a1a5d93f9accc6Jesse Wilson            requestHeaders.get("D").add("i");
11683a47d4d0c536e06fc53eda9d5a1a5d93f9accc6Jesse Wilson            fail("Modified an unmodifiable view.");
11783a47d4d0c536e06fc53eda9d5a1a5d93f9accc6Jesse Wilson        } catch (UnsupportedOperationException expected) {
11883a47d4d0c536e06fc53eda9d5a1a5d93f9accc6Jesse Wilson        }
11983a47d4d0c536e06fc53eda9d5a1a5d93f9accc6Jesse Wilson        try {
12083a47d4d0c536e06fc53eda9d5a1a5d93f9accc6Jesse Wilson            urlConnection.setRequestProperty(null, "j");
12183a47d4d0c536e06fc53eda9d5a1a5d93f9accc6Jesse Wilson            fail();
12283a47d4d0c536e06fc53eda9d5a1a5d93f9accc6Jesse Wilson        } catch (NullPointerException expected) {
12383a47d4d0c536e06fc53eda9d5a1a5d93f9accc6Jesse Wilson        }
12483a47d4d0c536e06fc53eda9d5a1a5d93f9accc6Jesse Wilson        try {
12583a47d4d0c536e06fc53eda9d5a1a5d93f9accc6Jesse Wilson            urlConnection.addRequestProperty(null, "k");
12683a47d4d0c536e06fc53eda9d5a1a5d93f9accc6Jesse Wilson            fail();
12783a47d4d0c536e06fc53eda9d5a1a5d93f9accc6Jesse Wilson        } catch (NullPointerException expected) {
12883a47d4d0c536e06fc53eda9d5a1a5d93f9accc6Jesse Wilson        }
12983a47d4d0c536e06fc53eda9d5a1a5d93f9accc6Jesse Wilson        urlConnection.setRequestProperty("NullValue", null); // should fail silently!
130ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson        assertNull(urlConnection.getRequestProperty("NullValue"));
13183a47d4d0c536e06fc53eda9d5a1a5d93f9accc6Jesse Wilson        urlConnection.addRequestProperty("AnotherNullValue", null);  // should fail silently!
132ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson        assertNull(urlConnection.getRequestProperty("AnotherNullValue"));
13383a47d4d0c536e06fc53eda9d5a1a5d93f9accc6Jesse Wilson
13483a47d4d0c536e06fc53eda9d5a1a5d93f9accc6Jesse Wilson        urlConnection.getResponseCode();
13583a47d4d0c536e06fc53eda9d5a1a5d93f9accc6Jesse Wilson        RecordedRequest request = server.takeRequest();
13683a47d4d0c536e06fc53eda9d5a1a5d93f9accc6Jesse Wilson        assertContains(request.getHeaders(), "D: e");
13783a47d4d0c536e06fc53eda9d5a1a5d93f9accc6Jesse Wilson        assertContains(request.getHeaders(), "D: f");
13883a47d4d0c536e06fc53eda9d5a1a5d93f9accc6Jesse Wilson        assertContainsNoneMatching(request.getHeaders(), "NullValue.*");
13983a47d4d0c536e06fc53eda9d5a1a5d93f9accc6Jesse Wilson        assertContainsNoneMatching(request.getHeaders(), "AnotherNullValue.*");
14083a47d4d0c536e06fc53eda9d5a1a5d93f9accc6Jesse Wilson        assertContainsNoneMatching(request.getHeaders(), "G:.*");
14183a47d4d0c536e06fc53eda9d5a1a5d93f9accc6Jesse Wilson        assertContainsNoneMatching(request.getHeaders(), "null:.*");
14283a47d4d0c536e06fc53eda9d5a1a5d93f9accc6Jesse Wilson
14383a47d4d0c536e06fc53eda9d5a1a5d93f9accc6Jesse Wilson        try {
14483a47d4d0c536e06fc53eda9d5a1a5d93f9accc6Jesse Wilson            urlConnection.addRequestProperty("N", "o");
14583a47d4d0c536e06fc53eda9d5a1a5d93f9accc6Jesse Wilson            fail("Set header after connect");
14683a47d4d0c536e06fc53eda9d5a1a5d93f9accc6Jesse Wilson        } catch (IllegalStateException expected) {
14783a47d4d0c536e06fc53eda9d5a1a5d93f9accc6Jesse Wilson        }
14883a47d4d0c536e06fc53eda9d5a1a5d93f9accc6Jesse Wilson        try {
14983a47d4d0c536e06fc53eda9d5a1a5d93f9accc6Jesse Wilson            urlConnection.setRequestProperty("P", "q");
15083a47d4d0c536e06fc53eda9d5a1a5d93f9accc6Jesse Wilson            fail("Set header after connect");
15183a47d4d0c536e06fc53eda9d5a1a5d93f9accc6Jesse Wilson        } catch (IllegalStateException expected) {
15283a47d4d0c536e06fc53eda9d5a1a5d93f9accc6Jesse Wilson        }
153ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson        try {
154ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson            urlConnection.getRequestProperties();
155ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson            fail();
156ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson        } catch (IllegalStateException expected) {
157ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson        }
158ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson    }
159ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson
160ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson    public void testGetRequestPropertyReturnsLastValue() throws Exception {
161ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson        server.play();
162ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson        HttpURLConnection urlConnection = (HttpURLConnection) server.getUrl("/").openConnection();
163ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson        urlConnection.addRequestProperty("A", "value1");
164ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson        urlConnection.addRequestProperty("A", "value2");
165ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson        assertEquals("value2", urlConnection.getRequestProperty("A"));
16683a47d4d0c536e06fc53eda9d5a1a5d93f9accc6Jesse Wilson    }
16783a47d4d0c536e06fc53eda9d5a1a5d93f9accc6Jesse Wilson
16883a47d4d0c536e06fc53eda9d5a1a5d93f9accc6Jesse Wilson    public void testResponseHeaders() throws IOException, InterruptedException {
16983a47d4d0c536e06fc53eda9d5a1a5d93f9accc6Jesse Wilson        server.enqueue(new MockResponse()
17083a47d4d0c536e06fc53eda9d5a1a5d93f9accc6Jesse Wilson                .setStatus("HTTP/1.0 200 Fantastic")
17183a47d4d0c536e06fc53eda9d5a1a5d93f9accc6Jesse Wilson                .addHeader("A: c")
172ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson                .addHeader("B: d")
173ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson                .addHeader("A: e")
17483a47d4d0c536e06fc53eda9d5a1a5d93f9accc6Jesse Wilson                .setChunkedBody("ABCDE\nFGHIJ\nKLMNO\nPQR", 8));
17583a47d4d0c536e06fc53eda9d5a1a5d93f9accc6Jesse Wilson        server.play();
17683a47d4d0c536e06fc53eda9d5a1a5d93f9accc6Jesse Wilson
17783a47d4d0c536e06fc53eda9d5a1a5d93f9accc6Jesse Wilson        HttpURLConnection urlConnection = (HttpURLConnection) server.getUrl("/").openConnection();
17883a47d4d0c536e06fc53eda9d5a1a5d93f9accc6Jesse Wilson        assertEquals(200, urlConnection.getResponseCode());
17983a47d4d0c536e06fc53eda9d5a1a5d93f9accc6Jesse Wilson        assertEquals("Fantastic", urlConnection.getResponseMessage());
180c1a675c80c69decadb736b245f0366f93a94a462Jesse Wilson        assertEquals("HTTP/1.0 200 Fantastic", urlConnection.getHeaderField(null));
18183a47d4d0c536e06fc53eda9d5a1a5d93f9accc6Jesse Wilson        Map<String, List<String>> responseHeaders = urlConnection.getHeaderFields();
1828ac847a52e72f0cefbb20a6850ae04468d433a9eJesse Wilson        assertEquals(Arrays.asList("HTTP/1.0 200 Fantastic"), responseHeaders.get(null));
183ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson        assertEquals(newSet("c", "e"), new HashSet<String>(responseHeaders.get("A")));
184ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson        assertEquals(newSet("c", "e"), new HashSet<String>(responseHeaders.get("a")));
18583a47d4d0c536e06fc53eda9d5a1a5d93f9accc6Jesse Wilson        try {
18683a47d4d0c536e06fc53eda9d5a1a5d93f9accc6Jesse Wilson            responseHeaders.put("N", Arrays.asList("o"));
18783a47d4d0c536e06fc53eda9d5a1a5d93f9accc6Jesse Wilson            fail("Modified an unmodifiable view.");
18883a47d4d0c536e06fc53eda9d5a1a5d93f9accc6Jesse Wilson        } catch (UnsupportedOperationException expected) {
18983a47d4d0c536e06fc53eda9d5a1a5d93f9accc6Jesse Wilson        }
19083a47d4d0c536e06fc53eda9d5a1a5d93f9accc6Jesse Wilson        try {
191ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson            responseHeaders.get("A").add("f");
19283a47d4d0c536e06fc53eda9d5a1a5d93f9accc6Jesse Wilson            fail("Modified an unmodifiable view.");
19383a47d4d0c536e06fc53eda9d5a1a5d93f9accc6Jesse Wilson        } catch (UnsupportedOperationException expected) {
19483a47d4d0c536e06fc53eda9d5a1a5d93f9accc6Jesse Wilson        }
195ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson        assertEquals("A", urlConnection.getHeaderFieldKey(0));
196ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson        assertEquals("c", urlConnection.getHeaderField(0));
197ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson        assertEquals("B", urlConnection.getHeaderFieldKey(1));
198ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson        assertEquals("d", urlConnection.getHeaderField(1));
199ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson        assertEquals("A", urlConnection.getHeaderFieldKey(2));
200ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson        assertEquals("e", urlConnection.getHeaderField(2));
201ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson    }
202ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson
203ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson    public void testGetErrorStreamOnSuccessfulRequest() throws Exception {
204ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson        server.enqueue(new MockResponse().setBody("A"));
205ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson        server.play();
206ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson        HttpURLConnection connection = (HttpURLConnection) server.getUrl("/").openConnection();
207ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson        assertNull(connection.getErrorStream());
208ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson    }
209ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson
210ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson    public void testGetErrorStreamOnUnsuccessfulRequest() throws Exception {
211ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson        server.enqueue(new MockResponse().setResponseCode(404).setBody("A"));
212ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson        server.play();
213ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson        HttpURLConnection connection = (HttpURLConnection) server.getUrl("/").openConnection();
214ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson        assertEquals("A", readAscii(connection.getErrorStream(), Integer.MAX_VALUE));
21583a47d4d0c536e06fc53eda9d5a1a5d93f9accc6Jesse Wilson    }
21683a47d4d0c536e06fc53eda9d5a1a5d93f9accc6Jesse Wilson
217e40c9e3935a5024c0f3ebfb3f1441fcd5c48ed86Elliott Hughes    // Check that if we don't read to the end of a response, the next request on the
218e40c9e3935a5024c0f3ebfb3f1441fcd5c48ed86Elliott Hughes    // recycled connection doesn't get the unread tail of the first request's response.
219e40c9e3935a5024c0f3ebfb3f1441fcd5c48ed86Elliott Hughes    // http://code.google.com/p/android/issues/detail?id=2939
220e40c9e3935a5024c0f3ebfb3f1441fcd5c48ed86Elliott Hughes    public void test_2939() throws Exception {
221b1b5baac449d2725002338735f4db34bec8fd001Jesse Wilson        MockResponse response = new MockResponse().setChunkedBody("ABCDE\nFGHIJ\nKLMNO\nPQR", 8);
222b1b5baac449d2725002338735f4db34bec8fd001Jesse Wilson
223b1b5baac449d2725002338735f4db34bec8fd001Jesse Wilson        server.enqueue(response);
224b1b5baac449d2725002338735f4db34bec8fd001Jesse Wilson        server.enqueue(response);
225b1b5baac449d2725002338735f4db34bec8fd001Jesse Wilson        server.play();
226b1b5baac449d2725002338735f4db34bec8fd001Jesse Wilson
227c8977f474b30c5f3807398859a6b16687af6fc7bJesse Wilson        assertContent("ABCDE", server.getUrl("/").openConnection(), 5);
228c8977f474b30c5f3807398859a6b16687af6fc7bJesse Wilson        assertContent("ABCDE", server.getUrl("/").openConnection(), 5);
2298baf143a7c8921d07b54adbc66ac1e5b42de5fe6Jesse Wilson    }
2308baf143a7c8921d07b54adbc66ac1e5b42de5fe6Jesse Wilson
231977a9954414ec41256b218e6278a8544ea135d45Elliott Hughes    // Check that we recognize a few basic mime types by extension.
232977a9954414ec41256b218e6278a8544ea135d45Elliott Hughes    // http://code.google.com/p/android/issues/detail?id=10100
233977a9954414ec41256b218e6278a8544ea135d45Elliott Hughes    public void test_10100() throws Exception {
234977a9954414ec41256b218e6278a8544ea135d45Elliott Hughes        assertEquals("image/jpeg", URLConnection.guessContentTypeFromName("someFile.jpg"));
235977a9954414ec41256b218e6278a8544ea135d45Elliott Hughes        assertEquals("application/pdf", URLConnection.guessContentTypeFromName("stuff.pdf"));
236977a9954414ec41256b218e6278a8544ea135d45Elliott Hughes    }
237977a9954414ec41256b218e6278a8544ea135d45Elliott Hughes
2388baf143a7c8921d07b54adbc66ac1e5b42de5fe6Jesse Wilson    public void testConnectionsArePooled() throws Exception {
239b1b5baac449d2725002338735f4db34bec8fd001Jesse Wilson        MockResponse response = new MockResponse().setBody("ABCDEFGHIJKLMNOPQR");
240b1b5baac449d2725002338735f4db34bec8fd001Jesse Wilson
241b1b5baac449d2725002338735f4db34bec8fd001Jesse Wilson        server.enqueue(response);
242b1b5baac449d2725002338735f4db34bec8fd001Jesse Wilson        server.enqueue(response);
243b1b5baac449d2725002338735f4db34bec8fd001Jesse Wilson        server.enqueue(response);
244b1b5baac449d2725002338735f4db34bec8fd001Jesse Wilson        server.play();
245b1b5baac449d2725002338735f4db34bec8fd001Jesse Wilson
24606e15e6c528fcb773bedb43e34b0577312570927Jesse Wilson        assertContent("ABCDEFGHIJKLMNOPQR", server.getUrl("/foo").openConnection());
247c8977f474b30c5f3807398859a6b16687af6fc7bJesse Wilson        assertEquals(0, server.takeRequest().getSequenceNumber());
24806e15e6c528fcb773bedb43e34b0577312570927Jesse Wilson        assertContent("ABCDEFGHIJKLMNOPQR", server.getUrl("/bar?baz=quux").openConnection());
249c8977f474b30c5f3807398859a6b16687af6fc7bJesse Wilson        assertEquals(1, server.takeRequest().getSequenceNumber());
25006e15e6c528fcb773bedb43e34b0577312570927Jesse Wilson        assertContent("ABCDEFGHIJKLMNOPQR", server.getUrl("/z").openConnection());
251c8977f474b30c5f3807398859a6b16687af6fc7bJesse Wilson        assertEquals(2, server.takeRequest().getSequenceNumber());
252c8977f474b30c5f3807398859a6b16687af6fc7bJesse Wilson    }
253c8977f474b30c5f3807398859a6b16687af6fc7bJesse Wilson
254c8977f474b30c5f3807398859a6b16687af6fc7bJesse Wilson    public void testChunkedConnectionsArePooled() throws Exception {
255c8977f474b30c5f3807398859a6b16687af6fc7bJesse Wilson        MockResponse response = new MockResponse().setChunkedBody("ABCDEFGHIJKLMNOPQR", 5);
256c8977f474b30c5f3807398859a6b16687af6fc7bJesse Wilson
257c8977f474b30c5f3807398859a6b16687af6fc7bJesse Wilson        server.enqueue(response);
258c8977f474b30c5f3807398859a6b16687af6fc7bJesse Wilson        server.enqueue(response);
259c8977f474b30c5f3807398859a6b16687af6fc7bJesse Wilson        server.enqueue(response);
260c8977f474b30c5f3807398859a6b16687af6fc7bJesse Wilson        server.play();
261c8977f474b30c5f3807398859a6b16687af6fc7bJesse Wilson
26206e15e6c528fcb773bedb43e34b0577312570927Jesse Wilson        assertContent("ABCDEFGHIJKLMNOPQR", server.getUrl("/foo").openConnection());
263b1b5baac449d2725002338735f4db34bec8fd001Jesse Wilson        assertEquals(0, server.takeRequest().getSequenceNumber());
26406e15e6c528fcb773bedb43e34b0577312570927Jesse Wilson        assertContent("ABCDEFGHIJKLMNOPQR", server.getUrl("/bar?baz=quux").openConnection());
265b1b5baac449d2725002338735f4db34bec8fd001Jesse Wilson        assertEquals(1, server.takeRequest().getSequenceNumber());
26606e15e6c528fcb773bedb43e34b0577312570927Jesse Wilson        assertContent("ABCDEFGHIJKLMNOPQR", server.getUrl("/z").openConnection());
267b1b5baac449d2725002338735f4db34bec8fd001Jesse Wilson        assertEquals(2, server.takeRequest().getSequenceNumber());
268e40c9e3935a5024c0f3ebfb3f1441fcd5c48ed86Elliott Hughes    }
26902f0cb2eb84a112fcf644d7d1fd0b5f94ea2f03bElliott Hughes
2700613de89655e481fa610bfd4f1bcaeeae3272205Jesse Wilson    /**
2710613de89655e481fa610bfd4f1bcaeeae3272205Jesse Wilson     * Test that connections are added to the pool as soon as the response has
2720613de89655e481fa610bfd4f1bcaeeae3272205Jesse Wilson     * been consumed.
2730613de89655e481fa610bfd4f1bcaeeae3272205Jesse Wilson     */
2740613de89655e481fa610bfd4f1bcaeeae3272205Jesse Wilson    public void testConnectionsArePooledWithoutExplicitDisconnect() throws Exception {
2750613de89655e481fa610bfd4f1bcaeeae3272205Jesse Wilson        server.enqueue(new MockResponse().setBody("ABC"));
2760613de89655e481fa610bfd4f1bcaeeae3272205Jesse Wilson        server.enqueue(new MockResponse().setBody("DEF"));
2770613de89655e481fa610bfd4f1bcaeeae3272205Jesse Wilson        server.play();
2780613de89655e481fa610bfd4f1bcaeeae3272205Jesse Wilson
2790613de89655e481fa610bfd4f1bcaeeae3272205Jesse Wilson        URLConnection connection1 = server.getUrl("/").openConnection();
2800613de89655e481fa610bfd4f1bcaeeae3272205Jesse Wilson        assertEquals("ABC", readAscii(connection1.getInputStream(), Integer.MAX_VALUE));
2810613de89655e481fa610bfd4f1bcaeeae3272205Jesse Wilson        assertEquals(0, server.takeRequest().getSequenceNumber());
2820613de89655e481fa610bfd4f1bcaeeae3272205Jesse Wilson        URLConnection connection2 = server.getUrl("/").openConnection();
2830613de89655e481fa610bfd4f1bcaeeae3272205Jesse Wilson        assertEquals("DEF", readAscii(connection2.getInputStream(), Integer.MAX_VALUE));
2840613de89655e481fa610bfd4f1bcaeeae3272205Jesse Wilson        assertEquals(1, server.takeRequest().getSequenceNumber());
2850613de89655e481fa610bfd4f1bcaeeae3272205Jesse Wilson    }
2860613de89655e481fa610bfd4f1bcaeeae3272205Jesse Wilson
287e942f46f10bb9384a1b186b3d7b74f9704c57090Jesse Wilson    public void testServerClosesSocket() throws Exception {
288b2b02ac6cd42a69463fd172531aa1f9b9bb887a8Jesse Wilson        testServerClosesSocket(DISCONNECT_AT_END);
289e942f46f10bb9384a1b186b3d7b74f9704c57090Jesse Wilson    }
290e942f46f10bb9384a1b186b3d7b74f9704c57090Jesse Wilson
291e942f46f10bb9384a1b186b3d7b74f9704c57090Jesse Wilson    public void testServerShutdownInput() throws Exception {
292b2b02ac6cd42a69463fd172531aa1f9b9bb887a8Jesse Wilson        testServerClosesSocket(SHUTDOWN_INPUT_AT_END);
293e942f46f10bb9384a1b186b3d7b74f9704c57090Jesse Wilson    }
294e942f46f10bb9384a1b186b3d7b74f9704c57090Jesse Wilson
295b2b02ac6cd42a69463fd172531aa1f9b9bb887a8Jesse Wilson    private void testServerClosesSocket(SocketPolicy socketPolicy) throws Exception {
296e942f46f10bb9384a1b186b3d7b74f9704c57090Jesse Wilson        server.enqueue(new MockResponse()
297e942f46f10bb9384a1b186b3d7b74f9704c57090Jesse Wilson                .setBody("This connection won't pool properly")
298e942f46f10bb9384a1b186b3d7b74f9704c57090Jesse Wilson                .setSocketPolicy(socketPolicy));
299b2b02ac6cd42a69463fd172531aa1f9b9bb887a8Jesse Wilson        server.enqueue(new MockResponse().setBody("This comes after a busted connection"));
300e942f46f10bb9384a1b186b3d7b74f9704c57090Jesse Wilson        server.play();
301e942f46f10bb9384a1b186b3d7b74f9704c57090Jesse Wilson
302e942f46f10bb9384a1b186b3d7b74f9704c57090Jesse Wilson        assertContent("This connection won't pool properly", server.getUrl("/a").openConnection());
303e942f46f10bb9384a1b186b3d7b74f9704c57090Jesse Wilson        assertEquals(0, server.takeRequest().getSequenceNumber());
304e942f46f10bb9384a1b186b3d7b74f9704c57090Jesse Wilson        assertContent("This comes after a busted connection", server.getUrl("/b").openConnection());
305e942f46f10bb9384a1b186b3d7b74f9704c57090Jesse Wilson        // sequence number 0 means the HTTP socket connection was not reused
306e942f46f10bb9384a1b186b3d7b74f9704c57090Jesse Wilson        assertEquals(0, server.takeRequest().getSequenceNumber());
307e942f46f10bb9384a1b186b3d7b74f9704c57090Jesse Wilson    }
308e942f46f10bb9384a1b186b3d7b74f9704c57090Jesse Wilson
309b2b02ac6cd42a69463fd172531aa1f9b9bb887a8Jesse Wilson    public void testServerShutdownOutput() throws Exception {
310b2b02ac6cd42a69463fd172531aa1f9b9bb887a8Jesse Wilson        // This test causes MockWebServer to log a "connection failed" stack trace
311b2b02ac6cd42a69463fd172531aa1f9b9bb887a8Jesse Wilson        server.enqueue(new MockResponse()
312b2b02ac6cd42a69463fd172531aa1f9b9bb887a8Jesse Wilson                .setBody("Output shutdown after this response")
313b2b02ac6cd42a69463fd172531aa1f9b9bb887a8Jesse Wilson                .setSocketPolicy(SHUTDOWN_OUTPUT_AT_END));
314b2b02ac6cd42a69463fd172531aa1f9b9bb887a8Jesse Wilson        server.enqueue(new MockResponse().setBody("This response will fail to write"));
315b2b02ac6cd42a69463fd172531aa1f9b9bb887a8Jesse Wilson        server.enqueue(new MockResponse().setBody("This comes after a busted connection"));
316b2b02ac6cd42a69463fd172531aa1f9b9bb887a8Jesse Wilson        server.play();
317b2b02ac6cd42a69463fd172531aa1f9b9bb887a8Jesse Wilson
318b2b02ac6cd42a69463fd172531aa1f9b9bb887a8Jesse Wilson        assertContent("Output shutdown after this response", server.getUrl("/a").openConnection());
319b2b02ac6cd42a69463fd172531aa1f9b9bb887a8Jesse Wilson        assertEquals(0, server.takeRequest().getSequenceNumber());
320b2b02ac6cd42a69463fd172531aa1f9b9bb887a8Jesse Wilson        assertContent("This comes after a busted connection", server.getUrl("/b").openConnection());
321b2b02ac6cd42a69463fd172531aa1f9b9bb887a8Jesse Wilson        assertEquals(1, server.takeRequest().getSequenceNumber());
322b2b02ac6cd42a69463fd172531aa1f9b9bb887a8Jesse Wilson        assertEquals(0, server.takeRequest().getSequenceNumber());
323b2b02ac6cd42a69463fd172531aa1f9b9bb887a8Jesse Wilson    }
324b2b02ac6cd42a69463fd172531aa1f9b9bb887a8Jesse Wilson
325b2b02ac6cd42a69463fd172531aa1f9b9bb887a8Jesse Wilson    public void testRetryableRequestBodyAfterBrokenConnection() throws Exception {
326b2b02ac6cd42a69463fd172531aa1f9b9bb887a8Jesse Wilson        server.enqueue(new MockResponse().setBody("abc").setSocketPolicy(DISCONNECT_AT_END));
327b2b02ac6cd42a69463fd172531aa1f9b9bb887a8Jesse Wilson        server.enqueue(new MockResponse().setBody("def"));
328b2b02ac6cd42a69463fd172531aa1f9b9bb887a8Jesse Wilson        server.play();
329b2b02ac6cd42a69463fd172531aa1f9b9bb887a8Jesse Wilson
330b2b02ac6cd42a69463fd172531aa1f9b9bb887a8Jesse Wilson        assertContent("abc", server.getUrl("/a").openConnection());
331b2b02ac6cd42a69463fd172531aa1f9b9bb887a8Jesse Wilson        HttpURLConnection connection = (HttpURLConnection) server.getUrl("/b").openConnection();
332b2b02ac6cd42a69463fd172531aa1f9b9bb887a8Jesse Wilson        connection.setDoOutput(true);
333b2b02ac6cd42a69463fd172531aa1f9b9bb887a8Jesse Wilson        OutputStream out = connection.getOutputStream();
334b2b02ac6cd42a69463fd172531aa1f9b9bb887a8Jesse Wilson        out.write(new byte[] {1, 2, 3});
335b2b02ac6cd42a69463fd172531aa1f9b9bb887a8Jesse Wilson        out.close();
336b2b02ac6cd42a69463fd172531aa1f9b9bb887a8Jesse Wilson        assertContent("def", connection);
337b2b02ac6cd42a69463fd172531aa1f9b9bb887a8Jesse Wilson    }
338b2b02ac6cd42a69463fd172531aa1f9b9bb887a8Jesse Wilson
339b2b02ac6cd42a69463fd172531aa1f9b9bb887a8Jesse Wilson    public void testNonRetryableRequestBodyAfterBrokenConnection() throws Exception {
340b2b02ac6cd42a69463fd172531aa1f9b9bb887a8Jesse Wilson        server.enqueue(new MockResponse().setBody("abc").setSocketPolicy(DISCONNECT_AT_END));
341b2b02ac6cd42a69463fd172531aa1f9b9bb887a8Jesse Wilson        server.enqueue(new MockResponse().setBody("def"));
342b2b02ac6cd42a69463fd172531aa1f9b9bb887a8Jesse Wilson        server.play();
343b2b02ac6cd42a69463fd172531aa1f9b9bb887a8Jesse Wilson
344b2b02ac6cd42a69463fd172531aa1f9b9bb887a8Jesse Wilson        assertContent("abc", server.getUrl("/a").openConnection());
345b2b02ac6cd42a69463fd172531aa1f9b9bb887a8Jesse Wilson        HttpURLConnection connection = (HttpURLConnection) server.getUrl("/b").openConnection();
346b2b02ac6cd42a69463fd172531aa1f9b9bb887a8Jesse Wilson        connection.setDoOutput(true);
347b2b02ac6cd42a69463fd172531aa1f9b9bb887a8Jesse Wilson        connection.setFixedLengthStreamingMode(3);
348b2b02ac6cd42a69463fd172531aa1f9b9bb887a8Jesse Wilson        OutputStream out = connection.getOutputStream();
349b2b02ac6cd42a69463fd172531aa1f9b9bb887a8Jesse Wilson        out.write(new byte[] {1, 2, 3});
350b2b02ac6cd42a69463fd172531aa1f9b9bb887a8Jesse Wilson        out.close();
351b2b02ac6cd42a69463fd172531aa1f9b9bb887a8Jesse Wilson        try {
352b2b02ac6cd42a69463fd172531aa1f9b9bb887a8Jesse Wilson            connection.getInputStream();
353b2b02ac6cd42a69463fd172531aa1f9b9bb887a8Jesse Wilson            fail();
354b2b02ac6cd42a69463fd172531aa1f9b9bb887a8Jesse Wilson        } catch (IOException expected) {
355b2b02ac6cd42a69463fd172531aa1f9b9bb887a8Jesse Wilson        }
356b2b02ac6cd42a69463fd172531aa1f9b9bb887a8Jesse Wilson    }
357b2b02ac6cd42a69463fd172531aa1f9b9bb887a8Jesse Wilson
358b1b5baac449d2725002338735f4db34bec8fd001Jesse Wilson    enum WriteKind { BYTE_BY_BYTE, SMALL_BUFFERS, LARGE_BUFFERS }
35902f0cb2eb84a112fcf644d7d1fd0b5f94ea2f03bElliott Hughes
36002f0cb2eb84a112fcf644d7d1fd0b5f94ea2f03bElliott Hughes    public void test_chunkedUpload_byteByByte() throws Exception {
36151e468abf2628ce964d3657042f3ac8f2c947504Jesse Wilson        doUpload(TransferKind.CHUNKED, WriteKind.BYTE_BY_BYTE);
36202f0cb2eb84a112fcf644d7d1fd0b5f94ea2f03bElliott Hughes    }
36302f0cb2eb84a112fcf644d7d1fd0b5f94ea2f03bElliott Hughes
36402f0cb2eb84a112fcf644d7d1fd0b5f94ea2f03bElliott Hughes    public void test_chunkedUpload_smallBuffers() throws Exception {
36551e468abf2628ce964d3657042f3ac8f2c947504Jesse Wilson        doUpload(TransferKind.CHUNKED, WriteKind.SMALL_BUFFERS);
36602f0cb2eb84a112fcf644d7d1fd0b5f94ea2f03bElliott Hughes    }
36702f0cb2eb84a112fcf644d7d1fd0b5f94ea2f03bElliott Hughes
36802f0cb2eb84a112fcf644d7d1fd0b5f94ea2f03bElliott Hughes    public void test_chunkedUpload_largeBuffers() throws Exception {
36951e468abf2628ce964d3657042f3ac8f2c947504Jesse Wilson        doUpload(TransferKind.CHUNKED, WriteKind.LARGE_BUFFERS);
37002f0cb2eb84a112fcf644d7d1fd0b5f94ea2f03bElliott Hughes    }
37102f0cb2eb84a112fcf644d7d1fd0b5f94ea2f03bElliott Hughes
37202f0cb2eb84a112fcf644d7d1fd0b5f94ea2f03bElliott Hughes    public void test_fixedLengthUpload_byteByByte() throws Exception {
37351e468abf2628ce964d3657042f3ac8f2c947504Jesse Wilson        doUpload(TransferKind.FIXED_LENGTH, WriteKind.BYTE_BY_BYTE);
37402f0cb2eb84a112fcf644d7d1fd0b5f94ea2f03bElliott Hughes    }
37502f0cb2eb84a112fcf644d7d1fd0b5f94ea2f03bElliott Hughes
37602f0cb2eb84a112fcf644d7d1fd0b5f94ea2f03bElliott Hughes    public void test_fixedLengthUpload_smallBuffers() throws Exception {
37751e468abf2628ce964d3657042f3ac8f2c947504Jesse Wilson        doUpload(TransferKind.FIXED_LENGTH, WriteKind.SMALL_BUFFERS);
37802f0cb2eb84a112fcf644d7d1fd0b5f94ea2f03bElliott Hughes    }
37902f0cb2eb84a112fcf644d7d1fd0b5f94ea2f03bElliott Hughes
38002f0cb2eb84a112fcf644d7d1fd0b5f94ea2f03bElliott Hughes    public void test_fixedLengthUpload_largeBuffers() throws Exception {
38151e468abf2628ce964d3657042f3ac8f2c947504Jesse Wilson        doUpload(TransferKind.FIXED_LENGTH, WriteKind.LARGE_BUFFERS);
38202f0cb2eb84a112fcf644d7d1fd0b5f94ea2f03bElliott Hughes    }
38302f0cb2eb84a112fcf644d7d1fd0b5f94ea2f03bElliott Hughes
38451e468abf2628ce964d3657042f3ac8f2c947504Jesse Wilson    private void doUpload(TransferKind uploadKind, WriteKind writeKind) throws Exception {
38502f0cb2eb84a112fcf644d7d1fd0b5f94ea2f03bElliott Hughes        int n = 512*1024;
386b1b5baac449d2725002338735f4db34bec8fd001Jesse Wilson        server.setBodyLimit(0);
387b1b5baac449d2725002338735f4db34bec8fd001Jesse Wilson        server.enqueue(new MockResponse());
388b1b5baac449d2725002338735f4db34bec8fd001Jesse Wilson        server.play();
389b1b5baac449d2725002338735f4db34bec8fd001Jesse Wilson
390b1b5baac449d2725002338735f4db34bec8fd001Jesse Wilson        HttpURLConnection conn = (HttpURLConnection) server.getUrl("/").openConnection();
39102f0cb2eb84a112fcf644d7d1fd0b5f94ea2f03bElliott Hughes        conn.setDoOutput(true);
39202f0cb2eb84a112fcf644d7d1fd0b5f94ea2f03bElliott Hughes        conn.setRequestMethod("POST");
39351e468abf2628ce964d3657042f3ac8f2c947504Jesse Wilson        if (uploadKind == TransferKind.CHUNKED) {
39402f0cb2eb84a112fcf644d7d1fd0b5f94ea2f03bElliott Hughes            conn.setChunkedStreamingMode(-1);
39502f0cb2eb84a112fcf644d7d1fd0b5f94ea2f03bElliott Hughes        } else {
39602f0cb2eb84a112fcf644d7d1fd0b5f94ea2f03bElliott Hughes            conn.setFixedLengthStreamingMode(n);
39702f0cb2eb84a112fcf644d7d1fd0b5f94ea2f03bElliott Hughes        }
39802f0cb2eb84a112fcf644d7d1fd0b5f94ea2f03bElliott Hughes        OutputStream out = conn.getOutputStream();
39902f0cb2eb84a112fcf644d7d1fd0b5f94ea2f03bElliott Hughes        if (writeKind == WriteKind.BYTE_BY_BYTE) {
40002f0cb2eb84a112fcf644d7d1fd0b5f94ea2f03bElliott Hughes            for (int i = 0; i < n; ++i) {
40102f0cb2eb84a112fcf644d7d1fd0b5f94ea2f03bElliott Hughes                out.write('x');
40202f0cb2eb84a112fcf644d7d1fd0b5f94ea2f03bElliott Hughes            }
40302f0cb2eb84a112fcf644d7d1fd0b5f94ea2f03bElliott Hughes        } else {
40402f0cb2eb84a112fcf644d7d1fd0b5f94ea2f03bElliott Hughes            byte[] buf = new byte[writeKind == WriteKind.SMALL_BUFFERS ? 256 : 64*1024];
40502f0cb2eb84a112fcf644d7d1fd0b5f94ea2f03bElliott Hughes            Arrays.fill(buf, (byte) 'x');
40602f0cb2eb84a112fcf644d7d1fd0b5f94ea2f03bElliott Hughes            for (int i = 0; i < n; i += buf.length) {
40702f0cb2eb84a112fcf644d7d1fd0b5f94ea2f03bElliott Hughes                out.write(buf, 0, Math.min(buf.length, n - i));
40802f0cb2eb84a112fcf644d7d1fd0b5f94ea2f03bElliott Hughes            }
40902f0cb2eb84a112fcf644d7d1fd0b5f94ea2f03bElliott Hughes        }
41002f0cb2eb84a112fcf644d7d1fd0b5f94ea2f03bElliott Hughes        out.close();
4114cb7f05dc68abb23ae54a5891c369062185f2210Elliott Hughes        assertEquals(200, conn.getResponseCode());
412b1b5baac449d2725002338735f4db34bec8fd001Jesse Wilson        RecordedRequest request = server.takeRequest();
413b1b5baac449d2725002338735f4db34bec8fd001Jesse Wilson        assertEquals(n, request.getBodySize());
41451e468abf2628ce964d3657042f3ac8f2c947504Jesse Wilson        if (uploadKind == TransferKind.CHUNKED) {
415b1b5baac449d2725002338735f4db34bec8fd001Jesse Wilson            assertTrue(request.getChunkSizes().size() > 0);
416b1b5baac449d2725002338735f4db34bec8fd001Jesse Wilson        } else {
417b1b5baac449d2725002338735f4db34bec8fd001Jesse Wilson            assertTrue(request.getChunkSizes().isEmpty());
418b1b5baac449d2725002338735f4db34bec8fd001Jesse Wilson        }
41902f0cb2eb84a112fcf644d7d1fd0b5f94ea2f03bElliott Hughes    }
4206247987eb505a482a67f5f19678260d9e7240a5fElliott Hughes
421f14bee4dbf9f724a177a85a7b73f7b0bc6df1ec0Jesse Wilson    public void testGetResponseCodeNoResponseBody() throws Exception {
422f14bee4dbf9f724a177a85a7b73f7b0bc6df1ec0Jesse Wilson        server.enqueue(new MockResponse()
423f14bee4dbf9f724a177a85a7b73f7b0bc6df1ec0Jesse Wilson                .addHeader("abc: def"));
424f14bee4dbf9f724a177a85a7b73f7b0bc6df1ec0Jesse Wilson        server.play();
425f14bee4dbf9f724a177a85a7b73f7b0bc6df1ec0Jesse Wilson
426f14bee4dbf9f724a177a85a7b73f7b0bc6df1ec0Jesse Wilson        URL url = server.getUrl("/");
427f14bee4dbf9f724a177a85a7b73f7b0bc6df1ec0Jesse Wilson        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
428f14bee4dbf9f724a177a85a7b73f7b0bc6df1ec0Jesse Wilson        conn.setDoInput(false);
429f14bee4dbf9f724a177a85a7b73f7b0bc6df1ec0Jesse Wilson        assertEquals("def", conn.getHeaderField("abc"));
430f14bee4dbf9f724a177a85a7b73f7b0bc6df1ec0Jesse Wilson        assertEquals(200, conn.getResponseCode());
431f14bee4dbf9f724a177a85a7b73f7b0bc6df1ec0Jesse Wilson        try {
432f14bee4dbf9f724a177a85a7b73f7b0bc6df1ec0Jesse Wilson            conn.getInputStream();
433f14bee4dbf9f724a177a85a7b73f7b0bc6df1ec0Jesse Wilson            fail();
434f14bee4dbf9f724a177a85a7b73f7b0bc6df1ec0Jesse Wilson        } catch (ProtocolException expected) {
435f14bee4dbf9f724a177a85a7b73f7b0bc6df1ec0Jesse Wilson        }
436f14bee4dbf9f724a177a85a7b73f7b0bc6df1ec0Jesse Wilson    }
437f14bee4dbf9f724a177a85a7b73f7b0bc6df1ec0Jesse Wilson
43860476787f0e0f052366d8031c74e507ffd3d16a3Jesse Wilson    public void testConnectViaHttps() throws IOException, InterruptedException {
43960476787f0e0f052366d8031c74e507ffd3d16a3Jesse Wilson        TestSSLContext testSSLContext = TestSSLContext.create();
44060476787f0e0f052366d8031c74e507ffd3d16a3Jesse Wilson
441059dbc04218144f985b20a228bbe98139d400d0cBrian Carlstrom        server.useHttps(testSSLContext.serverContext.getSocketFactory(), false);
442c0372d90016d241ac979faa6fa1731f30b6f2a03Jesse Wilson        server.enqueue(new MockResponse().setBody("this response comes via HTTPS"));
44360476787f0e0f052366d8031c74e507ffd3d16a3Jesse Wilson        server.play();
44460476787f0e0f052366d8031c74e507ffd3d16a3Jesse Wilson
445096aac7b8a607d3da237900f52cab1c5066bf992Jesse Wilson        HttpsURLConnection connection = (HttpsURLConnection) server.getUrl("/foo").openConnection();
4464559b1d37edcb5d7f1da086cf2e3290388d74f46Brian Carlstrom        connection.setSSLSocketFactory(testSSLContext.clientContext.getSocketFactory());
44760476787f0e0f052366d8031c74e507ffd3d16a3Jesse Wilson
448c8977f474b30c5f3807398859a6b16687af6fc7bJesse Wilson        assertContent("this response comes via HTTPS", connection);
44960476787f0e0f052366d8031c74e507ffd3d16a3Jesse Wilson
45060476787f0e0f052366d8031c74e507ffd3d16a3Jesse Wilson        RecordedRequest request = server.takeRequest();
45160476787f0e0f052366d8031c74e507ffd3d16a3Jesse Wilson        assertEquals("GET /foo HTTP/1.1", request.getRequestLine());
452abe4e615f473b387b1c00a738062a7c428f05a33Jesse Wilson        assertEquals("TLSv1", request.getSslProtocol());
45360476787f0e0f052366d8031c74e507ffd3d16a3Jesse Wilson    }
45460476787f0e0f052366d8031c74e507ffd3d16a3Jesse Wilson
455096aac7b8a607d3da237900f52cab1c5066bf992Jesse Wilson    public void testConnectViaHttpsReusingConnections() throws IOException, InterruptedException {
456096aac7b8a607d3da237900f52cab1c5066bf992Jesse Wilson        TestSSLContext testSSLContext = TestSSLContext.create();
457fa5e8dfe3c7ed144b0fbe69091628dedd6a3b961Jesse Wilson        SSLSocketFactory clientSocketFactory = testSSLContext.clientContext.getSocketFactory();
458096aac7b8a607d3da237900f52cab1c5066bf992Jesse Wilson
459059dbc04218144f985b20a228bbe98139d400d0cBrian Carlstrom        server.useHttps(testSSLContext.serverContext.getSocketFactory(), false);
460096aac7b8a607d3da237900f52cab1c5066bf992Jesse Wilson        server.enqueue(new MockResponse().setBody("this response comes via HTTPS"));
461096aac7b8a607d3da237900f52cab1c5066bf992Jesse Wilson        server.enqueue(new MockResponse().setBody("another response via HTTPS"));
462096aac7b8a607d3da237900f52cab1c5066bf992Jesse Wilson        server.play();
463096aac7b8a607d3da237900f52cab1c5066bf992Jesse Wilson
464b7155fd57239e986bbaba254a91aeb9600d60305Jesse Wilson        HttpsURLConnection connection = (HttpsURLConnection) server.getUrl("/").openConnection();
465fa5e8dfe3c7ed144b0fbe69091628dedd6a3b961Jesse Wilson        connection.setSSLSocketFactory(clientSocketFactory);
466b7155fd57239e986bbaba254a91aeb9600d60305Jesse Wilson        assertContent("this response comes via HTTPS", connection);
467b7155fd57239e986bbaba254a91aeb9600d60305Jesse Wilson
468b7155fd57239e986bbaba254a91aeb9600d60305Jesse Wilson        connection = (HttpsURLConnection) server.getUrl("/").openConnection();
469fa5e8dfe3c7ed144b0fbe69091628dedd6a3b961Jesse Wilson        connection.setSSLSocketFactory(clientSocketFactory);
470b7155fd57239e986bbaba254a91aeb9600d60305Jesse Wilson        assertContent("another response via HTTPS", connection);
471b7155fd57239e986bbaba254a91aeb9600d60305Jesse Wilson
472b7155fd57239e986bbaba254a91aeb9600d60305Jesse Wilson        assertEquals(0, server.takeRequest().getSequenceNumber());
473b7155fd57239e986bbaba254a91aeb9600d60305Jesse Wilson        assertEquals(1, server.takeRequest().getSequenceNumber());
474b7155fd57239e986bbaba254a91aeb9600d60305Jesse Wilson    }
475b7155fd57239e986bbaba254a91aeb9600d60305Jesse Wilson
4768116f7e97e00d223e7fbe5c950c9a5e3277de124Jesse Wilson    public void testConnectViaHttpsReusingConnectionsDifferentFactories()
477b7155fd57239e986bbaba254a91aeb9600d60305Jesse Wilson            throws IOException, InterruptedException {
478b7155fd57239e986bbaba254a91aeb9600d60305Jesse Wilson        TestSSLContext testSSLContext = TestSSLContext.create();
479b7155fd57239e986bbaba254a91aeb9600d60305Jesse Wilson
480b7155fd57239e986bbaba254a91aeb9600d60305Jesse Wilson        server.useHttps(testSSLContext.serverContext.getSocketFactory(), false);
481b7155fd57239e986bbaba254a91aeb9600d60305Jesse Wilson        server.enqueue(new MockResponse().setBody("this response comes via HTTPS"));
482b7155fd57239e986bbaba254a91aeb9600d60305Jesse Wilson        server.enqueue(new MockResponse().setBody("another response via HTTPS"));
483b7155fd57239e986bbaba254a91aeb9600d60305Jesse Wilson        server.play();
484b7155fd57239e986bbaba254a91aeb9600d60305Jesse Wilson
485096aac7b8a607d3da237900f52cab1c5066bf992Jesse Wilson        // install a custom SSL socket factory so the server can be authorized
486096aac7b8a607d3da237900f52cab1c5066bf992Jesse Wilson        HttpsURLConnection connection = (HttpsURLConnection) server.getUrl("/").openConnection();
487059dbc04218144f985b20a228bbe98139d400d0cBrian Carlstrom        connection.setSSLSocketFactory(testSSLContext.clientContext.getSocketFactory());
488096aac7b8a607d3da237900f52cab1c5066bf992Jesse Wilson        assertContent("this response comes via HTTPS", connection);
489096aac7b8a607d3da237900f52cab1c5066bf992Jesse Wilson
490096aac7b8a607d3da237900f52cab1c5066bf992Jesse Wilson        connection = (HttpsURLConnection) server.getUrl("/").openConnection();
491096aac7b8a607d3da237900f52cab1c5066bf992Jesse Wilson        try {
492096aac7b8a607d3da237900f52cab1c5066bf992Jesse Wilson            readAscii(connection.getInputStream(), Integer.MAX_VALUE);
493b7155fd57239e986bbaba254a91aeb9600d60305Jesse Wilson            fail("without an SSL socket factory, the connection should fail");
494096aac7b8a607d3da237900f52cab1c5066bf992Jesse Wilson        } catch (SSLException expected) {
495096aac7b8a607d3da237900f52cab1c5066bf992Jesse Wilson        }
496096aac7b8a607d3da237900f52cab1c5066bf992Jesse Wilson    }
497096aac7b8a607d3da237900f52cab1c5066bf992Jesse Wilson
4984559b1d37edcb5d7f1da086cf2e3290388d74f46Brian Carlstrom    public void testConnectViaHttpsWithSSLFallback() throws IOException, InterruptedException {
4994559b1d37edcb5d7f1da086cf2e3290388d74f46Brian Carlstrom        TestSSLContext testSSLContext = TestSSLContext.create();
5004559b1d37edcb5d7f1da086cf2e3290388d74f46Brian Carlstrom
5014559b1d37edcb5d7f1da086cf2e3290388d74f46Brian Carlstrom        server.useHttps(testSSLContext.serverContext.getSocketFactory(), false);
502e942f46f10bb9384a1b186b3d7b74f9704c57090Jesse Wilson        server.enqueue(new MockResponse().setSocketPolicy(DISCONNECT_AT_START));
5034559b1d37edcb5d7f1da086cf2e3290388d74f46Brian Carlstrom        server.enqueue(new MockResponse().setBody("this response comes via SSL"));
5044559b1d37edcb5d7f1da086cf2e3290388d74f46Brian Carlstrom        server.play();
5054559b1d37edcb5d7f1da086cf2e3290388d74f46Brian Carlstrom
5064559b1d37edcb5d7f1da086cf2e3290388d74f46Brian Carlstrom        HttpsURLConnection connection = (HttpsURLConnection) server.getUrl("/foo").openConnection();
5074559b1d37edcb5d7f1da086cf2e3290388d74f46Brian Carlstrom        connection.setSSLSocketFactory(testSSLContext.clientContext.getSocketFactory());
5084559b1d37edcb5d7f1da086cf2e3290388d74f46Brian Carlstrom
5094559b1d37edcb5d7f1da086cf2e3290388d74f46Brian Carlstrom        assertContent("this response comes via SSL", connection);
5104559b1d37edcb5d7f1da086cf2e3290388d74f46Brian Carlstrom
5114559b1d37edcb5d7f1da086cf2e3290388d74f46Brian Carlstrom        RecordedRequest request = server.takeRequest();
5124559b1d37edcb5d7f1da086cf2e3290388d74f46Brian Carlstrom        assertEquals("GET /foo HTTP/1.1", request.getRequestLine());
5134559b1d37edcb5d7f1da086cf2e3290388d74f46Brian Carlstrom    }
5144559b1d37edcb5d7f1da086cf2e3290388d74f46Brian Carlstrom
5152915378e253f08e47fe5a9bfd026cd1ca7c6c351Brian Carlstrom    /**
5162915378e253f08e47fe5a9bfd026cd1ca7c6c351Brian Carlstrom     * Verify that we don't retry connections on certificate verification errors.
5172915378e253f08e47fe5a9bfd026cd1ca7c6c351Brian Carlstrom     *
5182915378e253f08e47fe5a9bfd026cd1ca7c6c351Brian Carlstrom     * http://code.google.com/p/android/issues/detail?id=13178
5192915378e253f08e47fe5a9bfd026cd1ca7c6c351Brian Carlstrom     */
5202915378e253f08e47fe5a9bfd026cd1ca7c6c351Brian Carlstrom    public void testConnectViaHttpsToUntrustedServer() throws IOException, InterruptedException {
5212915378e253f08e47fe5a9bfd026cd1ca7c6c351Brian Carlstrom        TestSSLContext testSSLContext = TestSSLContext.create(TestKeyStore.getClientCA2(),
5222915378e253f08e47fe5a9bfd026cd1ca7c6c351Brian Carlstrom                                                              TestKeyStore.getServer());
5232915378e253f08e47fe5a9bfd026cd1ca7c6c351Brian Carlstrom
5242915378e253f08e47fe5a9bfd026cd1ca7c6c351Brian Carlstrom        server.useHttps(testSSLContext.serverContext.getSocketFactory(), false);
5252915378e253f08e47fe5a9bfd026cd1ca7c6c351Brian Carlstrom        server.enqueue(new MockResponse()); // unused
5262915378e253f08e47fe5a9bfd026cd1ca7c6c351Brian Carlstrom        server.play();
5272915378e253f08e47fe5a9bfd026cd1ca7c6c351Brian Carlstrom
5282915378e253f08e47fe5a9bfd026cd1ca7c6c351Brian Carlstrom        HttpsURLConnection connection = (HttpsURLConnection) server.getUrl("/foo").openConnection();
5292915378e253f08e47fe5a9bfd026cd1ca7c6c351Brian Carlstrom        connection.setSSLSocketFactory(testSSLContext.clientContext.getSocketFactory());
5302915378e253f08e47fe5a9bfd026cd1ca7c6c351Brian Carlstrom        try {
5312915378e253f08e47fe5a9bfd026cd1ca7c6c351Brian Carlstrom            connection.getInputStream();
5322915378e253f08e47fe5a9bfd026cd1ca7c6c351Brian Carlstrom            fail();
5332915378e253f08e47fe5a9bfd026cd1ca7c6c351Brian Carlstrom        } catch (SSLHandshakeException expected) {
5342915378e253f08e47fe5a9bfd026cd1ca7c6c351Brian Carlstrom            assertTrue(expected.getCause() instanceof CertificateException);
5352915378e253f08e47fe5a9bfd026cd1ca7c6c351Brian Carlstrom        }
5362915378e253f08e47fe5a9bfd026cd1ca7c6c351Brian Carlstrom        assertEquals(0, server.getRequestCount());
5372915378e253f08e47fe5a9bfd026cd1ca7c6c351Brian Carlstrom    }
5382915378e253f08e47fe5a9bfd026cd1ca7c6c351Brian Carlstrom
539984fcff696380abd6ea14e80030f9fd2d09dbad0Jesse Wilson    public void testConnectViaProxyUsingProxyArg() throws Exception {
540984fcff696380abd6ea14e80030f9fd2d09dbad0Jesse Wilson        testConnectViaProxy(ProxyConfig.CREATE_ARG);
541984fcff696380abd6ea14e80030f9fd2d09dbad0Jesse Wilson    }
542984fcff696380abd6ea14e80030f9fd2d09dbad0Jesse Wilson
543984fcff696380abd6ea14e80030f9fd2d09dbad0Jesse Wilson    public void testConnectViaProxyUsingProxySystemProperty() throws Exception {
544984fcff696380abd6ea14e80030f9fd2d09dbad0Jesse Wilson        testConnectViaProxy(ProxyConfig.PROXY_SYSTEM_PROPERTY);
545984fcff696380abd6ea14e80030f9fd2d09dbad0Jesse Wilson    }
546984fcff696380abd6ea14e80030f9fd2d09dbad0Jesse Wilson
547984fcff696380abd6ea14e80030f9fd2d09dbad0Jesse Wilson    public void testConnectViaProxyUsingHttpProxySystemProperty() throws Exception {
548984fcff696380abd6ea14e80030f9fd2d09dbad0Jesse Wilson        testConnectViaProxy(ProxyConfig.HTTP_PROXY_SYSTEM_PROPERTY);
549984fcff696380abd6ea14e80030f9fd2d09dbad0Jesse Wilson    }
550984fcff696380abd6ea14e80030f9fd2d09dbad0Jesse Wilson
551984fcff696380abd6ea14e80030f9fd2d09dbad0Jesse Wilson    private void testConnectViaProxy(ProxyConfig proxyConfig) throws Exception {
552c0372d90016d241ac979faa6fa1731f30b6f2a03Jesse Wilson        MockResponse mockResponse = new MockResponse().setBody("this response comes via a proxy");
55351e468abf2628ce964d3657042f3ac8f2c947504Jesse Wilson        server.enqueue(mockResponse);
55451e468abf2628ce964d3657042f3ac8f2c947504Jesse Wilson        server.play();
55560476787f0e0f052366d8031c74e507ffd3d16a3Jesse Wilson
556984fcff696380abd6ea14e80030f9fd2d09dbad0Jesse Wilson        URL url = new URL("http://android.com/foo");
557984fcff696380abd6ea14e80030f9fd2d09dbad0Jesse Wilson        HttpURLConnection connection = proxyConfig.connect(server, url);
558c8977f474b30c5f3807398859a6b16687af6fc7bJesse Wilson        assertContent("this response comes via a proxy", connection);
55960476787f0e0f052366d8031c74e507ffd3d16a3Jesse Wilson
56051e468abf2628ce964d3657042f3ac8f2c947504Jesse Wilson        RecordedRequest request = server.takeRequest();
56160476787f0e0f052366d8031c74e507ffd3d16a3Jesse Wilson        assertEquals("GET http://android.com/foo HTTP/1.1", request.getRequestLine());
56260476787f0e0f052366d8031c74e507ffd3d16a3Jesse Wilson        assertContains(request.getHeaders(), "Host: android.com");
56360476787f0e0f052366d8031c74e507ffd3d16a3Jesse Wilson    }
56460476787f0e0f052366d8031c74e507ffd3d16a3Jesse Wilson
565c8977f474b30c5f3807398859a6b16687af6fc7bJesse Wilson    public void testContentDisagreesWithContentLengthHeader() throws IOException {
566c8977f474b30c5f3807398859a6b16687af6fc7bJesse Wilson        server.enqueue(new MockResponse()
567c8977f474b30c5f3807398859a6b16687af6fc7bJesse Wilson                .setBody("abc\r\nYOU SHOULD NOT SEE THIS")
568c8977f474b30c5f3807398859a6b16687af6fc7bJesse Wilson                .clearHeaders()
569c8977f474b30c5f3807398859a6b16687af6fc7bJesse Wilson                .addHeader("Content-Length: 3"));
570c8977f474b30c5f3807398859a6b16687af6fc7bJesse Wilson        server.play();
571c8977f474b30c5f3807398859a6b16687af6fc7bJesse Wilson
572c8977f474b30c5f3807398859a6b16687af6fc7bJesse Wilson        assertContent("abc", server.getUrl("/").openConnection());
573c8977f474b30c5f3807398859a6b16687af6fc7bJesse Wilson    }
574c8977f474b30c5f3807398859a6b16687af6fc7bJesse Wilson
575c8977f474b30c5f3807398859a6b16687af6fc7bJesse Wilson    public void testContentDisagreesWithChunkedHeader() throws IOException {
576c8977f474b30c5f3807398859a6b16687af6fc7bJesse Wilson        MockResponse mockResponse = new MockResponse();
577c8977f474b30c5f3807398859a6b16687af6fc7bJesse Wilson        mockResponse.setChunkedBody("abc", 3);
578c8977f474b30c5f3807398859a6b16687af6fc7bJesse Wilson        ByteArrayOutputStream bytesOut = new ByteArrayOutputStream();
579c8977f474b30c5f3807398859a6b16687af6fc7bJesse Wilson        bytesOut.write(mockResponse.getBody());
580c8977f474b30c5f3807398859a6b16687af6fc7bJesse Wilson        bytesOut.write("\r\nYOU SHOULD NOT SEE THIS".getBytes());
581c8977f474b30c5f3807398859a6b16687af6fc7bJesse Wilson        mockResponse.setBody(bytesOut.toByteArray());
582c8977f474b30c5f3807398859a6b16687af6fc7bJesse Wilson        mockResponse.clearHeaders();
583c8977f474b30c5f3807398859a6b16687af6fc7bJesse Wilson        mockResponse.addHeader("Transfer-encoding: chunked");
584c8977f474b30c5f3807398859a6b16687af6fc7bJesse Wilson
585c8977f474b30c5f3807398859a6b16687af6fc7bJesse Wilson        server.enqueue(mockResponse);
586c8977f474b30c5f3807398859a6b16687af6fc7bJesse Wilson        server.play();
587c8977f474b30c5f3807398859a6b16687af6fc7bJesse Wilson
588c8977f474b30c5f3807398859a6b16687af6fc7bJesse Wilson        assertContent("abc", server.getUrl("/").openConnection());
589c8977f474b30c5f3807398859a6b16687af6fc7bJesse Wilson    }
590c8977f474b30c5f3807398859a6b16687af6fc7bJesse Wilson
591f02c695ed03e708623d9365dec26d533356ef2d0Brian Carlstrom    public void testConnectViaHttpProxyToHttpsUsingProxyArgWithNoProxy() throws Exception {
592f02c695ed03e708623d9365dec26d533356ef2d0Brian Carlstrom        testConnectViaDirectProxyToHttps(ProxyConfig.NO_PROXY);
593f02c695ed03e708623d9365dec26d533356ef2d0Brian Carlstrom    }
594f02c695ed03e708623d9365dec26d533356ef2d0Brian Carlstrom
595f02c695ed03e708623d9365dec26d533356ef2d0Brian Carlstrom    public void testConnectViaHttpProxyToHttpsUsingHttpProxySystemProperty() throws Exception {
596f02c695ed03e708623d9365dec26d533356ef2d0Brian Carlstrom        // https should not use http proxy
597f02c695ed03e708623d9365dec26d533356ef2d0Brian Carlstrom        testConnectViaDirectProxyToHttps(ProxyConfig.HTTP_PROXY_SYSTEM_PROPERTY);
598f02c695ed03e708623d9365dec26d533356ef2d0Brian Carlstrom    }
599f02c695ed03e708623d9365dec26d533356ef2d0Brian Carlstrom
600f02c695ed03e708623d9365dec26d533356ef2d0Brian Carlstrom    private void testConnectViaDirectProxyToHttps(ProxyConfig proxyConfig) throws Exception {
601f02c695ed03e708623d9365dec26d533356ef2d0Brian Carlstrom        TestSSLContext testSSLContext = TestSSLContext.create();
602f02c695ed03e708623d9365dec26d533356ef2d0Brian Carlstrom
603f02c695ed03e708623d9365dec26d533356ef2d0Brian Carlstrom        server.useHttps(testSSLContext.serverContext.getSocketFactory(), false);
604f02c695ed03e708623d9365dec26d533356ef2d0Brian Carlstrom        server.enqueue(new MockResponse().setBody("this response comes via HTTPS"));
605f02c695ed03e708623d9365dec26d533356ef2d0Brian Carlstrom        server.play();
606f02c695ed03e708623d9365dec26d533356ef2d0Brian Carlstrom
607f02c695ed03e708623d9365dec26d533356ef2d0Brian Carlstrom        URL url = server.getUrl("/foo");
608f02c695ed03e708623d9365dec26d533356ef2d0Brian Carlstrom        HttpsURLConnection connection = (HttpsURLConnection) proxyConfig.connect(server, url);
609f02c695ed03e708623d9365dec26d533356ef2d0Brian Carlstrom        connection.setSSLSocketFactory(testSSLContext.clientContext.getSocketFactory());
610f02c695ed03e708623d9365dec26d533356ef2d0Brian Carlstrom
611f02c695ed03e708623d9365dec26d533356ef2d0Brian Carlstrom        assertContent("this response comes via HTTPS", connection);
612f02c695ed03e708623d9365dec26d533356ef2d0Brian Carlstrom
613f02c695ed03e708623d9365dec26d533356ef2d0Brian Carlstrom        RecordedRequest request = server.takeRequest();
614f02c695ed03e708623d9365dec26d533356ef2d0Brian Carlstrom        assertEquals("GET /foo HTTP/1.1", request.getRequestLine());
615f02c695ed03e708623d9365dec26d533356ef2d0Brian Carlstrom    }
616f02c695ed03e708623d9365dec26d533356ef2d0Brian Carlstrom
617f02c695ed03e708623d9365dec26d533356ef2d0Brian Carlstrom
618984fcff696380abd6ea14e80030f9fd2d09dbad0Jesse Wilson    public void testConnectViaHttpProxyToHttpsUsingProxyArg() throws Exception {
619984fcff696380abd6ea14e80030f9fd2d09dbad0Jesse Wilson        testConnectViaHttpProxyToHttps(ProxyConfig.CREATE_ARG);
620984fcff696380abd6ea14e80030f9fd2d09dbad0Jesse Wilson    }
621984fcff696380abd6ea14e80030f9fd2d09dbad0Jesse Wilson
622984fcff696380abd6ea14e80030f9fd2d09dbad0Jesse Wilson    /**
623984fcff696380abd6ea14e80030f9fd2d09dbad0Jesse Wilson     * We weren't honoring all of the appropriate proxy system properties when
624984fcff696380abd6ea14e80030f9fd2d09dbad0Jesse Wilson     * connecting via HTTPS. http://b/3097518
625984fcff696380abd6ea14e80030f9fd2d09dbad0Jesse Wilson     */
626984fcff696380abd6ea14e80030f9fd2d09dbad0Jesse Wilson    public void testConnectViaHttpProxyToHttpsUsingProxySystemProperty() throws Exception {
627984fcff696380abd6ea14e80030f9fd2d09dbad0Jesse Wilson        testConnectViaHttpProxyToHttps(ProxyConfig.PROXY_SYSTEM_PROPERTY);
628984fcff696380abd6ea14e80030f9fd2d09dbad0Jesse Wilson    }
629984fcff696380abd6ea14e80030f9fd2d09dbad0Jesse Wilson
630984fcff696380abd6ea14e80030f9fd2d09dbad0Jesse Wilson    public void testConnectViaHttpProxyToHttpsUsingHttpsProxySystemProperty() throws Exception {
631984fcff696380abd6ea14e80030f9fd2d09dbad0Jesse Wilson        testConnectViaHttpProxyToHttps(ProxyConfig.HTTPS_PROXY_SYSTEM_PROPERTY);
632984fcff696380abd6ea14e80030f9fd2d09dbad0Jesse Wilson    }
633984fcff696380abd6ea14e80030f9fd2d09dbad0Jesse Wilson
634984fcff696380abd6ea14e80030f9fd2d09dbad0Jesse Wilson    /**
635984fcff696380abd6ea14e80030f9fd2d09dbad0Jesse Wilson     * We were verifying the wrong hostname when connecting to an HTTPS site
636984fcff696380abd6ea14e80030f9fd2d09dbad0Jesse Wilson     * through a proxy. http://b/3097277
637984fcff696380abd6ea14e80030f9fd2d09dbad0Jesse Wilson     */
638984fcff696380abd6ea14e80030f9fd2d09dbad0Jesse Wilson    private void testConnectViaHttpProxyToHttps(ProxyConfig proxyConfig) throws Exception {
63960476787f0e0f052366d8031c74e507ffd3d16a3Jesse Wilson        TestSSLContext testSSLContext = TestSSLContext.create();
640984fcff696380abd6ea14e80030f9fd2d09dbad0Jesse Wilson        RecordingHostnameVerifier hostnameVerifier = new RecordingHostnameVerifier();
64160476787f0e0f052366d8031c74e507ffd3d16a3Jesse Wilson
642059dbc04218144f985b20a228bbe98139d400d0cBrian Carlstrom        server.useHttps(testSSLContext.serverContext.getSocketFactory(), true);
643c996149b500fc4825156106554457fe2394ae087Jesse Wilson        server.enqueue(new MockResponse()
644c996149b500fc4825156106554457fe2394ae087Jesse Wilson                .setSocketPolicy(SocketPolicy.UPGRADE_TO_SSL_AT_END)
645c996149b500fc4825156106554457fe2394ae087Jesse Wilson                .clearHeaders());
646c0372d90016d241ac979faa6fa1731f30b6f2a03Jesse Wilson        server.enqueue(new MockResponse().setBody("this response comes via a secure proxy"));
64751e468abf2628ce964d3657042f3ac8f2c947504Jesse Wilson        server.play();
64860476787f0e0f052366d8031c74e507ffd3d16a3Jesse Wilson
64960476787f0e0f052366d8031c74e507ffd3d16a3Jesse Wilson        URL url = new URL("https://android.com/foo");
650984fcff696380abd6ea14e80030f9fd2d09dbad0Jesse Wilson        HttpsURLConnection connection = (HttpsURLConnection) proxyConfig.connect(server, url);
651059dbc04218144f985b20a228bbe98139d400d0cBrian Carlstrom        connection.setSSLSocketFactory(testSSLContext.clientContext.getSocketFactory());
652984fcff696380abd6ea14e80030f9fd2d09dbad0Jesse Wilson        connection.setHostnameVerifier(hostnameVerifier);
65360476787f0e0f052366d8031c74e507ffd3d16a3Jesse Wilson
654c8977f474b30c5f3807398859a6b16687af6fc7bJesse Wilson        assertContent("this response comes via a secure proxy", connection);
65560476787f0e0f052366d8031c74e507ffd3d16a3Jesse Wilson
65651e468abf2628ce964d3657042f3ac8f2c947504Jesse Wilson        RecordedRequest connect = server.takeRequest();
65760476787f0e0f052366d8031c74e507ffd3d16a3Jesse Wilson        assertEquals("Connect line failure on proxy",
65860476787f0e0f052366d8031c74e507ffd3d16a3Jesse Wilson                "CONNECT android.com:443 HTTP/1.1", connect.getRequestLine());
65960476787f0e0f052366d8031c74e507ffd3d16a3Jesse Wilson        assertContains(connect.getHeaders(), "Host: android.com");
66060476787f0e0f052366d8031c74e507ffd3d16a3Jesse Wilson
66151e468abf2628ce964d3657042f3ac8f2c947504Jesse Wilson        RecordedRequest get = server.takeRequest();
66260476787f0e0f052366d8031c74e507ffd3d16a3Jesse Wilson        assertEquals("GET /foo HTTP/1.1", get.getRequestLine());
66360476787f0e0f052366d8031c74e507ffd3d16a3Jesse Wilson        assertContains(get.getHeaders(), "Host: android.com");
664984fcff696380abd6ea14e80030f9fd2d09dbad0Jesse Wilson        assertEquals(Arrays.asList("verify android.com"), hostnameVerifier.calls);
66560476787f0e0f052366d8031c74e507ffd3d16a3Jesse Wilson    }
66660476787f0e0f052366d8031c74e507ffd3d16a3Jesse Wilson
667d4bddd7d1fb7b1b7f0836648228235c6e4b56a18Jesse Wilson    /**
668d4bddd7d1fb7b1b7f0836648228235c6e4b56a18Jesse Wilson     * Test which headers are sent unencrypted to the HTTP proxy.
669d4bddd7d1fb7b1b7f0836648228235c6e4b56a18Jesse Wilson     */
670d4bddd7d1fb7b1b7f0836648228235c6e4b56a18Jesse Wilson    public void testProxyConnectIncludesProxyHeadersOnly()
671d4bddd7d1fb7b1b7f0836648228235c6e4b56a18Jesse Wilson            throws IOException, InterruptedException {
672984fcff696380abd6ea14e80030f9fd2d09dbad0Jesse Wilson        RecordingHostnameVerifier hostnameVerifier = new RecordingHostnameVerifier();
673d4bddd7d1fb7b1b7f0836648228235c6e4b56a18Jesse Wilson        TestSSLContext testSSLContext = TestSSLContext.create();
674d4bddd7d1fb7b1b7f0836648228235c6e4b56a18Jesse Wilson
675d4bddd7d1fb7b1b7f0836648228235c6e4b56a18Jesse Wilson        server.useHttps(testSSLContext.serverContext.getSocketFactory(), true);
676c996149b500fc4825156106554457fe2394ae087Jesse Wilson        server.enqueue(new MockResponse()
677c996149b500fc4825156106554457fe2394ae087Jesse Wilson                .setSocketPolicy(SocketPolicy.UPGRADE_TO_SSL_AT_END)
678c996149b500fc4825156106554457fe2394ae087Jesse Wilson                .clearHeaders());
679d4bddd7d1fb7b1b7f0836648228235c6e4b56a18Jesse Wilson        server.enqueue(new MockResponse().setBody("encrypted response from the origin server"));
680d4bddd7d1fb7b1b7f0836648228235c6e4b56a18Jesse Wilson        server.play();
681d4bddd7d1fb7b1b7f0836648228235c6e4b56a18Jesse Wilson
682d4bddd7d1fb7b1b7f0836648228235c6e4b56a18Jesse Wilson        URL url = new URL("https://android.com/foo");
683d4bddd7d1fb7b1b7f0836648228235c6e4b56a18Jesse Wilson        HttpsURLConnection connection = (HttpsURLConnection) url.openConnection(
684d4bddd7d1fb7b1b7f0836648228235c6e4b56a18Jesse Wilson                server.toProxyAddress());
685d4bddd7d1fb7b1b7f0836648228235c6e4b56a18Jesse Wilson        connection.addRequestProperty("Private", "Secret");
686d4bddd7d1fb7b1b7f0836648228235c6e4b56a18Jesse Wilson        connection.addRequestProperty("Proxy-Authorization", "bar");
687d4bddd7d1fb7b1b7f0836648228235c6e4b56a18Jesse Wilson        connection.addRequestProperty("User-Agent", "baz");
688d4bddd7d1fb7b1b7f0836648228235c6e4b56a18Jesse Wilson        connection.setSSLSocketFactory(testSSLContext.clientContext.getSocketFactory());
689984fcff696380abd6ea14e80030f9fd2d09dbad0Jesse Wilson        connection.setHostnameVerifier(hostnameVerifier);
690d4bddd7d1fb7b1b7f0836648228235c6e4b56a18Jesse Wilson        assertContent("encrypted response from the origin server", connection);
691d4bddd7d1fb7b1b7f0836648228235c6e4b56a18Jesse Wilson
692d4bddd7d1fb7b1b7f0836648228235c6e4b56a18Jesse Wilson        RecordedRequest connect = server.takeRequest();
693d4bddd7d1fb7b1b7f0836648228235c6e4b56a18Jesse Wilson        assertContainsNoneMatching(connect.getHeaders(), "Private.*");
694d4bddd7d1fb7b1b7f0836648228235c6e4b56a18Jesse Wilson        assertContains(connect.getHeaders(), "Proxy-Authorization: bar");
695d4bddd7d1fb7b1b7f0836648228235c6e4b56a18Jesse Wilson        assertContains(connect.getHeaders(), "User-Agent: baz");
696d4bddd7d1fb7b1b7f0836648228235c6e4b56a18Jesse Wilson        assertContains(connect.getHeaders(), "Host: android.com");
697d4bddd7d1fb7b1b7f0836648228235c6e4b56a18Jesse Wilson        assertContains(connect.getHeaders(), "Proxy-Connection: Keep-Alive");
698d4bddd7d1fb7b1b7f0836648228235c6e4b56a18Jesse Wilson
699d4bddd7d1fb7b1b7f0836648228235c6e4b56a18Jesse Wilson        RecordedRequest get = server.takeRequest();
700d4bddd7d1fb7b1b7f0836648228235c6e4b56a18Jesse Wilson        assertContains(get.getHeaders(), "Private: Secret");
701984fcff696380abd6ea14e80030f9fd2d09dbad0Jesse Wilson        assertEquals(Arrays.asList("verify android.com"), hostnameVerifier.calls);
702d4bddd7d1fb7b1b7f0836648228235c6e4b56a18Jesse Wilson    }
703d4bddd7d1fb7b1b7f0836648228235c6e4b56a18Jesse Wilson
704c996149b500fc4825156106554457fe2394ae087Jesse Wilson    public void testProxyAuthenticateOnConnect() throws Exception {
7055757cb35ad2e58d7accb7f5d3db6f2d5e72f097dJesse Wilson        Authenticator.setDefault(new SimpleAuthenticator());
706c996149b500fc4825156106554457fe2394ae087Jesse Wilson        TestSSLContext testSSLContext = TestSSLContext.create();
707c996149b500fc4825156106554457fe2394ae087Jesse Wilson        server.useHttps(testSSLContext.serverContext.getSocketFactory(), true);
708c996149b500fc4825156106554457fe2394ae087Jesse Wilson        server.enqueue(new MockResponse()
709c996149b500fc4825156106554457fe2394ae087Jesse Wilson                .setResponseCode(407)
710c996149b500fc4825156106554457fe2394ae087Jesse Wilson                .addHeader("Proxy-Authenticate: Basic realm=\"localhost\""));
711c996149b500fc4825156106554457fe2394ae087Jesse Wilson        server.enqueue(new MockResponse()
712c996149b500fc4825156106554457fe2394ae087Jesse Wilson                .setSocketPolicy(SocketPolicy.UPGRADE_TO_SSL_AT_END)
713c996149b500fc4825156106554457fe2394ae087Jesse Wilson                .clearHeaders());
714c996149b500fc4825156106554457fe2394ae087Jesse Wilson        server.enqueue(new MockResponse().setBody("A"));
715c996149b500fc4825156106554457fe2394ae087Jesse Wilson        server.play();
716c996149b500fc4825156106554457fe2394ae087Jesse Wilson
717c996149b500fc4825156106554457fe2394ae087Jesse Wilson        URL url = new URL("https://android.com/foo");
718c996149b500fc4825156106554457fe2394ae087Jesse Wilson        HttpsURLConnection connection = (HttpsURLConnection) url.openConnection(
719c996149b500fc4825156106554457fe2394ae087Jesse Wilson                server.toProxyAddress());
720c996149b500fc4825156106554457fe2394ae087Jesse Wilson        connection.setSSLSocketFactory(testSSLContext.clientContext.getSocketFactory());
721c996149b500fc4825156106554457fe2394ae087Jesse Wilson        connection.setHostnameVerifier(new RecordingHostnameVerifier());
722c996149b500fc4825156106554457fe2394ae087Jesse Wilson        assertContent("A", connection);
723c996149b500fc4825156106554457fe2394ae087Jesse Wilson
724c996149b500fc4825156106554457fe2394ae087Jesse Wilson        RecordedRequest connect1 = server.takeRequest();
725c996149b500fc4825156106554457fe2394ae087Jesse Wilson        assertEquals("CONNECT android.com:443 HTTP/1.1", connect1.getRequestLine());
726c996149b500fc4825156106554457fe2394ae087Jesse Wilson        assertContainsNoneMatching(connect1.getHeaders(), "Proxy\\-Authorization.*");
727c996149b500fc4825156106554457fe2394ae087Jesse Wilson
728c996149b500fc4825156106554457fe2394ae087Jesse Wilson        RecordedRequest connect2 = server.takeRequest();
729c996149b500fc4825156106554457fe2394ae087Jesse Wilson        assertEquals("CONNECT android.com:443 HTTP/1.1", connect2.getRequestLine());
7305757cb35ad2e58d7accb7f5d3db6f2d5e72f097dJesse Wilson        assertContains(connect2.getHeaders(), "Proxy-Authorization: Basic "
7315757cb35ad2e58d7accb7f5d3db6f2d5e72f097dJesse Wilson                + SimpleAuthenticator.BASE_64_CREDENTIALS);
732c996149b500fc4825156106554457fe2394ae087Jesse Wilson
733c996149b500fc4825156106554457fe2394ae087Jesse Wilson        RecordedRequest get = server.takeRequest();
734c996149b500fc4825156106554457fe2394ae087Jesse Wilson        assertEquals("GET /foo HTTP/1.1", get.getRequestLine());
735c996149b500fc4825156106554457fe2394ae087Jesse Wilson        assertContainsNoneMatching(get.getHeaders(), "Proxy\\-Authorization.*");
736c996149b500fc4825156106554457fe2394ae087Jesse Wilson    }
737c996149b500fc4825156106554457fe2394ae087Jesse Wilson
738d4bddd7d1fb7b1b7f0836648228235c6e4b56a18Jesse Wilson    public void testDisconnectedConnection() throws IOException {
739d4bddd7d1fb7b1b7f0836648228235c6e4b56a18Jesse Wilson        server.enqueue(new MockResponse().setBody("ABCDEFGHIJKLMNOPQR"));
740d4bddd7d1fb7b1b7f0836648228235c6e4b56a18Jesse Wilson        server.play();
741d4bddd7d1fb7b1b7f0836648228235c6e4b56a18Jesse Wilson
742d4bddd7d1fb7b1b7f0836648228235c6e4b56a18Jesse Wilson        HttpURLConnection connection = (HttpURLConnection) server.getUrl("/").openConnection();
743d4bddd7d1fb7b1b7f0836648228235c6e4b56a18Jesse Wilson        InputStream in = connection.getInputStream();
744d4bddd7d1fb7b1b7f0836648228235c6e4b56a18Jesse Wilson        assertEquals('A', (char) in.read());
745d4bddd7d1fb7b1b7f0836648228235c6e4b56a18Jesse Wilson        connection.disconnect();
746d4bddd7d1fb7b1b7f0836648228235c6e4b56a18Jesse Wilson        try {
747d4bddd7d1fb7b1b7f0836648228235c6e4b56a18Jesse Wilson            in.read();
748d4bddd7d1fb7b1b7f0836648228235c6e4b56a18Jesse Wilson            fail("Expected a connection closed exception");
749d4bddd7d1fb7b1b7f0836648228235c6e4b56a18Jesse Wilson        } catch (IOException expected) {
750d4bddd7d1fb7b1b7f0836648228235c6e4b56a18Jesse Wilson        }
751d4bddd7d1fb7b1b7f0836648228235c6e4b56a18Jesse Wilson    }
752d4bddd7d1fb7b1b7f0836648228235c6e4b56a18Jesse Wilson
753d742d7fc7f0593eb8c6e4ac9dd4c0f6a80374e46Jesse Wilson    public void testDisconnectBeforeConnect() throws IOException {
754d742d7fc7f0593eb8c6e4ac9dd4c0f6a80374e46Jesse Wilson        server.enqueue(new MockResponse().setBody("A"));
755d742d7fc7f0593eb8c6e4ac9dd4c0f6a80374e46Jesse Wilson        server.play();
756d742d7fc7f0593eb8c6e4ac9dd4c0f6a80374e46Jesse Wilson
757d742d7fc7f0593eb8c6e4ac9dd4c0f6a80374e46Jesse Wilson        HttpURLConnection connection = (HttpURLConnection) server.getUrl("/").openConnection();
758d742d7fc7f0593eb8c6e4ac9dd4c0f6a80374e46Jesse Wilson        connection.disconnect();
759d742d7fc7f0593eb8c6e4ac9dd4c0f6a80374e46Jesse Wilson
760d742d7fc7f0593eb8c6e4ac9dd4c0f6a80374e46Jesse Wilson        assertContent("A", connection);
761d742d7fc7f0593eb8c6e4ac9dd4c0f6a80374e46Jesse Wilson        assertEquals(200, connection.getResponseCode());
762d742d7fc7f0593eb8c6e4ac9dd4c0f6a80374e46Jesse Wilson    }
763d742d7fc7f0593eb8c6e4ac9dd4c0f6a80374e46Jesse Wilson
764d742d7fc7f0593eb8c6e4ac9dd4c0f6a80374e46Jesse Wilson    public void testDefaultRequestProperty() throws Exception {
765d742d7fc7f0593eb8c6e4ac9dd4c0f6a80374e46Jesse Wilson        URLConnection.setDefaultRequestProperty("X-testSetDefaultRequestProperty", "A");
766d742d7fc7f0593eb8c6e4ac9dd4c0f6a80374e46Jesse Wilson        assertNull(URLConnection.getDefaultRequestProperty("X-setDefaultRequestProperty"));
767d742d7fc7f0593eb8c6e4ac9dd4c0f6a80374e46Jesse Wilson    }
768d742d7fc7f0593eb8c6e4ac9dd4c0f6a80374e46Jesse Wilson
76951e468abf2628ce964d3657042f3ac8f2c947504Jesse Wilson    /**
77051e468abf2628ce964d3657042f3ac8f2c947504Jesse Wilson     * Reads {@code count} characters from the stream. If the stream is
77151e468abf2628ce964d3657042f3ac8f2c947504Jesse Wilson     * exhausted before {@code count} characters can be read, the remaining
77251e468abf2628ce964d3657042f3ac8f2c947504Jesse Wilson     * characters are returned and the stream is closed.
77351e468abf2628ce964d3657042f3ac8f2c947504Jesse Wilson     */
77451e468abf2628ce964d3657042f3ac8f2c947504Jesse Wilson    private String readAscii(InputStream in, int count) throws IOException {
77551e468abf2628ce964d3657042f3ac8f2c947504Jesse Wilson        StringBuilder result = new StringBuilder();
77651e468abf2628ce964d3657042f3ac8f2c947504Jesse Wilson        for (int i = 0; i < count; i++) {
77751e468abf2628ce964d3657042f3ac8f2c947504Jesse Wilson            int value = in.read();
77851e468abf2628ce964d3657042f3ac8f2c947504Jesse Wilson            if (value == -1) {
77951e468abf2628ce964d3657042f3ac8f2c947504Jesse Wilson                in.close();
78051e468abf2628ce964d3657042f3ac8f2c947504Jesse Wilson                break;
78151e468abf2628ce964d3657042f3ac8f2c947504Jesse Wilson            }
78251e468abf2628ce964d3657042f3ac8f2c947504Jesse Wilson            result.append((char) value);
78351e468abf2628ce964d3657042f3ac8f2c947504Jesse Wilson        }
78451e468abf2628ce964d3657042f3ac8f2c947504Jesse Wilson        return result.toString();
78551e468abf2628ce964d3657042f3ac8f2c947504Jesse Wilson    }
78651e468abf2628ce964d3657042f3ac8f2c947504Jesse Wilson
78751e468abf2628ce964d3657042f3ac8f2c947504Jesse Wilson    public void testMarkAndResetWithContentLengthHeader() throws IOException {
78851e468abf2628ce964d3657042f3ac8f2c947504Jesse Wilson        testMarkAndReset(TransferKind.FIXED_LENGTH);
78951e468abf2628ce964d3657042f3ac8f2c947504Jesse Wilson    }
79051e468abf2628ce964d3657042f3ac8f2c947504Jesse Wilson
79151e468abf2628ce964d3657042f3ac8f2c947504Jesse Wilson    public void testMarkAndResetWithChunkedEncoding() throws IOException {
79251e468abf2628ce964d3657042f3ac8f2c947504Jesse Wilson        testMarkAndReset(TransferKind.CHUNKED);
79351e468abf2628ce964d3657042f3ac8f2c947504Jesse Wilson    }
79451e468abf2628ce964d3657042f3ac8f2c947504Jesse Wilson
79551e468abf2628ce964d3657042f3ac8f2c947504Jesse Wilson    public void testMarkAndResetWithNoLengthHeaders() throws IOException {
79651e468abf2628ce964d3657042f3ac8f2c947504Jesse Wilson        testMarkAndReset(TransferKind.END_OF_STREAM);
79751e468abf2628ce964d3657042f3ac8f2c947504Jesse Wilson    }
79851e468abf2628ce964d3657042f3ac8f2c947504Jesse Wilson
7990c2fd828abec671333b8b88281825fd27a783723Jesse Wilson    private void testMarkAndReset(TransferKind transferKind) throws IOException {
80051e468abf2628ce964d3657042f3ac8f2c947504Jesse Wilson        MockResponse response = new MockResponse();
80151e468abf2628ce964d3657042f3ac8f2c947504Jesse Wilson        transferKind.setBody(response, "ABCDEFGHIJKLMNOPQRSTUVWXYZ", 1024);
80251e468abf2628ce964d3657042f3ac8f2c947504Jesse Wilson        server.enqueue(response);
803953df613522e12a418cb7cb73248594d6c9f53d4Jesse Wilson        server.enqueue(response);
80451e468abf2628ce964d3657042f3ac8f2c947504Jesse Wilson        server.play();
80551e468abf2628ce964d3657042f3ac8f2c947504Jesse Wilson
80651e468abf2628ce964d3657042f3ac8f2c947504Jesse Wilson        InputStream in = server.getUrl("/").openConnection().getInputStream();
80751e468abf2628ce964d3657042f3ac8f2c947504Jesse Wilson        assertFalse("This implementation claims to support mark().", in.markSupported());
80851e468abf2628ce964d3657042f3ac8f2c947504Jesse Wilson        in.mark(5);
80951e468abf2628ce964d3657042f3ac8f2c947504Jesse Wilson        assertEquals("ABCDE", readAscii(in, 5));
81051e468abf2628ce964d3657042f3ac8f2c947504Jesse Wilson        try {
81151e468abf2628ce964d3657042f3ac8f2c947504Jesse Wilson            in.reset();
81251e468abf2628ce964d3657042f3ac8f2c947504Jesse Wilson            fail();
81351e468abf2628ce964d3657042f3ac8f2c947504Jesse Wilson        } catch (IOException expected) {
81451e468abf2628ce964d3657042f3ac8f2c947504Jesse Wilson        }
81551e468abf2628ce964d3657042f3ac8f2c947504Jesse Wilson        assertEquals("FGHIJKLMNOPQRSTUVWXYZ", readAscii(in, Integer.MAX_VALUE));
81651e468abf2628ce964d3657042f3ac8f2c947504Jesse Wilson        assertContent("ABCDEFGHIJKLMNOPQRSTUVWXYZ", server.getUrl("/").openConnection());
81751e468abf2628ce964d3657042f3ac8f2c947504Jesse Wilson    }
81851e468abf2628ce964d3657042f3ac8f2c947504Jesse Wilson
81951e468abf2628ce964d3657042f3ac8f2c947504Jesse Wilson    /**
82051e468abf2628ce964d3657042f3ac8f2c947504Jesse Wilson     * We've had a bug where we forget the HTTP response when we see response
82151e468abf2628ce964d3657042f3ac8f2c947504Jesse Wilson     * code 401. This causes a new HTTP request to be issued for every call into
82251e468abf2628ce964d3657042f3ac8f2c947504Jesse Wilson     * the URLConnection.
82351e468abf2628ce964d3657042f3ac8f2c947504Jesse Wilson     */
82451e468abf2628ce964d3657042f3ac8f2c947504Jesse Wilson    public void testUnauthorizedResponseHandling() throws IOException {
82551e468abf2628ce964d3657042f3ac8f2c947504Jesse Wilson        MockResponse response = new MockResponse()
8265757cb35ad2e58d7accb7f5d3db6f2d5e72f097dJesse Wilson                .addHeader("WWW-Authenticate: Basic realm=\"protected area\"")
82751e468abf2628ce964d3657042f3ac8f2c947504Jesse Wilson                .setResponseCode(401) // UNAUTHORIZED
82851e468abf2628ce964d3657042f3ac8f2c947504Jesse Wilson                .setBody("Unauthorized");
82951e468abf2628ce964d3657042f3ac8f2c947504Jesse Wilson        server.enqueue(response);
83051e468abf2628ce964d3657042f3ac8f2c947504Jesse Wilson        server.enqueue(response);
83151e468abf2628ce964d3657042f3ac8f2c947504Jesse Wilson        server.enqueue(response);
83251e468abf2628ce964d3657042f3ac8f2c947504Jesse Wilson        server.play();
83351e468abf2628ce964d3657042f3ac8f2c947504Jesse Wilson
83451e468abf2628ce964d3657042f3ac8f2c947504Jesse Wilson        URL url = server.getUrl("/");
83551e468abf2628ce964d3657042f3ac8f2c947504Jesse Wilson        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
83651e468abf2628ce964d3657042f3ac8f2c947504Jesse Wilson
83751e468abf2628ce964d3657042f3ac8f2c947504Jesse Wilson        assertEquals(401, conn.getResponseCode());
83851e468abf2628ce964d3657042f3ac8f2c947504Jesse Wilson        assertEquals(401, conn.getResponseCode());
83951e468abf2628ce964d3657042f3ac8f2c947504Jesse Wilson        assertEquals(401, conn.getResponseCode());
84051e468abf2628ce964d3657042f3ac8f2c947504Jesse Wilson        assertEquals(1, server.getRequestCount());
84151e468abf2628ce964d3657042f3ac8f2c947504Jesse Wilson    }
84251e468abf2628ce964d3657042f3ac8f2c947504Jesse Wilson
8436906b0c12dcf3216883d0373973a252812a20d32Jesse Wilson    public void testNonHexChunkSize() throws IOException {
8446906b0c12dcf3216883d0373973a252812a20d32Jesse Wilson        server.enqueue(new MockResponse()
8456906b0c12dcf3216883d0373973a252812a20d32Jesse Wilson                .setBody("5\r\nABCDE\r\nG\r\nFGHIJKLMNOPQRSTU\r\n0\r\n\r\n")
8466906b0c12dcf3216883d0373973a252812a20d32Jesse Wilson                .clearHeaders()
8476906b0c12dcf3216883d0373973a252812a20d32Jesse Wilson                .addHeader("Transfer-encoding: chunked"));
8486906b0c12dcf3216883d0373973a252812a20d32Jesse Wilson        server.play();
8496906b0c12dcf3216883d0373973a252812a20d32Jesse Wilson
8506906b0c12dcf3216883d0373973a252812a20d32Jesse Wilson        URLConnection connection = server.getUrl("/").openConnection();
8516906b0c12dcf3216883d0373973a252812a20d32Jesse Wilson        try {
8526906b0c12dcf3216883d0373973a252812a20d32Jesse Wilson            readAscii(connection.getInputStream(), Integer.MAX_VALUE);
8536906b0c12dcf3216883d0373973a252812a20d32Jesse Wilson            fail();
8546906b0c12dcf3216883d0373973a252812a20d32Jesse Wilson        } catch (IOException e) {
8556906b0c12dcf3216883d0373973a252812a20d32Jesse Wilson        }
8566906b0c12dcf3216883d0373973a252812a20d32Jesse Wilson    }
8576906b0c12dcf3216883d0373973a252812a20d32Jesse Wilson
8586906b0c12dcf3216883d0373973a252812a20d32Jesse Wilson    public void testMissingChunkBody() throws IOException {
8596906b0c12dcf3216883d0373973a252812a20d32Jesse Wilson        server.enqueue(new MockResponse()
8606906b0c12dcf3216883d0373973a252812a20d32Jesse Wilson                .setBody("5")
8616906b0c12dcf3216883d0373973a252812a20d32Jesse Wilson                .clearHeaders()
8626906b0c12dcf3216883d0373973a252812a20d32Jesse Wilson                .addHeader("Transfer-encoding: chunked")
863e942f46f10bb9384a1b186b3d7b74f9704c57090Jesse Wilson                .setSocketPolicy(DISCONNECT_AT_END));
8646906b0c12dcf3216883d0373973a252812a20d32Jesse Wilson        server.play();
8656906b0c12dcf3216883d0373973a252812a20d32Jesse Wilson
8666906b0c12dcf3216883d0373973a252812a20d32Jesse Wilson        URLConnection connection = server.getUrl("/").openConnection();
8676906b0c12dcf3216883d0373973a252812a20d32Jesse Wilson        try {
8686906b0c12dcf3216883d0373973a252812a20d32Jesse Wilson            readAscii(connection.getInputStream(), Integer.MAX_VALUE);
8696906b0c12dcf3216883d0373973a252812a20d32Jesse Wilson            fail();
8706906b0c12dcf3216883d0373973a252812a20d32Jesse Wilson        } catch (IOException e) {
8716906b0c12dcf3216883d0373973a252812a20d32Jesse Wilson        }
8726906b0c12dcf3216883d0373973a252812a20d32Jesse Wilson    }
8736906b0c12dcf3216883d0373973a252812a20d32Jesse Wilson
87450ae32218918eae80298bd1ab8e4f588bbbabdb2Jesse Wilson    /**
87550ae32218918eae80298bd1ab8e4f588bbbabdb2Jesse Wilson     * This test checks whether connections are gzipped by default. This
87650ae32218918eae80298bd1ab8e4f588bbbabdb2Jesse Wilson     * behavior in not required by the API, so a failure of this test does not
87750ae32218918eae80298bd1ab8e4f588bbbabdb2Jesse Wilson     * imply a bug in the implementation.
87850ae32218918eae80298bd1ab8e4f588bbbabdb2Jesse Wilson     */
87950ae32218918eae80298bd1ab8e4f588bbbabdb2Jesse Wilson    public void testGzipEncodingEnabledByDefault() throws IOException, InterruptedException {
88050ae32218918eae80298bd1ab8e4f588bbbabdb2Jesse Wilson        server.enqueue(new MockResponse()
88150ae32218918eae80298bd1ab8e4f588bbbabdb2Jesse Wilson                .setBody(gzip("ABCABCABC".getBytes("UTF-8")))
88250ae32218918eae80298bd1ab8e4f588bbbabdb2Jesse Wilson                .addHeader("Content-Encoding: gzip"));
88350ae32218918eae80298bd1ab8e4f588bbbabdb2Jesse Wilson        server.play();
88450ae32218918eae80298bd1ab8e4f588bbbabdb2Jesse Wilson
88550ae32218918eae80298bd1ab8e4f588bbbabdb2Jesse Wilson        URLConnection connection = server.getUrl("/").openConnection();
88650ae32218918eae80298bd1ab8e4f588bbbabdb2Jesse Wilson        assertEquals("ABCABCABC", readAscii(connection.getInputStream(), Integer.MAX_VALUE));
8878116f7e97e00d223e7fbe5c950c9a5e3277de124Jesse Wilson        assertNull(connection.getContentEncoding());
88850ae32218918eae80298bd1ab8e4f588bbbabdb2Jesse Wilson
88950ae32218918eae80298bd1ab8e4f588bbbabdb2Jesse Wilson        RecordedRequest request = server.takeRequest();
89050ae32218918eae80298bd1ab8e4f588bbbabdb2Jesse Wilson        assertContains(request.getHeaders(), "Accept-Encoding: gzip");
89150ae32218918eae80298bd1ab8e4f588bbbabdb2Jesse Wilson    }
89250ae32218918eae80298bd1ab8e4f588bbbabdb2Jesse Wilson
893deb236fb06f2a14861e7d40dea959f181cd5cf28Jesse Wilson    public void testClientConfiguredGzipContentEncoding() throws Exception {
894deb236fb06f2a14861e7d40dea959f181cd5cf28Jesse Wilson        server.enqueue(new MockResponse()
895deb236fb06f2a14861e7d40dea959f181cd5cf28Jesse Wilson                .setBody(gzip("ABCDEFGHIJKLMNOPQRSTUVWXYZ".getBytes("UTF-8")))
896deb236fb06f2a14861e7d40dea959f181cd5cf28Jesse Wilson                .addHeader("Content-Encoding: gzip"));
897deb236fb06f2a14861e7d40dea959f181cd5cf28Jesse Wilson        server.play();
898deb236fb06f2a14861e7d40dea959f181cd5cf28Jesse Wilson
899deb236fb06f2a14861e7d40dea959f181cd5cf28Jesse Wilson        URLConnection connection = server.getUrl("/").openConnection();
900deb236fb06f2a14861e7d40dea959f181cd5cf28Jesse Wilson        connection.addRequestProperty("Accept-Encoding", "gzip");
901deb236fb06f2a14861e7d40dea959f181cd5cf28Jesse Wilson        InputStream gunzippedIn = new GZIPInputStream(connection.getInputStream());
902deb236fb06f2a14861e7d40dea959f181cd5cf28Jesse Wilson        assertEquals("ABCDEFGHIJKLMNOPQRSTUVWXYZ", readAscii(gunzippedIn, Integer.MAX_VALUE));
903deb236fb06f2a14861e7d40dea959f181cd5cf28Jesse Wilson
904deb236fb06f2a14861e7d40dea959f181cd5cf28Jesse Wilson        RecordedRequest request = server.takeRequest();
905deb236fb06f2a14861e7d40dea959f181cd5cf28Jesse Wilson        assertContains(request.getHeaders(), "Accept-Encoding: gzip");
906deb236fb06f2a14861e7d40dea959f181cd5cf28Jesse Wilson    }
907deb236fb06f2a14861e7d40dea959f181cd5cf28Jesse Wilson
908deb236fb06f2a14861e7d40dea959f181cd5cf28Jesse Wilson    public void testGzipAndConnectionReuseWithFixedLength() throws Exception {
909deb236fb06f2a14861e7d40dea959f181cd5cf28Jesse Wilson        testClientConfiguredGzipContentEncodingAndConnectionReuse(TransferKind.FIXED_LENGTH);
910deb236fb06f2a14861e7d40dea959f181cd5cf28Jesse Wilson    }
911deb236fb06f2a14861e7d40dea959f181cd5cf28Jesse Wilson
912deb236fb06f2a14861e7d40dea959f181cd5cf28Jesse Wilson    public void testGzipAndConnectionReuseWithChunkedEncoding() throws Exception {
913deb236fb06f2a14861e7d40dea959f181cd5cf28Jesse Wilson        testClientConfiguredGzipContentEncodingAndConnectionReuse(TransferKind.CHUNKED);
914deb236fb06f2a14861e7d40dea959f181cd5cf28Jesse Wilson    }
915deb236fb06f2a14861e7d40dea959f181cd5cf28Jesse Wilson
91650ae32218918eae80298bd1ab8e4f588bbbabdb2Jesse Wilson    public void testClientConfiguredCustomContentEncoding() throws Exception {
91750ae32218918eae80298bd1ab8e4f588bbbabdb2Jesse Wilson        server.enqueue(new MockResponse()
91850ae32218918eae80298bd1ab8e4f588bbbabdb2Jesse Wilson                .setBody("ABCDE")
91950ae32218918eae80298bd1ab8e4f588bbbabdb2Jesse Wilson                .addHeader("Content-Encoding: custom"));
92050ae32218918eae80298bd1ab8e4f588bbbabdb2Jesse Wilson        server.play();
92150ae32218918eae80298bd1ab8e4f588bbbabdb2Jesse Wilson
92250ae32218918eae80298bd1ab8e4f588bbbabdb2Jesse Wilson        URLConnection connection = server.getUrl("/").openConnection();
92350ae32218918eae80298bd1ab8e4f588bbbabdb2Jesse Wilson        connection.addRequestProperty("Accept-Encoding", "custom");
92450ae32218918eae80298bd1ab8e4f588bbbabdb2Jesse Wilson        assertEquals("ABCDE", readAscii(connection.getInputStream(), Integer.MAX_VALUE));
92550ae32218918eae80298bd1ab8e4f588bbbabdb2Jesse Wilson
92650ae32218918eae80298bd1ab8e4f588bbbabdb2Jesse Wilson        RecordedRequest request = server.takeRequest();
92750ae32218918eae80298bd1ab8e4f588bbbabdb2Jesse Wilson        assertContains(request.getHeaders(), "Accept-Encoding: custom");
92850ae32218918eae80298bd1ab8e4f588bbbabdb2Jesse Wilson    }
92950ae32218918eae80298bd1ab8e4f588bbbabdb2Jesse Wilson
930deb236fb06f2a14861e7d40dea959f181cd5cf28Jesse Wilson    /**
931deb236fb06f2a14861e7d40dea959f181cd5cf28Jesse Wilson     * Test a bug where gzip input streams weren't exhausting the input stream,
932deb236fb06f2a14861e7d40dea959f181cd5cf28Jesse Wilson     * which corrupted the request that followed.
933deb236fb06f2a14861e7d40dea959f181cd5cf28Jesse Wilson     * http://code.google.com/p/android/issues/detail?id=7059
934deb236fb06f2a14861e7d40dea959f181cd5cf28Jesse Wilson     */
935deb236fb06f2a14861e7d40dea959f181cd5cf28Jesse Wilson    private void testClientConfiguredGzipContentEncodingAndConnectionReuse(
936deb236fb06f2a14861e7d40dea959f181cd5cf28Jesse Wilson            TransferKind transferKind) throws Exception {
937deb236fb06f2a14861e7d40dea959f181cd5cf28Jesse Wilson        MockResponse responseOne = new MockResponse();
938deb236fb06f2a14861e7d40dea959f181cd5cf28Jesse Wilson        responseOne.addHeader("Content-Encoding: gzip");
939deb236fb06f2a14861e7d40dea959f181cd5cf28Jesse Wilson        transferKind.setBody(responseOne, gzip("one (gzipped)".getBytes("UTF-8")), 5);
940deb236fb06f2a14861e7d40dea959f181cd5cf28Jesse Wilson        server.enqueue(responseOne);
941deb236fb06f2a14861e7d40dea959f181cd5cf28Jesse Wilson        MockResponse responseTwo = new MockResponse();
942deb236fb06f2a14861e7d40dea959f181cd5cf28Jesse Wilson        transferKind.setBody(responseTwo, "two (identity)", 5);
943deb236fb06f2a14861e7d40dea959f181cd5cf28Jesse Wilson        server.enqueue(responseTwo);
944deb236fb06f2a14861e7d40dea959f181cd5cf28Jesse Wilson        server.play();
945deb236fb06f2a14861e7d40dea959f181cd5cf28Jesse Wilson
946deb236fb06f2a14861e7d40dea959f181cd5cf28Jesse Wilson        URLConnection connection = server.getUrl("/").openConnection();
947deb236fb06f2a14861e7d40dea959f181cd5cf28Jesse Wilson        connection.addRequestProperty("Accept-Encoding", "gzip");
948deb236fb06f2a14861e7d40dea959f181cd5cf28Jesse Wilson        InputStream gunzippedIn = new GZIPInputStream(connection.getInputStream());
949deb236fb06f2a14861e7d40dea959f181cd5cf28Jesse Wilson        assertEquals("one (gzipped)", readAscii(gunzippedIn, Integer.MAX_VALUE));
950deb236fb06f2a14861e7d40dea959f181cd5cf28Jesse Wilson        assertEquals(0, server.takeRequest().getSequenceNumber());
951deb236fb06f2a14861e7d40dea959f181cd5cf28Jesse Wilson
952deb236fb06f2a14861e7d40dea959f181cd5cf28Jesse Wilson        connection = server.getUrl("/").openConnection();
953deb236fb06f2a14861e7d40dea959f181cd5cf28Jesse Wilson        assertEquals("two (identity)", readAscii(connection.getInputStream(), Integer.MAX_VALUE));
954deb236fb06f2a14861e7d40dea959f181cd5cf28Jesse Wilson        assertEquals(1, server.takeRequest().getSequenceNumber());
955deb236fb06f2a14861e7d40dea959f181cd5cf28Jesse Wilson    }
956deb236fb06f2a14861e7d40dea959f181cd5cf28Jesse Wilson
957deb236fb06f2a14861e7d40dea959f181cd5cf28Jesse Wilson    /**
958df29c7dc69965462cd19de8910b04c8cb463e57fJesse Wilson     * Test that HEAD requests don't have a body regardless of the response
959df29c7dc69965462cd19de8910b04c8cb463e57fJesse Wilson     * headers. http://code.google.com/p/android/issues/detail?id=24672
960df29c7dc69965462cd19de8910b04c8cb463e57fJesse Wilson     */
961df29c7dc69965462cd19de8910b04c8cb463e57fJesse Wilson    public void testHeadAndContentLength() throws Exception {
962df29c7dc69965462cd19de8910b04c8cb463e57fJesse Wilson        server.enqueue(new MockResponse()
963df29c7dc69965462cd19de8910b04c8cb463e57fJesse Wilson                .clearHeaders()
964df29c7dc69965462cd19de8910b04c8cb463e57fJesse Wilson                .addHeader("Content-Length: 100"));
965df29c7dc69965462cd19de8910b04c8cb463e57fJesse Wilson        server.enqueue(new MockResponse().setBody("A"));
966df29c7dc69965462cd19de8910b04c8cb463e57fJesse Wilson        server.play();
967df29c7dc69965462cd19de8910b04c8cb463e57fJesse Wilson
968df29c7dc69965462cd19de8910b04c8cb463e57fJesse Wilson        HttpURLConnection connection1 = (HttpURLConnection) server.getUrl("/").openConnection();
969df29c7dc69965462cd19de8910b04c8cb463e57fJesse Wilson        connection1.setRequestMethod("HEAD");
970df29c7dc69965462cd19de8910b04c8cb463e57fJesse Wilson        assertEquals("100", connection1.getHeaderField("Content-Length"));
971df29c7dc69965462cd19de8910b04c8cb463e57fJesse Wilson        assertContent("", connection1);
972df29c7dc69965462cd19de8910b04c8cb463e57fJesse Wilson
973df29c7dc69965462cd19de8910b04c8cb463e57fJesse Wilson        HttpURLConnection connection2 = (HttpURLConnection) server.getUrl("/").openConnection();
974df29c7dc69965462cd19de8910b04c8cb463e57fJesse Wilson        assertEquals("A", readAscii(connection2.getInputStream(), Integer.MAX_VALUE));
975df29c7dc69965462cd19de8910b04c8cb463e57fJesse Wilson
976df29c7dc69965462cd19de8910b04c8cb463e57fJesse Wilson        assertEquals(0, server.takeRequest().getSequenceNumber());
977df29c7dc69965462cd19de8910b04c8cb463e57fJesse Wilson        assertEquals(1, server.takeRequest().getSequenceNumber());
978df29c7dc69965462cd19de8910b04c8cb463e57fJesse Wilson    }
979df29c7dc69965462cd19de8910b04c8cb463e57fJesse Wilson
980df29c7dc69965462cd19de8910b04c8cb463e57fJesse Wilson    /**
981ffd579b668428272b78f5c6c64f9c89766f37c1aJesse Wilson     * Obnoxiously test that the chunk sizes transmitted exactly equal the
982ffd579b668428272b78f5c6c64f9c89766f37c1aJesse Wilson     * requested data+chunk header size. Although setChunkedStreamingMode()
983ffd579b668428272b78f5c6c64f9c89766f37c1aJesse Wilson     * isn't specific about whether the size applies to the data or the
984ffd579b668428272b78f5c6c64f9c89766f37c1aJesse Wilson     * complete chunk, the RI interprets it as a complete chunk.
985ffd579b668428272b78f5c6c64f9c89766f37c1aJesse Wilson     */
986ffd579b668428272b78f5c6c64f9c89766f37c1aJesse Wilson    public void testSetChunkedStreamingMode() throws IOException, InterruptedException {
987ffd579b668428272b78f5c6c64f9c89766f37c1aJesse Wilson        server.enqueue(new MockResponse());
988ffd579b668428272b78f5c6c64f9c89766f37c1aJesse Wilson        server.play();
989ffd579b668428272b78f5c6c64f9c89766f37c1aJesse Wilson
990ffd579b668428272b78f5c6c64f9c89766f37c1aJesse Wilson        HttpURLConnection urlConnection = (HttpURLConnection) server.getUrl("/").openConnection();
991ffd579b668428272b78f5c6c64f9c89766f37c1aJesse Wilson        urlConnection.setChunkedStreamingMode(8);
992ffd579b668428272b78f5c6c64f9c89766f37c1aJesse Wilson        urlConnection.setDoOutput(true);
993ffd579b668428272b78f5c6c64f9c89766f37c1aJesse Wilson        OutputStream outputStream = urlConnection.getOutputStream();
994ffd579b668428272b78f5c6c64f9c89766f37c1aJesse Wilson        outputStream.write("ABCDEFGHIJKLMNOPQ".getBytes("US-ASCII"));
995ffd579b668428272b78f5c6c64f9c89766f37c1aJesse Wilson        assertEquals(200, urlConnection.getResponseCode());
996ffd579b668428272b78f5c6c64f9c89766f37c1aJesse Wilson
997ffd579b668428272b78f5c6c64f9c89766f37c1aJesse Wilson        RecordedRequest request = server.takeRequest();
998ffd579b668428272b78f5c6c64f9c89766f37c1aJesse Wilson        assertEquals("ABCDEFGHIJKLMNOPQ", new String(request.getBody(), "US-ASCII"));
999ffd579b668428272b78f5c6c64f9c89766f37c1aJesse Wilson        assertEquals(Arrays.asList(3, 3, 3, 3, 3, 2), request.getChunkSizes());
1000ffd579b668428272b78f5c6c64f9c89766f37c1aJesse Wilson    }
1001ffd579b668428272b78f5c6c64f9c89766f37c1aJesse Wilson
1002ffd579b668428272b78f5c6c64f9c89766f37c1aJesse Wilson    public void testAuthenticateWithFixedLengthStreaming() throws Exception {
1003ffd579b668428272b78f5c6c64f9c89766f37c1aJesse Wilson        testAuthenticateWithStreamingPost(StreamingMode.FIXED_LENGTH);
1004ffd579b668428272b78f5c6c64f9c89766f37c1aJesse Wilson    }
1005ffd579b668428272b78f5c6c64f9c89766f37c1aJesse Wilson
1006ffd579b668428272b78f5c6c64f9c89766f37c1aJesse Wilson    public void testAuthenticateWithChunkedStreaming() throws Exception {
1007ffd579b668428272b78f5c6c64f9c89766f37c1aJesse Wilson        testAuthenticateWithStreamingPost(StreamingMode.CHUNKED);
1008ffd579b668428272b78f5c6c64f9c89766f37c1aJesse Wilson    }
1009ffd579b668428272b78f5c6c64f9c89766f37c1aJesse Wilson
1010ffd579b668428272b78f5c6c64f9c89766f37c1aJesse Wilson    private void testAuthenticateWithStreamingPost(StreamingMode streamingMode) throws Exception {
1011ffd579b668428272b78f5c6c64f9c89766f37c1aJesse Wilson        MockResponse pleaseAuthenticate = new MockResponse()
1012ffd579b668428272b78f5c6c64f9c89766f37c1aJesse Wilson                .setResponseCode(401)
1013ffd579b668428272b78f5c6c64f9c89766f37c1aJesse Wilson                .addHeader("WWW-Authenticate: Basic realm=\"protected area\"")
1014ffd579b668428272b78f5c6c64f9c89766f37c1aJesse Wilson                .setBody("Please authenticate.");
1015ffd579b668428272b78f5c6c64f9c89766f37c1aJesse Wilson        server.enqueue(pleaseAuthenticate);
1016ffd579b668428272b78f5c6c64f9c89766f37c1aJesse Wilson        server.play();
1017ffd579b668428272b78f5c6c64f9c89766f37c1aJesse Wilson
10185757cb35ad2e58d7accb7f5d3db6f2d5e72f097dJesse Wilson        Authenticator.setDefault(new SimpleAuthenticator());
1019ffd579b668428272b78f5c6c64f9c89766f37c1aJesse Wilson        HttpURLConnection connection = (HttpURLConnection) server.getUrl("/").openConnection();
1020ffd579b668428272b78f5c6c64f9c89766f37c1aJesse Wilson        connection.setDoOutput(true);
1021ffd579b668428272b78f5c6c64f9c89766f37c1aJesse Wilson        byte[] requestBody = { 'A', 'B', 'C', 'D' };
1022ffd579b668428272b78f5c6c64f9c89766f37c1aJesse Wilson        if (streamingMode == StreamingMode.FIXED_LENGTH) {
1023ffd579b668428272b78f5c6c64f9c89766f37c1aJesse Wilson            connection.setFixedLengthStreamingMode(requestBody.length);
1024ffd579b668428272b78f5c6c64f9c89766f37c1aJesse Wilson        } else if (streamingMode == StreamingMode.CHUNKED) {
1025ffd579b668428272b78f5c6c64f9c89766f37c1aJesse Wilson            connection.setChunkedStreamingMode(0);
1026ffd579b668428272b78f5c6c64f9c89766f37c1aJesse Wilson        }
1027ffd579b668428272b78f5c6c64f9c89766f37c1aJesse Wilson        OutputStream outputStream = connection.getOutputStream();
1028ffd579b668428272b78f5c6c64f9c89766f37c1aJesse Wilson        outputStream.write(requestBody);
1029ffd579b668428272b78f5c6c64f9c89766f37c1aJesse Wilson        outputStream.close();
1030ffd579b668428272b78f5c6c64f9c89766f37c1aJesse Wilson        try {
1031ffd579b668428272b78f5c6c64f9c89766f37c1aJesse Wilson            connection.getInputStream();
1032ffd579b668428272b78f5c6c64f9c89766f37c1aJesse Wilson            fail();
1033ffd579b668428272b78f5c6c64f9c89766f37c1aJesse Wilson        } catch (HttpRetryException expected) {
1034ffd579b668428272b78f5c6c64f9c89766f37c1aJesse Wilson        }
1035ffd579b668428272b78f5c6c64f9c89766f37c1aJesse Wilson
1036ffd579b668428272b78f5c6c64f9c89766f37c1aJesse Wilson        // no authorization header for the request...
1037ffd579b668428272b78f5c6c64f9c89766f37c1aJesse Wilson        RecordedRequest request = server.takeRequest();
1038ffd579b668428272b78f5c6c64f9c89766f37c1aJesse Wilson        assertContainsNoneMatching(request.getHeaders(), "Authorization: Basic .*");
1039ffd579b668428272b78f5c6c64f9c89766f37c1aJesse Wilson        assertEquals(Arrays.toString(requestBody), Arrays.toString(request.getBody()));
1040ffd579b668428272b78f5c6c64f9c89766f37c1aJesse Wilson    }
1041ffd579b668428272b78f5c6c64f9c89766f37c1aJesse Wilson
1042ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson    public void testSetValidRequestMethod() throws Exception {
1043ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson        server.play();
1044ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson        assertValidRequestMethod("GET");
1045ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson        assertValidRequestMethod("DELETE");
1046ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson        assertValidRequestMethod("HEAD");
1047ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson        assertValidRequestMethod("OPTIONS");
1048ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson        assertValidRequestMethod("POST");
1049ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson        assertValidRequestMethod("PUT");
1050ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson        assertValidRequestMethod("TRACE");
1051ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson    }
1052ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson
1053ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson    private void assertValidRequestMethod(String requestMethod) throws Exception {
1054ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson        HttpURLConnection connection = (HttpURLConnection) server.getUrl("/").openConnection();
1055ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson        connection.setRequestMethod(requestMethod);
1056ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson        assertEquals(requestMethod, connection.getRequestMethod());
1057ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson    }
1058ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson
1059ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson    public void testSetInvalidRequestMethodLowercase() throws Exception {
1060ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson        server.play();
1061ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson        assertInvalidRequestMethod("get");
1062ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson    }
1063ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson
1064ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson    public void testSetInvalidRequestMethodConnect() throws Exception {
1065ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson        server.play();
1066ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson        assertInvalidRequestMethod("CONNECT");
1067ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson    }
1068ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson
1069ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson    private void assertInvalidRequestMethod(String requestMethod) throws Exception {
1070ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson        HttpURLConnection connection = (HttpURLConnection) server.getUrl("/").openConnection();
1071ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson        try {
1072ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson            connection.setRequestMethod(requestMethod);
1073ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson            fail();
1074ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson        } catch (ProtocolException expected) {
1075ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson        }
1076ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson    }
1077ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson
1078ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson    public void testCannotSetNegativeFixedLengthStreamingMode() throws Exception {
1079ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson        server.play();
1080ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson        HttpURLConnection connection = (HttpURLConnection) server.getUrl("/").openConnection();
1081ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson        try {
1082ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson            connection.setFixedLengthStreamingMode(-2);
1083ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson            fail();
1084ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson        } catch (IllegalArgumentException expected) {
1085ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson        }
1086ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson    }
1087ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson
1088ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson    public void testCanSetNegativeChunkedStreamingMode() throws Exception {
1089ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson        server.play();
1090ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson        HttpURLConnection connection = (HttpURLConnection) server.getUrl("/").openConnection();
1091ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson        connection.setChunkedStreamingMode(-2);
1092ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson    }
1093ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson
1094ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson    public void testCannotSetFixedLengthStreamingModeAfterConnect() throws Exception {
1095ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson        server.enqueue(new MockResponse().setBody("A"));
1096ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson        server.play();
1097ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson        HttpURLConnection connection = (HttpURLConnection) server.getUrl("/").openConnection();
1098ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson        assertEquals("A", readAscii(connection.getInputStream(), Integer.MAX_VALUE));
1099ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson        try {
1100ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson            connection.setFixedLengthStreamingMode(1);
1101ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson            fail();
1102ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson        } catch (IllegalStateException expected) {
1103ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson        }
1104ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson    }
1105ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson
1106ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson    public void testCannotSetChunkedStreamingModeAfterConnect() throws Exception {
1107ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson        server.enqueue(new MockResponse().setBody("A"));
1108ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson        server.play();
1109ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson        HttpURLConnection connection = (HttpURLConnection) server.getUrl("/").openConnection();
1110ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson        assertEquals("A", readAscii(connection.getInputStream(), Integer.MAX_VALUE));
1111ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson        try {
1112ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson            connection.setChunkedStreamingMode(1);
1113ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson            fail();
1114ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson        } catch (IllegalStateException expected) {
1115ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson        }
1116ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson    }
1117ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson
1118ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson    public void testCannotSetFixedLengthStreamingModeAfterChunkedStreamingMode() throws Exception {
1119ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson        server.play();
1120ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson        HttpURLConnection connection = (HttpURLConnection) server.getUrl("/").openConnection();
1121ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson        connection.setChunkedStreamingMode(1);
1122ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson        try {
1123ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson            connection.setFixedLengthStreamingMode(1);
1124ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson            fail();
1125ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson        } catch (IllegalStateException expected) {
1126ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson        }
1127ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson    }
1128ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson
1129ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson    public void testCannotSetChunkedStreamingModeAfterFixedLengthStreamingMode() throws Exception {
1130ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson        server.play();
1131ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson        HttpURLConnection connection = (HttpURLConnection) server.getUrl("/").openConnection();
1132ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson        connection.setFixedLengthStreamingMode(1);
1133ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson        try {
1134ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson            connection.setChunkedStreamingMode(1);
1135ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson            fail();
1136ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson        } catch (IllegalStateException expected) {
1137ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson        }
1138ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson    }
1139ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson
114035eef71e8ce721c4199c525890ecc1a263054596Jesse Wilson    public void testSecureFixedLengthStreaming() throws Exception {
114135eef71e8ce721c4199c525890ecc1a263054596Jesse Wilson        testSecureStreamingPost(StreamingMode.FIXED_LENGTH);
114235eef71e8ce721c4199c525890ecc1a263054596Jesse Wilson    }
114335eef71e8ce721c4199c525890ecc1a263054596Jesse Wilson
114435eef71e8ce721c4199c525890ecc1a263054596Jesse Wilson    public void testSecureChunkedStreaming() throws Exception {
114535eef71e8ce721c4199c525890ecc1a263054596Jesse Wilson        testSecureStreamingPost(StreamingMode.CHUNKED);
114635eef71e8ce721c4199c525890ecc1a263054596Jesse Wilson    }
114735eef71e8ce721c4199c525890ecc1a263054596Jesse Wilson
114835eef71e8ce721c4199c525890ecc1a263054596Jesse Wilson    /**
114935eef71e8ce721c4199c525890ecc1a263054596Jesse Wilson     * Users have reported problems using HTTPS with streaming request bodies.
115035eef71e8ce721c4199c525890ecc1a263054596Jesse Wilson     * http://code.google.com/p/android/issues/detail?id=12860
115135eef71e8ce721c4199c525890ecc1a263054596Jesse Wilson     */
115235eef71e8ce721c4199c525890ecc1a263054596Jesse Wilson    private void testSecureStreamingPost(StreamingMode streamingMode) throws Exception {
115335eef71e8ce721c4199c525890ecc1a263054596Jesse Wilson        TestSSLContext testSSLContext = TestSSLContext.create();
115435eef71e8ce721c4199c525890ecc1a263054596Jesse Wilson        server.useHttps(testSSLContext.serverContext.getSocketFactory(), false);
115535eef71e8ce721c4199c525890ecc1a263054596Jesse Wilson        server.enqueue(new MockResponse().setBody("Success!"));
115635eef71e8ce721c4199c525890ecc1a263054596Jesse Wilson        server.play();
115735eef71e8ce721c4199c525890ecc1a263054596Jesse Wilson
115835eef71e8ce721c4199c525890ecc1a263054596Jesse Wilson        HttpsURLConnection connection = (HttpsURLConnection) server.getUrl("/").openConnection();
115935eef71e8ce721c4199c525890ecc1a263054596Jesse Wilson        connection.setSSLSocketFactory(testSSLContext.clientContext.getSocketFactory());
116035eef71e8ce721c4199c525890ecc1a263054596Jesse Wilson        connection.setDoOutput(true);
116135eef71e8ce721c4199c525890ecc1a263054596Jesse Wilson        byte[] requestBody = { 'A', 'B', 'C', 'D' };
116235eef71e8ce721c4199c525890ecc1a263054596Jesse Wilson        if (streamingMode == StreamingMode.FIXED_LENGTH) {
116335eef71e8ce721c4199c525890ecc1a263054596Jesse Wilson            connection.setFixedLengthStreamingMode(requestBody.length);
116435eef71e8ce721c4199c525890ecc1a263054596Jesse Wilson        } else if (streamingMode == StreamingMode.CHUNKED) {
116535eef71e8ce721c4199c525890ecc1a263054596Jesse Wilson            connection.setChunkedStreamingMode(0);
116635eef71e8ce721c4199c525890ecc1a263054596Jesse Wilson        }
116735eef71e8ce721c4199c525890ecc1a263054596Jesse Wilson        OutputStream outputStream = connection.getOutputStream();
116835eef71e8ce721c4199c525890ecc1a263054596Jesse Wilson        outputStream.write(requestBody);
116935eef71e8ce721c4199c525890ecc1a263054596Jesse Wilson        outputStream.close();
117035eef71e8ce721c4199c525890ecc1a263054596Jesse Wilson        assertEquals("Success!", readAscii(connection.getInputStream(), Integer.MAX_VALUE));
117135eef71e8ce721c4199c525890ecc1a263054596Jesse Wilson
117235eef71e8ce721c4199c525890ecc1a263054596Jesse Wilson        RecordedRequest request = server.takeRequest();
117335eef71e8ce721c4199c525890ecc1a263054596Jesse Wilson        assertEquals("POST / HTTP/1.1", request.getRequestLine());
117435eef71e8ce721c4199c525890ecc1a263054596Jesse Wilson        if (streamingMode == StreamingMode.FIXED_LENGTH) {
117535eef71e8ce721c4199c525890ecc1a263054596Jesse Wilson            assertEquals(Collections.<Integer>emptyList(), request.getChunkSizes());
117635eef71e8ce721c4199c525890ecc1a263054596Jesse Wilson        } else if (streamingMode == StreamingMode.CHUNKED) {
117735eef71e8ce721c4199c525890ecc1a263054596Jesse Wilson            assertEquals(Arrays.asList(4), request.getChunkSizes());
117835eef71e8ce721c4199c525890ecc1a263054596Jesse Wilson        }
117935eef71e8ce721c4199c525890ecc1a263054596Jesse Wilson        assertEquals(Arrays.toString(requestBody), Arrays.toString(request.getBody()));
118035eef71e8ce721c4199c525890ecc1a263054596Jesse Wilson    }
118135eef71e8ce721c4199c525890ecc1a263054596Jesse Wilson
1182ffd579b668428272b78f5c6c64f9c89766f37c1aJesse Wilson    enum StreamingMode {
1183ffd579b668428272b78f5c6c64f9c89766f37c1aJesse Wilson        FIXED_LENGTH, CHUNKED
1184ffd579b668428272b78f5c6c64f9c89766f37c1aJesse Wilson    }
1185ffd579b668428272b78f5c6c64f9c89766f37c1aJesse Wilson
1186ffd579b668428272b78f5c6c64f9c89766f37c1aJesse Wilson    public void testAuthenticateWithPost() throws Exception {
1187ffd579b668428272b78f5c6c64f9c89766f37c1aJesse Wilson        MockResponse pleaseAuthenticate = new MockResponse()
1188ffd579b668428272b78f5c6c64f9c89766f37c1aJesse Wilson                .setResponseCode(401)
1189ffd579b668428272b78f5c6c64f9c89766f37c1aJesse Wilson                .addHeader("WWW-Authenticate: Basic realm=\"protected area\"")
1190ffd579b668428272b78f5c6c64f9c89766f37c1aJesse Wilson                .setBody("Please authenticate.");
1191ffd579b668428272b78f5c6c64f9c89766f37c1aJesse Wilson        // fail auth three times...
1192ffd579b668428272b78f5c6c64f9c89766f37c1aJesse Wilson        server.enqueue(pleaseAuthenticate);
1193ffd579b668428272b78f5c6c64f9c89766f37c1aJesse Wilson        server.enqueue(pleaseAuthenticate);
1194ffd579b668428272b78f5c6c64f9c89766f37c1aJesse Wilson        server.enqueue(pleaseAuthenticate);
1195ffd579b668428272b78f5c6c64f9c89766f37c1aJesse Wilson        // ...then succeed the fourth time
1196ffd579b668428272b78f5c6c64f9c89766f37c1aJesse Wilson        server.enqueue(new MockResponse().setBody("Successful auth!"));
1197ffd579b668428272b78f5c6c64f9c89766f37c1aJesse Wilson        server.play();
1198ffd579b668428272b78f5c6c64f9c89766f37c1aJesse Wilson
11995757cb35ad2e58d7accb7f5d3db6f2d5e72f097dJesse Wilson        Authenticator.setDefault(new SimpleAuthenticator());
1200ffd579b668428272b78f5c6c64f9c89766f37c1aJesse Wilson        HttpURLConnection connection = (HttpURLConnection) server.getUrl("/").openConnection();
1201ffd579b668428272b78f5c6c64f9c89766f37c1aJesse Wilson        connection.setDoOutput(true);
1202ffd579b668428272b78f5c6c64f9c89766f37c1aJesse Wilson        byte[] requestBody = { 'A', 'B', 'C', 'D' };
1203ffd579b668428272b78f5c6c64f9c89766f37c1aJesse Wilson        OutputStream outputStream = connection.getOutputStream();
1204ffd579b668428272b78f5c6c64f9c89766f37c1aJesse Wilson        outputStream.write(requestBody);
1205ffd579b668428272b78f5c6c64f9c89766f37c1aJesse Wilson        outputStream.close();
1206ffd579b668428272b78f5c6c64f9c89766f37c1aJesse Wilson        assertEquals("Successful auth!", readAscii(connection.getInputStream(), Integer.MAX_VALUE));
1207ffd579b668428272b78f5c6c64f9c89766f37c1aJesse Wilson
1208ffd579b668428272b78f5c6c64f9c89766f37c1aJesse Wilson        // no authorization header for the first request...
1209ffd579b668428272b78f5c6c64f9c89766f37c1aJesse Wilson        RecordedRequest request = server.takeRequest();
12105757cb35ad2e58d7accb7f5d3db6f2d5e72f097dJesse Wilson        assertContainsNoneMatching(request.getHeaders(), "Authorization: .*");
1211ffd579b668428272b78f5c6c64f9c89766f37c1aJesse Wilson
1212da289bcd0a9e207cc03c752f7c21c9004056e179Jesse Wilson        // ...but the three requests that follow include an authorization header
1213ffd579b668428272b78f5c6c64f9c89766f37c1aJesse Wilson        for (int i = 0; i < 3; i++) {
1214ffd579b668428272b78f5c6c64f9c89766f37c1aJesse Wilson            request = server.takeRequest();
1215ffd579b668428272b78f5c6c64f9c89766f37c1aJesse Wilson            assertEquals("POST / HTTP/1.1", request.getRequestLine());
12165757cb35ad2e58d7accb7f5d3db6f2d5e72f097dJesse Wilson            assertContains(request.getHeaders(), "Authorization: Basic "
12175757cb35ad2e58d7accb7f5d3db6f2d5e72f097dJesse Wilson                    + SimpleAuthenticator.BASE_64_CREDENTIALS);
1218ffd579b668428272b78f5c6c64f9c89766f37c1aJesse Wilson            assertEquals(Arrays.toString(requestBody), Arrays.toString(request.getBody()));
1219ffd579b668428272b78f5c6c64f9c89766f37c1aJesse Wilson        }
1220ffd579b668428272b78f5c6c64f9c89766f37c1aJesse Wilson    }
1221ffd579b668428272b78f5c6c64f9c89766f37c1aJesse Wilson
1222ffd579b668428272b78f5c6c64f9c89766f37c1aJesse Wilson    public void testAuthenticateWithGet() throws Exception {
1223ffd579b668428272b78f5c6c64f9c89766f37c1aJesse Wilson        MockResponse pleaseAuthenticate = new MockResponse()
1224ffd579b668428272b78f5c6c64f9c89766f37c1aJesse Wilson                .setResponseCode(401)
1225ffd579b668428272b78f5c6c64f9c89766f37c1aJesse Wilson                .addHeader("WWW-Authenticate: Basic realm=\"protected area\"")
1226ffd579b668428272b78f5c6c64f9c89766f37c1aJesse Wilson                .setBody("Please authenticate.");
1227ffd579b668428272b78f5c6c64f9c89766f37c1aJesse Wilson        // fail auth three times...
1228ffd579b668428272b78f5c6c64f9c89766f37c1aJesse Wilson        server.enqueue(pleaseAuthenticate);
1229ffd579b668428272b78f5c6c64f9c89766f37c1aJesse Wilson        server.enqueue(pleaseAuthenticate);
1230ffd579b668428272b78f5c6c64f9c89766f37c1aJesse Wilson        server.enqueue(pleaseAuthenticate);
1231ffd579b668428272b78f5c6c64f9c89766f37c1aJesse Wilson        // ...then succeed the fourth time
1232ffd579b668428272b78f5c6c64f9c89766f37c1aJesse Wilson        server.enqueue(new MockResponse().setBody("Successful auth!"));
1233ffd579b668428272b78f5c6c64f9c89766f37c1aJesse Wilson        server.play();
1234ffd579b668428272b78f5c6c64f9c89766f37c1aJesse Wilson
12355757cb35ad2e58d7accb7f5d3db6f2d5e72f097dJesse Wilson        SimpleAuthenticator authenticator = new SimpleAuthenticator();
12365757cb35ad2e58d7accb7f5d3db6f2d5e72f097dJesse Wilson        Authenticator.setDefault(authenticator);
1237ffd579b668428272b78f5c6c64f9c89766f37c1aJesse Wilson        HttpURLConnection connection = (HttpURLConnection) server.getUrl("/").openConnection();
1238ffd579b668428272b78f5c6c64f9c89766f37c1aJesse Wilson        assertEquals("Successful auth!", readAscii(connection.getInputStream(), Integer.MAX_VALUE));
12395757cb35ad2e58d7accb7f5d3db6f2d5e72f097dJesse Wilson        assertEquals(Authenticator.RequestorType.SERVER, authenticator.requestorType);
12405757cb35ad2e58d7accb7f5d3db6f2d5e72f097dJesse Wilson        assertEquals(server.getPort(), authenticator.requestingPort);
12415757cb35ad2e58d7accb7f5d3db6f2d5e72f097dJesse Wilson        assertEquals(InetAddress.getByName(server.getHostName()), authenticator.requestingSite);
12425757cb35ad2e58d7accb7f5d3db6f2d5e72f097dJesse Wilson        assertEquals("protected area", authenticator.requestingPrompt);
12435757cb35ad2e58d7accb7f5d3db6f2d5e72f097dJesse Wilson        assertEquals("http", authenticator.requestingProtocol);
12445757cb35ad2e58d7accb7f5d3db6f2d5e72f097dJesse Wilson        assertEquals("Basic", authenticator.requestingScheme);
1245ffd579b668428272b78f5c6c64f9c89766f37c1aJesse Wilson
1246ffd579b668428272b78f5c6c64f9c89766f37c1aJesse Wilson        // no authorization header for the first request...
1247ffd579b668428272b78f5c6c64f9c89766f37c1aJesse Wilson        RecordedRequest request = server.takeRequest();
12485757cb35ad2e58d7accb7f5d3db6f2d5e72f097dJesse Wilson        assertContainsNoneMatching(request.getHeaders(), "Authorization: .*");
1249ffd579b668428272b78f5c6c64f9c89766f37c1aJesse Wilson
1250ffd579b668428272b78f5c6c64f9c89766f37c1aJesse Wilson        // ...but the three requests that follow requests include an authorization header
1251ffd579b668428272b78f5c6c64f9c89766f37c1aJesse Wilson        for (int i = 0; i < 3; i++) {
1252ffd579b668428272b78f5c6c64f9c89766f37c1aJesse Wilson            request = server.takeRequest();
1253ffd579b668428272b78f5c6c64f9c89766f37c1aJesse Wilson            assertEquals("GET / HTTP/1.1", request.getRequestLine());
12545757cb35ad2e58d7accb7f5d3db6f2d5e72f097dJesse Wilson            assertContains(request.getHeaders(), "Authorization: Basic "
12555757cb35ad2e58d7accb7f5d3db6f2d5e72f097dJesse Wilson                    + SimpleAuthenticator.BASE_64_CREDENTIALS);
1256ffd579b668428272b78f5c6c64f9c89766f37c1aJesse Wilson        }
1257ffd579b668428272b78f5c6c64f9c89766f37c1aJesse Wilson    }
1258ffd579b668428272b78f5c6c64f9c89766f37c1aJesse Wilson
12595757cb35ad2e58d7accb7f5d3db6f2d5e72f097dJesse Wilson    // http://code.google.com/p/android/issues/detail?id=19081
12605757cb35ad2e58d7accb7f5d3db6f2d5e72f097dJesse Wilson    public void testAuthenticateWithCommaSeparatedAuthenticationMethods() throws Exception {
12615757cb35ad2e58d7accb7f5d3db6f2d5e72f097dJesse Wilson        server.enqueue(new MockResponse()
12625757cb35ad2e58d7accb7f5d3db6f2d5e72f097dJesse Wilson                .setResponseCode(401)
12635757cb35ad2e58d7accb7f5d3db6f2d5e72f097dJesse Wilson                .addHeader("WWW-Authenticate: Scheme1 realm=\"a\", Scheme2 realm=\"b\", "
12645757cb35ad2e58d7accb7f5d3db6f2d5e72f097dJesse Wilson                        + "Scheme3 realm=\"c\"")
12655757cb35ad2e58d7accb7f5d3db6f2d5e72f097dJesse Wilson                .setBody("Please authenticate."));
12665757cb35ad2e58d7accb7f5d3db6f2d5e72f097dJesse Wilson        server.enqueue(new MockResponse().setBody("Successful auth!"));
12675757cb35ad2e58d7accb7f5d3db6f2d5e72f097dJesse Wilson        server.play();
12685757cb35ad2e58d7accb7f5d3db6f2d5e72f097dJesse Wilson
12695757cb35ad2e58d7accb7f5d3db6f2d5e72f097dJesse Wilson        SimpleAuthenticator authenticator = new SimpleAuthenticator();
12705757cb35ad2e58d7accb7f5d3db6f2d5e72f097dJesse Wilson        authenticator.expectedPrompt = "b";
12715757cb35ad2e58d7accb7f5d3db6f2d5e72f097dJesse Wilson        Authenticator.setDefault(authenticator);
12725757cb35ad2e58d7accb7f5d3db6f2d5e72f097dJesse Wilson        HttpURLConnection connection = (HttpURLConnection) server.getUrl("/").openConnection();
12735757cb35ad2e58d7accb7f5d3db6f2d5e72f097dJesse Wilson        assertEquals("Successful auth!", readAscii(connection.getInputStream(), Integer.MAX_VALUE));
12745757cb35ad2e58d7accb7f5d3db6f2d5e72f097dJesse Wilson
12755757cb35ad2e58d7accb7f5d3db6f2d5e72f097dJesse Wilson        assertContainsNoneMatching(server.takeRequest().getHeaders(), "Authorization: .*");
12765757cb35ad2e58d7accb7f5d3db6f2d5e72f097dJesse Wilson        assertContains(server.takeRequest().getHeaders(),
12775757cb35ad2e58d7accb7f5d3db6f2d5e72f097dJesse Wilson                "Authorization: Scheme2 " + SimpleAuthenticator.BASE_64_CREDENTIALS);
12785757cb35ad2e58d7accb7f5d3db6f2d5e72f097dJesse Wilson        assertEquals("Scheme2", authenticator.requestingScheme);
12795757cb35ad2e58d7accb7f5d3db6f2d5e72f097dJesse Wilson    }
12805757cb35ad2e58d7accb7f5d3db6f2d5e72f097dJesse Wilson
12815757cb35ad2e58d7accb7f5d3db6f2d5e72f097dJesse Wilson    public void testAuthenticateWithMultipleAuthenticationHeaders() throws Exception {
12825757cb35ad2e58d7accb7f5d3db6f2d5e72f097dJesse Wilson        server.enqueue(new MockResponse()
12835757cb35ad2e58d7accb7f5d3db6f2d5e72f097dJesse Wilson                .setResponseCode(401)
12845757cb35ad2e58d7accb7f5d3db6f2d5e72f097dJesse Wilson                .addHeader("WWW-Authenticate: Scheme1 realm=\"a\"")
12855757cb35ad2e58d7accb7f5d3db6f2d5e72f097dJesse Wilson                .addHeader("WWW-Authenticate: Scheme2 realm=\"b\"")
12865757cb35ad2e58d7accb7f5d3db6f2d5e72f097dJesse Wilson                .addHeader("WWW-Authenticate: Scheme3 realm=\"c\"")
12875757cb35ad2e58d7accb7f5d3db6f2d5e72f097dJesse Wilson                .setBody("Please authenticate."));
12885757cb35ad2e58d7accb7f5d3db6f2d5e72f097dJesse Wilson        server.enqueue(new MockResponse().setBody("Successful auth!"));
12895757cb35ad2e58d7accb7f5d3db6f2d5e72f097dJesse Wilson        server.play();
12905757cb35ad2e58d7accb7f5d3db6f2d5e72f097dJesse Wilson
12915757cb35ad2e58d7accb7f5d3db6f2d5e72f097dJesse Wilson        SimpleAuthenticator authenticator = new SimpleAuthenticator();
12925757cb35ad2e58d7accb7f5d3db6f2d5e72f097dJesse Wilson        authenticator.expectedPrompt = "b";
12935757cb35ad2e58d7accb7f5d3db6f2d5e72f097dJesse Wilson        Authenticator.setDefault(authenticator);
12945757cb35ad2e58d7accb7f5d3db6f2d5e72f097dJesse Wilson        HttpURLConnection connection = (HttpURLConnection) server.getUrl("/").openConnection();
12955757cb35ad2e58d7accb7f5d3db6f2d5e72f097dJesse Wilson        assertEquals("Successful auth!", readAscii(connection.getInputStream(), Integer.MAX_VALUE));
12965757cb35ad2e58d7accb7f5d3db6f2d5e72f097dJesse Wilson
12975757cb35ad2e58d7accb7f5d3db6f2d5e72f097dJesse Wilson        assertContainsNoneMatching(server.takeRequest().getHeaders(), "Authorization: .*");
12985757cb35ad2e58d7accb7f5d3db6f2d5e72f097dJesse Wilson        assertContains(server.takeRequest().getHeaders(),
12995757cb35ad2e58d7accb7f5d3db6f2d5e72f097dJesse Wilson                "Authorization: Scheme2 " + SimpleAuthenticator.BASE_64_CREDENTIALS);
13005757cb35ad2e58d7accb7f5d3db6f2d5e72f097dJesse Wilson        assertEquals("Scheme2", authenticator.requestingScheme);
13015757cb35ad2e58d7accb7f5d3db6f2d5e72f097dJesse Wilson    }
13025757cb35ad2e58d7accb7f5d3db6f2d5e72f097dJesse Wilson
1303c0372d90016d241ac979faa6fa1731f30b6f2a03Jesse Wilson    public void testRedirectedWithChunkedEncoding() throws Exception {
1304c0372d90016d241ac979faa6fa1731f30b6f2a03Jesse Wilson        testRedirected(TransferKind.CHUNKED, true);
1305c0372d90016d241ac979faa6fa1731f30b6f2a03Jesse Wilson    }
1306c0372d90016d241ac979faa6fa1731f30b6f2a03Jesse Wilson
1307c0372d90016d241ac979faa6fa1731f30b6f2a03Jesse Wilson    public void testRedirectedWithContentLengthHeader() throws Exception {
1308c0372d90016d241ac979faa6fa1731f30b6f2a03Jesse Wilson        testRedirected(TransferKind.FIXED_LENGTH, true);
1309c0372d90016d241ac979faa6fa1731f30b6f2a03Jesse Wilson    }
1310c0372d90016d241ac979faa6fa1731f30b6f2a03Jesse Wilson
1311c0372d90016d241ac979faa6fa1731f30b6f2a03Jesse Wilson    public void testRedirectedWithNoLengthHeaders() throws Exception {
1312c0372d90016d241ac979faa6fa1731f30b6f2a03Jesse Wilson        testRedirected(TransferKind.END_OF_STREAM, false);
1313c0372d90016d241ac979faa6fa1731f30b6f2a03Jesse Wilson    }
1314c0372d90016d241ac979faa6fa1731f30b6f2a03Jesse Wilson
1315c0372d90016d241ac979faa6fa1731f30b6f2a03Jesse Wilson    private void testRedirected(TransferKind transferKind, boolean reuse) throws Exception {
1316c0372d90016d241ac979faa6fa1731f30b6f2a03Jesse Wilson        MockResponse response = new MockResponse()
1317c0372d90016d241ac979faa6fa1731f30b6f2a03Jesse Wilson                .setResponseCode(HttpURLConnection.HTTP_MOVED_TEMP)
1318c0372d90016d241ac979faa6fa1731f30b6f2a03Jesse Wilson                .addHeader("Location: /foo");
1319c0372d90016d241ac979faa6fa1731f30b6f2a03Jesse Wilson        transferKind.setBody(response, "This page has moved!", 10);
1320c0372d90016d241ac979faa6fa1731f30b6f2a03Jesse Wilson        server.enqueue(response);
1321c0372d90016d241ac979faa6fa1731f30b6f2a03Jesse Wilson        server.enqueue(new MockResponse().setBody("This is the new location!"));
1322c0372d90016d241ac979faa6fa1731f30b6f2a03Jesse Wilson        server.play();
1323c0372d90016d241ac979faa6fa1731f30b6f2a03Jesse Wilson
1324c0372d90016d241ac979faa6fa1731f30b6f2a03Jesse Wilson        URLConnection connection = server.getUrl("/").openConnection();
1325c0372d90016d241ac979faa6fa1731f30b6f2a03Jesse Wilson        assertEquals("This is the new location!",
1326c0372d90016d241ac979faa6fa1731f30b6f2a03Jesse Wilson                readAscii(connection.getInputStream(), Integer.MAX_VALUE));
1327c0372d90016d241ac979faa6fa1731f30b6f2a03Jesse Wilson
1328c0372d90016d241ac979faa6fa1731f30b6f2a03Jesse Wilson        RecordedRequest first = server.takeRequest();
1329c0372d90016d241ac979faa6fa1731f30b6f2a03Jesse Wilson        assertEquals("GET / HTTP/1.1", first.getRequestLine());
1330c0372d90016d241ac979faa6fa1731f30b6f2a03Jesse Wilson        RecordedRequest retry = server.takeRequest();
1331c0372d90016d241ac979faa6fa1731f30b6f2a03Jesse Wilson        assertEquals("GET /foo HTTP/1.1", retry.getRequestLine());
1332c0372d90016d241ac979faa6fa1731f30b6f2a03Jesse Wilson        if (reuse) {
1333c0372d90016d241ac979faa6fa1731f30b6f2a03Jesse Wilson            assertEquals("Expected connection reuse", 1, retry.getSequenceNumber());
1334c0372d90016d241ac979faa6fa1731f30b6f2a03Jesse Wilson        }
1335c0372d90016d241ac979faa6fa1731f30b6f2a03Jesse Wilson    }
1336c0372d90016d241ac979faa6fa1731f30b6f2a03Jesse Wilson
1337c0372d90016d241ac979faa6fa1731f30b6f2a03Jesse Wilson    public void testRedirectedOnHttps() throws IOException, InterruptedException {
1338c0372d90016d241ac979faa6fa1731f30b6f2a03Jesse Wilson        TestSSLContext testSSLContext = TestSSLContext.create();
1339059dbc04218144f985b20a228bbe98139d400d0cBrian Carlstrom        server.useHttps(testSSLContext.serverContext.getSocketFactory(), false);
1340c0372d90016d241ac979faa6fa1731f30b6f2a03Jesse Wilson        server.enqueue(new MockResponse()
1341c0372d90016d241ac979faa6fa1731f30b6f2a03Jesse Wilson                .setResponseCode(HttpURLConnection.HTTP_MOVED_TEMP)
1342c0372d90016d241ac979faa6fa1731f30b6f2a03Jesse Wilson                .addHeader("Location: /foo")
1343c0372d90016d241ac979faa6fa1731f30b6f2a03Jesse Wilson                .setBody("This page has moved!"));
1344c0372d90016d241ac979faa6fa1731f30b6f2a03Jesse Wilson        server.enqueue(new MockResponse().setBody("This is the new location!"));
1345c0372d90016d241ac979faa6fa1731f30b6f2a03Jesse Wilson        server.play();
1346c0372d90016d241ac979faa6fa1731f30b6f2a03Jesse Wilson
1347c0372d90016d241ac979faa6fa1731f30b6f2a03Jesse Wilson        HttpsURLConnection connection = (HttpsURLConnection) server.getUrl("/").openConnection();
1348059dbc04218144f985b20a228bbe98139d400d0cBrian Carlstrom        connection.setSSLSocketFactory(testSSLContext.clientContext.getSocketFactory());
1349c0372d90016d241ac979faa6fa1731f30b6f2a03Jesse Wilson        assertEquals("This is the new location!",
1350c0372d90016d241ac979faa6fa1731f30b6f2a03Jesse Wilson                readAscii(connection.getInputStream(), Integer.MAX_VALUE));
1351c0372d90016d241ac979faa6fa1731f30b6f2a03Jesse Wilson
1352c0372d90016d241ac979faa6fa1731f30b6f2a03Jesse Wilson        RecordedRequest first = server.takeRequest();
1353c0372d90016d241ac979faa6fa1731f30b6f2a03Jesse Wilson        assertEquals("GET / HTTP/1.1", first.getRequestLine());
1354c0372d90016d241ac979faa6fa1731f30b6f2a03Jesse Wilson        RecordedRequest retry = server.takeRequest();
1355c0372d90016d241ac979faa6fa1731f30b6f2a03Jesse Wilson        assertEquals("GET /foo HTTP/1.1", retry.getRequestLine());
1356c0372d90016d241ac979faa6fa1731f30b6f2a03Jesse Wilson        assertEquals("Expected connection reuse", 1, retry.getSequenceNumber());
1357c0372d90016d241ac979faa6fa1731f30b6f2a03Jesse Wilson    }
1358c0372d90016d241ac979faa6fa1731f30b6f2a03Jesse Wilson
1359c0372d90016d241ac979faa6fa1731f30b6f2a03Jesse Wilson    public void testNotRedirectedFromHttpsToHttp() throws IOException, InterruptedException {
1360c0372d90016d241ac979faa6fa1731f30b6f2a03Jesse Wilson        TestSSLContext testSSLContext = TestSSLContext.create();
1361059dbc04218144f985b20a228bbe98139d400d0cBrian Carlstrom        server.useHttps(testSSLContext.serverContext.getSocketFactory(), false);
1362c0372d90016d241ac979faa6fa1731f30b6f2a03Jesse Wilson        server.enqueue(new MockResponse()
1363c0372d90016d241ac979faa6fa1731f30b6f2a03Jesse Wilson                .setResponseCode(HttpURLConnection.HTTP_MOVED_TEMP)
1364c0372d90016d241ac979faa6fa1731f30b6f2a03Jesse Wilson                .addHeader("Location: http://anyhost/foo")
1365c0372d90016d241ac979faa6fa1731f30b6f2a03Jesse Wilson                .setBody("This page has moved!"));
1366c0372d90016d241ac979faa6fa1731f30b6f2a03Jesse Wilson        server.play();
1367c0372d90016d241ac979faa6fa1731f30b6f2a03Jesse Wilson
1368c0372d90016d241ac979faa6fa1731f30b6f2a03Jesse Wilson        HttpsURLConnection connection = (HttpsURLConnection) server.getUrl("/").openConnection();
1369059dbc04218144f985b20a228bbe98139d400d0cBrian Carlstrom        connection.setSSLSocketFactory(testSSLContext.clientContext.getSocketFactory());
1370c0372d90016d241ac979faa6fa1731f30b6f2a03Jesse Wilson        assertEquals("This page has moved!",
1371c0372d90016d241ac979faa6fa1731f30b6f2a03Jesse Wilson                readAscii(connection.getInputStream(), Integer.MAX_VALUE));
1372c0372d90016d241ac979faa6fa1731f30b6f2a03Jesse Wilson    }
1373c0372d90016d241ac979faa6fa1731f30b6f2a03Jesse Wilson
1374c0372d90016d241ac979faa6fa1731f30b6f2a03Jesse Wilson    public void testNotRedirectedFromHttpToHttps() throws IOException, InterruptedException {
1375c0372d90016d241ac979faa6fa1731f30b6f2a03Jesse Wilson        server.enqueue(new MockResponse()
1376c0372d90016d241ac979faa6fa1731f30b6f2a03Jesse Wilson                .setResponseCode(HttpURLConnection.HTTP_MOVED_TEMP)
1377c0372d90016d241ac979faa6fa1731f30b6f2a03Jesse Wilson                .addHeader("Location: https://anyhost/foo")
1378c0372d90016d241ac979faa6fa1731f30b6f2a03Jesse Wilson                .setBody("This page has moved!"));
1379c0372d90016d241ac979faa6fa1731f30b6f2a03Jesse Wilson        server.play();
1380c0372d90016d241ac979faa6fa1731f30b6f2a03Jesse Wilson
1381c0372d90016d241ac979faa6fa1731f30b6f2a03Jesse Wilson        HttpURLConnection connection = (HttpURLConnection) server.getUrl("/").openConnection();
1382c0372d90016d241ac979faa6fa1731f30b6f2a03Jesse Wilson        assertEquals("This page has moved!",
1383c0372d90016d241ac979faa6fa1731f30b6f2a03Jesse Wilson                readAscii(connection.getInputStream(), Integer.MAX_VALUE));
1384c0372d90016d241ac979faa6fa1731f30b6f2a03Jesse Wilson    }
1385c0372d90016d241ac979faa6fa1731f30b6f2a03Jesse Wilson
1386c0372d90016d241ac979faa6fa1731f30b6f2a03Jesse Wilson    public void testRedirectToAnotherOriginServer() throws Exception {
1387c0372d90016d241ac979faa6fa1731f30b6f2a03Jesse Wilson        MockWebServer server2 = new MockWebServer();
1388c0372d90016d241ac979faa6fa1731f30b6f2a03Jesse Wilson        server2.enqueue(new MockResponse().setBody("This is the 2nd server!"));
1389c0372d90016d241ac979faa6fa1731f30b6f2a03Jesse Wilson        server2.play();
1390c0372d90016d241ac979faa6fa1731f30b6f2a03Jesse Wilson
1391c0372d90016d241ac979faa6fa1731f30b6f2a03Jesse Wilson        server.enqueue(new MockResponse()
1392c0372d90016d241ac979faa6fa1731f30b6f2a03Jesse Wilson                .setResponseCode(HttpURLConnection.HTTP_MOVED_TEMP)
1393c0372d90016d241ac979faa6fa1731f30b6f2a03Jesse Wilson                .addHeader("Location: " + server2.getUrl("/").toString())
1394c0372d90016d241ac979faa6fa1731f30b6f2a03Jesse Wilson                .setBody("This page has moved!"));
1395c0372d90016d241ac979faa6fa1731f30b6f2a03Jesse Wilson        server.enqueue(new MockResponse().setBody("This is the first server again!"));
1396c0372d90016d241ac979faa6fa1731f30b6f2a03Jesse Wilson        server.play();
1397c0372d90016d241ac979faa6fa1731f30b6f2a03Jesse Wilson
1398c0372d90016d241ac979faa6fa1731f30b6f2a03Jesse Wilson        URLConnection connection = server.getUrl("/").openConnection();
1399c0372d90016d241ac979faa6fa1731f30b6f2a03Jesse Wilson        assertEquals("This is the 2nd server!",
1400c0372d90016d241ac979faa6fa1731f30b6f2a03Jesse Wilson                readAscii(connection.getInputStream(), Integer.MAX_VALUE));
1401c0372d90016d241ac979faa6fa1731f30b6f2a03Jesse Wilson        assertEquals(server2.getUrl("/"), connection.getURL());
1402c0372d90016d241ac979faa6fa1731f30b6f2a03Jesse Wilson
1403c0372d90016d241ac979faa6fa1731f30b6f2a03Jesse Wilson        // make sure the first server was careful to recycle the connection
1404c0372d90016d241ac979faa6fa1731f30b6f2a03Jesse Wilson        assertEquals("This is the first server again!",
1405c0372d90016d241ac979faa6fa1731f30b6f2a03Jesse Wilson                readAscii(server.getUrl("/").openStream(), Integer.MAX_VALUE));
1406c0372d90016d241ac979faa6fa1731f30b6f2a03Jesse Wilson
1407c0372d90016d241ac979faa6fa1731f30b6f2a03Jesse Wilson        RecordedRequest first = server.takeRequest();
14080c2fd828abec671333b8b88281825fd27a783723Jesse Wilson        assertContains(first.getHeaders(), "Host: " + hostName + ":" + server.getPort());
1409c0372d90016d241ac979faa6fa1731f30b6f2a03Jesse Wilson        RecordedRequest second = server2.takeRequest();
14100c2fd828abec671333b8b88281825fd27a783723Jesse Wilson        assertContains(second.getHeaders(), "Host: " + hostName + ":" + server2.getPort());
1411c0372d90016d241ac979faa6fa1731f30b6f2a03Jesse Wilson        RecordedRequest third = server.takeRequest();
1412c0372d90016d241ac979faa6fa1731f30b6f2a03Jesse Wilson        assertEquals("Expected connection reuse", 1, third.getSequenceNumber());
1413c0372d90016d241ac979faa6fa1731f30b6f2a03Jesse Wilson
1414c0372d90016d241ac979faa6fa1731f30b6f2a03Jesse Wilson        server2.shutdown();
1415c0372d90016d241ac979faa6fa1731f30b6f2a03Jesse Wilson    }
1416c0372d90016d241ac979faa6fa1731f30b6f2a03Jesse Wilson
1417d742d7fc7f0593eb8c6e4ac9dd4c0f6a80374e46Jesse Wilson    public void testResponse300MultipleChoiceWithPost() throws Exception {
1418d742d7fc7f0593eb8c6e4ac9dd4c0f6a80374e46Jesse Wilson        // Chrome doesn't follow the redirect, but Firefox and the RI both do
1419d742d7fc7f0593eb8c6e4ac9dd4c0f6a80374e46Jesse Wilson        testResponseRedirectedWithPost(HttpURLConnection.HTTP_MULT_CHOICE);
1420d742d7fc7f0593eb8c6e4ac9dd4c0f6a80374e46Jesse Wilson    }
1421d742d7fc7f0593eb8c6e4ac9dd4c0f6a80374e46Jesse Wilson
1422d742d7fc7f0593eb8c6e4ac9dd4c0f6a80374e46Jesse Wilson    public void testResponse301MovedPermanentlyWithPost() throws Exception {
1423d742d7fc7f0593eb8c6e4ac9dd4c0f6a80374e46Jesse Wilson        testResponseRedirectedWithPost(HttpURLConnection.HTTP_MOVED_PERM);
1424d742d7fc7f0593eb8c6e4ac9dd4c0f6a80374e46Jesse Wilson    }
1425d742d7fc7f0593eb8c6e4ac9dd4c0f6a80374e46Jesse Wilson
1426d742d7fc7f0593eb8c6e4ac9dd4c0f6a80374e46Jesse Wilson    public void testResponse302MovedTemporarilyWithPost() throws Exception {
1427d742d7fc7f0593eb8c6e4ac9dd4c0f6a80374e46Jesse Wilson        testResponseRedirectedWithPost(HttpURLConnection.HTTP_MOVED_TEMP);
1428d742d7fc7f0593eb8c6e4ac9dd4c0f6a80374e46Jesse Wilson    }
1429d742d7fc7f0593eb8c6e4ac9dd4c0f6a80374e46Jesse Wilson
1430d742d7fc7f0593eb8c6e4ac9dd4c0f6a80374e46Jesse Wilson    public void testResponse303SeeOtherWithPost() throws Exception {
1431d742d7fc7f0593eb8c6e4ac9dd4c0f6a80374e46Jesse Wilson        testResponseRedirectedWithPost(HttpURLConnection.HTTP_SEE_OTHER);
1432d742d7fc7f0593eb8c6e4ac9dd4c0f6a80374e46Jesse Wilson    }
1433d742d7fc7f0593eb8c6e4ac9dd4c0f6a80374e46Jesse Wilson
1434d742d7fc7f0593eb8c6e4ac9dd4c0f6a80374e46Jesse Wilson    private void testResponseRedirectedWithPost(int redirectCode) throws Exception {
1435d742d7fc7f0593eb8c6e4ac9dd4c0f6a80374e46Jesse Wilson        server.enqueue(new MockResponse()
1436d742d7fc7f0593eb8c6e4ac9dd4c0f6a80374e46Jesse Wilson                .setResponseCode(redirectCode)
1437d742d7fc7f0593eb8c6e4ac9dd4c0f6a80374e46Jesse Wilson                .addHeader("Location: /page2")
1438d742d7fc7f0593eb8c6e4ac9dd4c0f6a80374e46Jesse Wilson                .setBody("This page has moved!"));
1439d742d7fc7f0593eb8c6e4ac9dd4c0f6a80374e46Jesse Wilson        server.enqueue(new MockResponse().setBody("Page 2"));
1440d742d7fc7f0593eb8c6e4ac9dd4c0f6a80374e46Jesse Wilson        server.play();
1441d742d7fc7f0593eb8c6e4ac9dd4c0f6a80374e46Jesse Wilson
1442d742d7fc7f0593eb8c6e4ac9dd4c0f6a80374e46Jesse Wilson        HttpURLConnection connection = (HttpURLConnection) server.getUrl("/page1").openConnection();
1443d742d7fc7f0593eb8c6e4ac9dd4c0f6a80374e46Jesse Wilson        connection.setDoOutput(true);
1444d742d7fc7f0593eb8c6e4ac9dd4c0f6a80374e46Jesse Wilson        byte[] requestBody = { 'A', 'B', 'C', 'D' };
1445d742d7fc7f0593eb8c6e4ac9dd4c0f6a80374e46Jesse Wilson        OutputStream outputStream = connection.getOutputStream();
1446d742d7fc7f0593eb8c6e4ac9dd4c0f6a80374e46Jesse Wilson        outputStream.write(requestBody);
1447d742d7fc7f0593eb8c6e4ac9dd4c0f6a80374e46Jesse Wilson        outputStream.close();
1448d742d7fc7f0593eb8c6e4ac9dd4c0f6a80374e46Jesse Wilson        assertEquals("Page 2", readAscii(connection.getInputStream(), Integer.MAX_VALUE));
1449d742d7fc7f0593eb8c6e4ac9dd4c0f6a80374e46Jesse Wilson        assertTrue(connection.getDoOutput());
1450d742d7fc7f0593eb8c6e4ac9dd4c0f6a80374e46Jesse Wilson
1451d742d7fc7f0593eb8c6e4ac9dd4c0f6a80374e46Jesse Wilson        RecordedRequest page1 = server.takeRequest();
1452d742d7fc7f0593eb8c6e4ac9dd4c0f6a80374e46Jesse Wilson        assertEquals("POST /page1 HTTP/1.1", page1.getRequestLine());
1453d742d7fc7f0593eb8c6e4ac9dd4c0f6a80374e46Jesse Wilson        assertEquals(Arrays.toString(requestBody), Arrays.toString(page1.getBody()));
1454d742d7fc7f0593eb8c6e4ac9dd4c0f6a80374e46Jesse Wilson
1455d742d7fc7f0593eb8c6e4ac9dd4c0f6a80374e46Jesse Wilson        RecordedRequest page2 = server.takeRequest();
1456d742d7fc7f0593eb8c6e4ac9dd4c0f6a80374e46Jesse Wilson        assertEquals("GET /page2 HTTP/1.1", page2.getRequestLine());
1457d742d7fc7f0593eb8c6e4ac9dd4c0f6a80374e46Jesse Wilson    }
1458d742d7fc7f0593eb8c6e4ac9dd4c0f6a80374e46Jesse Wilson
1459d742d7fc7f0593eb8c6e4ac9dd4c0f6a80374e46Jesse Wilson    public void testResponse305UseProxy() throws Exception {
1460d742d7fc7f0593eb8c6e4ac9dd4c0f6a80374e46Jesse Wilson        server.play();
1461d742d7fc7f0593eb8c6e4ac9dd4c0f6a80374e46Jesse Wilson        server.enqueue(new MockResponse()
1462d742d7fc7f0593eb8c6e4ac9dd4c0f6a80374e46Jesse Wilson                .setResponseCode(HttpURLConnection.HTTP_USE_PROXY)
1463d742d7fc7f0593eb8c6e4ac9dd4c0f6a80374e46Jesse Wilson                .addHeader("Location: " + server.getUrl("/"))
1464d742d7fc7f0593eb8c6e4ac9dd4c0f6a80374e46Jesse Wilson                .setBody("This page has moved!"));
1465d742d7fc7f0593eb8c6e4ac9dd4c0f6a80374e46Jesse Wilson        server.enqueue(new MockResponse().setBody("Proxy Response"));
1466d742d7fc7f0593eb8c6e4ac9dd4c0f6a80374e46Jesse Wilson
1467d742d7fc7f0593eb8c6e4ac9dd4c0f6a80374e46Jesse Wilson        HttpURLConnection connection = (HttpURLConnection) server.getUrl("/foo").openConnection();
1468d742d7fc7f0593eb8c6e4ac9dd4c0f6a80374e46Jesse Wilson        // Fails on the RI, which gets "Proxy Response"
1469d742d7fc7f0593eb8c6e4ac9dd4c0f6a80374e46Jesse Wilson        assertEquals("This page has moved!",
1470d742d7fc7f0593eb8c6e4ac9dd4c0f6a80374e46Jesse Wilson                readAscii(connection.getInputStream(), Integer.MAX_VALUE));
1471d742d7fc7f0593eb8c6e4ac9dd4c0f6a80374e46Jesse Wilson
1472d742d7fc7f0593eb8c6e4ac9dd4c0f6a80374e46Jesse Wilson        RecordedRequest page1 = server.takeRequest();
1473d742d7fc7f0593eb8c6e4ac9dd4c0f6a80374e46Jesse Wilson        assertEquals("GET /foo HTTP/1.1", page1.getRequestLine());
1474d742d7fc7f0593eb8c6e4ac9dd4c0f6a80374e46Jesse Wilson        assertEquals(1, server.getRequestCount());
1475d742d7fc7f0593eb8c6e4ac9dd4c0f6a80374e46Jesse Wilson    }
1476d742d7fc7f0593eb8c6e4ac9dd4c0f6a80374e46Jesse Wilson
1477c0372d90016d241ac979faa6fa1731f30b6f2a03Jesse Wilson    public void testHttpsWithCustomTrustManager() throws Exception {
1478c0372d90016d241ac979faa6fa1731f30b6f2a03Jesse Wilson        RecordingHostnameVerifier hostnameVerifier = new RecordingHostnameVerifier();
1479c0372d90016d241ac979faa6fa1731f30b6f2a03Jesse Wilson        RecordingTrustManager trustManager = new RecordingTrustManager();
1480c0372d90016d241ac979faa6fa1731f30b6f2a03Jesse Wilson        SSLContext sc = SSLContext.getInstance("TLS");
1481c0372d90016d241ac979faa6fa1731f30b6f2a03Jesse Wilson        sc.init(null, new TrustManager[] { trustManager }, new java.security.SecureRandom());
1482c0372d90016d241ac979faa6fa1731f30b6f2a03Jesse Wilson
1483c0372d90016d241ac979faa6fa1731f30b6f2a03Jesse Wilson        HostnameVerifier defaultHostnameVerifier = HttpsURLConnection.getDefaultHostnameVerifier();
1484c0372d90016d241ac979faa6fa1731f30b6f2a03Jesse Wilson        HttpsURLConnection.setDefaultHostnameVerifier(hostnameVerifier);
1485c0372d90016d241ac979faa6fa1731f30b6f2a03Jesse Wilson        SSLSocketFactory defaultSSLSocketFactory = HttpsURLConnection.getDefaultSSLSocketFactory();
1486c0372d90016d241ac979faa6fa1731f30b6f2a03Jesse Wilson        HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
1487c0372d90016d241ac979faa6fa1731f30b6f2a03Jesse Wilson        try {
1488c0372d90016d241ac979faa6fa1731f30b6f2a03Jesse Wilson            TestSSLContext testSSLContext = TestSSLContext.create();
1489059dbc04218144f985b20a228bbe98139d400d0cBrian Carlstrom            server.useHttps(testSSLContext.serverContext.getSocketFactory(), false);
1490c0372d90016d241ac979faa6fa1731f30b6f2a03Jesse Wilson            server.enqueue(new MockResponse().setBody("ABC"));
1491c0372d90016d241ac979faa6fa1731f30b6f2a03Jesse Wilson            server.enqueue(new MockResponse().setBody("DEF"));
1492c0372d90016d241ac979faa6fa1731f30b6f2a03Jesse Wilson            server.enqueue(new MockResponse().setBody("GHI"));
1493c0372d90016d241ac979faa6fa1731f30b6f2a03Jesse Wilson            server.play();
1494c0372d90016d241ac979faa6fa1731f30b6f2a03Jesse Wilson
1495c0372d90016d241ac979faa6fa1731f30b6f2a03Jesse Wilson            URL url = server.getUrl("/");
1496c0372d90016d241ac979faa6fa1731f30b6f2a03Jesse Wilson            assertEquals("ABC", readAscii(url.openStream(), Integer.MAX_VALUE));
1497c0372d90016d241ac979faa6fa1731f30b6f2a03Jesse Wilson            assertEquals("DEF", readAscii(url.openStream(), Integer.MAX_VALUE));
1498c0372d90016d241ac979faa6fa1731f30b6f2a03Jesse Wilson            assertEquals("GHI", readAscii(url.openStream(), Integer.MAX_VALUE));
1499c0372d90016d241ac979faa6fa1731f30b6f2a03Jesse Wilson
15000c2fd828abec671333b8b88281825fd27a783723Jesse Wilson            assertEquals(Arrays.asList("verify " + hostName), hostnameVerifier.calls);
15014559b1d37edcb5d7f1da086cf2e3290388d74f46Brian Carlstrom            assertEquals(Arrays.asList("checkServerTrusted ["
15020c2fd828abec671333b8b88281825fd27a783723Jesse Wilson                    + "CN=" + hostName + " 1, "
1503b7f4d6c3968c372767b2510f38a3d506067aced6Jesse Wilson                    + "CN=Test Intermediate Certificate Authority 1, "
1504b7f4d6c3968c372767b2510f38a3d506067aced6Jesse Wilson                    + "CN=Test Root Certificate Authority 1"
1505b7f4d6c3968c372767b2510f38a3d506067aced6Jesse Wilson                    + "] RSA"),
1506c0372d90016d241ac979faa6fa1731f30b6f2a03Jesse Wilson                    trustManager.calls);
1507c0372d90016d241ac979faa6fa1731f30b6f2a03Jesse Wilson        } finally {
1508c0372d90016d241ac979faa6fa1731f30b6f2a03Jesse Wilson            HttpsURLConnection.setDefaultHostnameVerifier(defaultHostnameVerifier);
1509c0372d90016d241ac979faa6fa1731f30b6f2a03Jesse Wilson            HttpsURLConnection.setDefaultSSLSocketFactory(defaultSSLSocketFactory);
1510c0372d90016d241ac979faa6fa1731f30b6f2a03Jesse Wilson        }
1511c0372d90016d241ac979faa6fa1731f30b6f2a03Jesse Wilson    }
1512c0372d90016d241ac979faa6fa1731f30b6f2a03Jesse Wilson
15132d9fa917aae6a6da38e9d1eda05841ffdf8855bbJesse Wilson    /**
15142d9fa917aae6a6da38e9d1eda05841ffdf8855bbJesse Wilson     * Test that the timeout period is honored. The timeout may be doubled!
15152d9fa917aae6a6da38e9d1eda05841ffdf8855bbJesse Wilson     * HttpURLConnection will wait the full timeout for each of the server's IP
15162d9fa917aae6a6da38e9d1eda05841ffdf8855bbJesse Wilson     * addresses. This is typically one IPv4 address and one IPv6 address.
15172d9fa917aae6a6da38e9d1eda05841ffdf8855bbJesse Wilson     */
1518eafede536f2059bb6c869e7a5f07fd7ad9758e28Jesse Wilson    public void testConnectTimeouts() throws IOException {
15195fc5dde4c719c1dfdac46b67d5d2e4884d07721eElliott Hughes        StuckServer ss = new StuckServer();
15205fc5dde4c719c1dfdac46b67d5d2e4884d07721eElliott Hughes        int serverPort = ss.getLocalPort();
1521f02c695ed03e708623d9365dec26d533356ef2d0Brian Carlstrom        URLConnection urlConnection = new URL("http://localhost:" + serverPort).openConnection();
1522b7f4d6c3968c372767b2510f38a3d506067aced6Jesse Wilson        int timeout = 1000;
1523b7f4d6c3968c372767b2510f38a3d506067aced6Jesse Wilson        urlConnection.setConnectTimeout(timeout);
1524b7f4d6c3968c372767b2510f38a3d506067aced6Jesse Wilson        long start = System.currentTimeMillis();
1525eafede536f2059bb6c869e7a5f07fd7ad9758e28Jesse Wilson        try {
1526eafede536f2059bb6c869e7a5f07fd7ad9758e28Jesse Wilson            urlConnection.getInputStream();
1527eafede536f2059bb6c869e7a5f07fd7ad9758e28Jesse Wilson            fail();
1528eafede536f2059bb6c869e7a5f07fd7ad9758e28Jesse Wilson        } catch (SocketTimeoutException expected) {
15292d9fa917aae6a6da38e9d1eda05841ffdf8855bbJesse Wilson            long elapsed = System.currentTimeMillis() - start;
15302d9fa917aae6a6da38e9d1eda05841ffdf8855bbJesse Wilson            int attempts = InetAddress.getAllByName("localhost").length; // one per IP address
15312d9fa917aae6a6da38e9d1eda05841ffdf8855bbJesse Wilson            assertTrue("timeout=" +timeout + ", elapsed=" + elapsed + ", attempts=" + attempts,
15322d9fa917aae6a6da38e9d1eda05841ffdf8855bbJesse Wilson                    Math.abs((attempts * timeout) - elapsed) < 500);
15335fc5dde4c719c1dfdac46b67d5d2e4884d07721eElliott Hughes        } finally {
15345fc5dde4c719c1dfdac46b67d5d2e4884d07721eElliott Hughes            ss.close();
1535f02c695ed03e708623d9365dec26d533356ef2d0Brian Carlstrom        }
1536eafede536f2059bb6c869e7a5f07fd7ad9758e28Jesse Wilson    }
1537eafede536f2059bb6c869e7a5f07fd7ad9758e28Jesse Wilson
1538eafede536f2059bb6c869e7a5f07fd7ad9758e28Jesse Wilson    public void testReadTimeouts() throws IOException {
1539eafede536f2059bb6c869e7a5f07fd7ad9758e28Jesse Wilson        /*
1540eafede536f2059bb6c869e7a5f07fd7ad9758e28Jesse Wilson         * This relies on the fact that MockWebServer doesn't close the
1541eafede536f2059bb6c869e7a5f07fd7ad9758e28Jesse Wilson         * connection after a response has been sent. This causes the client to
1542eafede536f2059bb6c869e7a5f07fd7ad9758e28Jesse Wilson         * try to read more bytes than are sent, which results in a timeout.
1543eafede536f2059bb6c869e7a5f07fd7ad9758e28Jesse Wilson         */
1544eafede536f2059bb6c869e7a5f07fd7ad9758e28Jesse Wilson        MockResponse timeout = new MockResponse()
1545eafede536f2059bb6c869e7a5f07fd7ad9758e28Jesse Wilson                .setBody("ABC")
1546eafede536f2059bb6c869e7a5f07fd7ad9758e28Jesse Wilson                .clearHeaders()
1547eafede536f2059bb6c869e7a5f07fd7ad9758e28Jesse Wilson                .addHeader("Content-Length: 4");
1548eafede536f2059bb6c869e7a5f07fd7ad9758e28Jesse Wilson        server.enqueue(timeout);
1549b7f4d6c3968c372767b2510f38a3d506067aced6Jesse Wilson        server.enqueue(new MockResponse().setBody("unused")); // to keep the server alive
1550eafede536f2059bb6c869e7a5f07fd7ad9758e28Jesse Wilson        server.play();
1551eafede536f2059bb6c869e7a5f07fd7ad9758e28Jesse Wilson
1552eafede536f2059bb6c869e7a5f07fd7ad9758e28Jesse Wilson        URLConnection urlConnection = server.getUrl("/").openConnection();
1553eafede536f2059bb6c869e7a5f07fd7ad9758e28Jesse Wilson        urlConnection.setReadTimeout(1000);
1554eafede536f2059bb6c869e7a5f07fd7ad9758e28Jesse Wilson        InputStream in = urlConnection.getInputStream();
1555eafede536f2059bb6c869e7a5f07fd7ad9758e28Jesse Wilson        assertEquals('A', in.read());
1556eafede536f2059bb6c869e7a5f07fd7ad9758e28Jesse Wilson        assertEquals('B', in.read());
1557eafede536f2059bb6c869e7a5f07fd7ad9758e28Jesse Wilson        assertEquals('C', in.read());
1558eafede536f2059bb6c869e7a5f07fd7ad9758e28Jesse Wilson        try {
1559eafede536f2059bb6c869e7a5f07fd7ad9758e28Jesse Wilson            in.read(); // if Content-Length was accurate, this would return -1 immediately
1560eafede536f2059bb6c869e7a5f07fd7ad9758e28Jesse Wilson            fail();
1561eafede536f2059bb6c869e7a5f07fd7ad9758e28Jesse Wilson        } catch (SocketTimeoutException expected) {
1562eafede536f2059bb6c869e7a5f07fd7ad9758e28Jesse Wilson        }
1563eafede536f2059bb6c869e7a5f07fd7ad9758e28Jesse Wilson    }
1564eafede536f2059bb6c869e7a5f07fd7ad9758e28Jesse Wilson
1565125f068f0a6cd739beac97821c9421cf8317cc87Jesse Wilson    public void testSetChunkedEncodingAsRequestProperty() throws IOException, InterruptedException {
1566125f068f0a6cd739beac97821c9421cf8317cc87Jesse Wilson        server.enqueue(new MockResponse());
1567125f068f0a6cd739beac97821c9421cf8317cc87Jesse Wilson        server.play();
1568125f068f0a6cd739beac97821c9421cf8317cc87Jesse Wilson
1569125f068f0a6cd739beac97821c9421cf8317cc87Jesse Wilson        HttpURLConnection urlConnection = (HttpURLConnection) server.getUrl("/").openConnection();
1570125f068f0a6cd739beac97821c9421cf8317cc87Jesse Wilson        urlConnection.setRequestProperty("Transfer-encoding", "chunked");
1571125f068f0a6cd739beac97821c9421cf8317cc87Jesse Wilson        urlConnection.setDoOutput(true);
1572125f068f0a6cd739beac97821c9421cf8317cc87Jesse Wilson        urlConnection.getOutputStream().write("ABC".getBytes("UTF-8"));
1573125f068f0a6cd739beac97821c9421cf8317cc87Jesse Wilson        assertEquals(200, urlConnection.getResponseCode());
1574125f068f0a6cd739beac97821c9421cf8317cc87Jesse Wilson
1575125f068f0a6cd739beac97821c9421cf8317cc87Jesse Wilson        RecordedRequest request = server.takeRequest();
1576125f068f0a6cd739beac97821c9421cf8317cc87Jesse Wilson        assertEquals("ABC", new String(request.getBody(), "UTF-8"));
1577125f068f0a6cd739beac97821c9421cf8317cc87Jesse Wilson    }
1578125f068f0a6cd739beac97821c9421cf8317cc87Jesse Wilson
1579f418bf447fd007cd2ec2d45b4b0399a11904e9b4Jesse Wilson    public void testConnectionCloseInRequest() throws IOException, InterruptedException {
1580f418bf447fd007cd2ec2d45b4b0399a11904e9b4Jesse Wilson        server.enqueue(new MockResponse()); // server doesn't honor the connection: close header!
1581f418bf447fd007cd2ec2d45b4b0399a11904e9b4Jesse Wilson        server.enqueue(new MockResponse());
1582f418bf447fd007cd2ec2d45b4b0399a11904e9b4Jesse Wilson        server.play();
1583f418bf447fd007cd2ec2d45b4b0399a11904e9b4Jesse Wilson
1584f418bf447fd007cd2ec2d45b4b0399a11904e9b4Jesse Wilson        HttpURLConnection a = (HttpURLConnection) server.getUrl("/").openConnection();
1585f418bf447fd007cd2ec2d45b4b0399a11904e9b4Jesse Wilson        a.setRequestProperty("Connection", "close");
1586f418bf447fd007cd2ec2d45b4b0399a11904e9b4Jesse Wilson        assertEquals(200, a.getResponseCode());
1587f418bf447fd007cd2ec2d45b4b0399a11904e9b4Jesse Wilson
1588f418bf447fd007cd2ec2d45b4b0399a11904e9b4Jesse Wilson        HttpURLConnection b = (HttpURLConnection) server.getUrl("/").openConnection();
1589f418bf447fd007cd2ec2d45b4b0399a11904e9b4Jesse Wilson        assertEquals(200, b.getResponseCode());
1590f418bf447fd007cd2ec2d45b4b0399a11904e9b4Jesse Wilson
1591f418bf447fd007cd2ec2d45b4b0399a11904e9b4Jesse Wilson        assertEquals(0, server.takeRequest().getSequenceNumber());
1592f418bf447fd007cd2ec2d45b4b0399a11904e9b4Jesse Wilson        assertEquals("When connection: close is used, each request should get its own connection",
1593f418bf447fd007cd2ec2d45b4b0399a11904e9b4Jesse Wilson                0, server.takeRequest().getSequenceNumber());
1594f418bf447fd007cd2ec2d45b4b0399a11904e9b4Jesse Wilson    }
1595f418bf447fd007cd2ec2d45b4b0399a11904e9b4Jesse Wilson
1596f418bf447fd007cd2ec2d45b4b0399a11904e9b4Jesse Wilson    public void testConnectionCloseInResponse() throws IOException, InterruptedException {
1597f418bf447fd007cd2ec2d45b4b0399a11904e9b4Jesse Wilson        server.enqueue(new MockResponse().addHeader("Connection: close"));
1598f418bf447fd007cd2ec2d45b4b0399a11904e9b4Jesse Wilson        server.enqueue(new MockResponse());
1599f418bf447fd007cd2ec2d45b4b0399a11904e9b4Jesse Wilson        server.play();
1600f418bf447fd007cd2ec2d45b4b0399a11904e9b4Jesse Wilson
1601f418bf447fd007cd2ec2d45b4b0399a11904e9b4Jesse Wilson        HttpURLConnection a = (HttpURLConnection) server.getUrl("/").openConnection();
1602f418bf447fd007cd2ec2d45b4b0399a11904e9b4Jesse Wilson        assertEquals(200, a.getResponseCode());
1603f418bf447fd007cd2ec2d45b4b0399a11904e9b4Jesse Wilson
1604f418bf447fd007cd2ec2d45b4b0399a11904e9b4Jesse Wilson        HttpURLConnection b = (HttpURLConnection) server.getUrl("/").openConnection();
1605f418bf447fd007cd2ec2d45b4b0399a11904e9b4Jesse Wilson        assertEquals(200, b.getResponseCode());
1606f418bf447fd007cd2ec2d45b4b0399a11904e9b4Jesse Wilson
1607f418bf447fd007cd2ec2d45b4b0399a11904e9b4Jesse Wilson        assertEquals(0, server.takeRequest().getSequenceNumber());
1608f418bf447fd007cd2ec2d45b4b0399a11904e9b4Jesse Wilson        assertEquals("When connection: close is used, each request should get its own connection",
1609f418bf447fd007cd2ec2d45b4b0399a11904e9b4Jesse Wilson                0, server.takeRequest().getSequenceNumber());
1610f418bf447fd007cd2ec2d45b4b0399a11904e9b4Jesse Wilson    }
1611f418bf447fd007cd2ec2d45b4b0399a11904e9b4Jesse Wilson
1612f418bf447fd007cd2ec2d45b4b0399a11904e9b4Jesse Wilson    public void testConnectionCloseWithRedirect() throws IOException, InterruptedException {
1613f418bf447fd007cd2ec2d45b4b0399a11904e9b4Jesse Wilson        MockResponse response = new MockResponse()
1614f418bf447fd007cd2ec2d45b4b0399a11904e9b4Jesse Wilson                .setResponseCode(HttpURLConnection.HTTP_MOVED_TEMP)
1615f418bf447fd007cd2ec2d45b4b0399a11904e9b4Jesse Wilson                .addHeader("Location: /foo")
1616f418bf447fd007cd2ec2d45b4b0399a11904e9b4Jesse Wilson                .addHeader("Connection: close");
1617f418bf447fd007cd2ec2d45b4b0399a11904e9b4Jesse Wilson        server.enqueue(response);
1618f418bf447fd007cd2ec2d45b4b0399a11904e9b4Jesse Wilson        server.enqueue(new MockResponse().setBody("This is the new location!"));
1619f418bf447fd007cd2ec2d45b4b0399a11904e9b4Jesse Wilson        server.play();
1620f418bf447fd007cd2ec2d45b4b0399a11904e9b4Jesse Wilson
1621f418bf447fd007cd2ec2d45b4b0399a11904e9b4Jesse Wilson        URLConnection connection = server.getUrl("/").openConnection();
1622f418bf447fd007cd2ec2d45b4b0399a11904e9b4Jesse Wilson        assertEquals("This is the new location!",
1623f418bf447fd007cd2ec2d45b4b0399a11904e9b4Jesse Wilson                readAscii(connection.getInputStream(), Integer.MAX_VALUE));
1624f418bf447fd007cd2ec2d45b4b0399a11904e9b4Jesse Wilson
1625f418bf447fd007cd2ec2d45b4b0399a11904e9b4Jesse Wilson        assertEquals(0, server.takeRequest().getSequenceNumber());
1626f418bf447fd007cd2ec2d45b4b0399a11904e9b4Jesse Wilson        assertEquals("When connection: close is used, each request should get its own connection",
1627f418bf447fd007cd2ec2d45b4b0399a11904e9b4Jesse Wilson                0, server.takeRequest().getSequenceNumber());
1628f418bf447fd007cd2ec2d45b4b0399a11904e9b4Jesse Wilson    }
1629f418bf447fd007cd2ec2d45b4b0399a11904e9b4Jesse Wilson
163065d890eb22aeba9b009ee642ffd4fff48a6f98aeJesse Wilson    public void testResponseCodeDisagreesWithHeaders() throws IOException, InterruptedException {
163165d890eb22aeba9b009ee642ffd4fff48a6f98aeJesse Wilson        server.enqueue(new MockResponse()
163265d890eb22aeba9b009ee642ffd4fff48a6f98aeJesse Wilson                .setResponseCode(HttpURLConnection.HTTP_NO_CONTENT)
163365d890eb22aeba9b009ee642ffd4fff48a6f98aeJesse Wilson                .setBody("This body is not allowed!"));
163465d890eb22aeba9b009ee642ffd4fff48a6f98aeJesse Wilson        server.play();
163565d890eb22aeba9b009ee642ffd4fff48a6f98aeJesse Wilson
163665d890eb22aeba9b009ee642ffd4fff48a6f98aeJesse Wilson        URLConnection connection = server.getUrl("/").openConnection();
163765d890eb22aeba9b009ee642ffd4fff48a6f98aeJesse Wilson        assertEquals("This body is not allowed!",
163865d890eb22aeba9b009ee642ffd4fff48a6f98aeJesse Wilson                readAscii(connection.getInputStream(), Integer.MAX_VALUE));
163965d890eb22aeba9b009ee642ffd4fff48a6f98aeJesse Wilson    }
164065d890eb22aeba9b009ee642ffd4fff48a6f98aeJesse Wilson
1641ef66494dce45a0b7ec22ec3fb20c60096517a4e3Jesse Wilson    public void testSingleByteReadIsSigned() throws IOException {
1642ef66494dce45a0b7ec22ec3fb20c60096517a4e3Jesse Wilson        server.enqueue(new MockResponse().setBody(new byte[] { -2, -1 }));
1643ef66494dce45a0b7ec22ec3fb20c60096517a4e3Jesse Wilson        server.play();
1644ef66494dce45a0b7ec22ec3fb20c60096517a4e3Jesse Wilson
1645ef66494dce45a0b7ec22ec3fb20c60096517a4e3Jesse Wilson        URLConnection connection = server.getUrl("/").openConnection();
1646ef66494dce45a0b7ec22ec3fb20c60096517a4e3Jesse Wilson        InputStream in = connection.getInputStream();
1647ef66494dce45a0b7ec22ec3fb20c60096517a4e3Jesse Wilson        assertEquals(254, in.read());
1648ef66494dce45a0b7ec22ec3fb20c60096517a4e3Jesse Wilson        assertEquals(255, in.read());
1649ef66494dce45a0b7ec22ec3fb20c60096517a4e3Jesse Wilson        assertEquals(-1, in.read());
1650ef66494dce45a0b7ec22ec3fb20c60096517a4e3Jesse Wilson    }
1651ef66494dce45a0b7ec22ec3fb20c60096517a4e3Jesse Wilson
1652f29ad8a60254345d1943d1b3836482395a7c916fJesse Wilson    public void testFlushAfterStreamTransmittedWithChunkedEncoding() throws IOException {
1653f29ad8a60254345d1943d1b3836482395a7c916fJesse Wilson        testFlushAfterStreamTransmitted(TransferKind.CHUNKED);
1654f29ad8a60254345d1943d1b3836482395a7c916fJesse Wilson    }
1655f29ad8a60254345d1943d1b3836482395a7c916fJesse Wilson
1656f29ad8a60254345d1943d1b3836482395a7c916fJesse Wilson    public void testFlushAfterStreamTransmittedWithFixedLength() throws IOException {
1657f29ad8a60254345d1943d1b3836482395a7c916fJesse Wilson        testFlushAfterStreamTransmitted(TransferKind.FIXED_LENGTH);
1658f29ad8a60254345d1943d1b3836482395a7c916fJesse Wilson    }
1659f29ad8a60254345d1943d1b3836482395a7c916fJesse Wilson
1660f29ad8a60254345d1943d1b3836482395a7c916fJesse Wilson    public void testFlushAfterStreamTransmittedWithNoLengthHeaders() throws IOException {
1661f29ad8a60254345d1943d1b3836482395a7c916fJesse Wilson        testFlushAfterStreamTransmitted(TransferKind.END_OF_STREAM);
1662f29ad8a60254345d1943d1b3836482395a7c916fJesse Wilson    }
1663f29ad8a60254345d1943d1b3836482395a7c916fJesse Wilson
1664f29ad8a60254345d1943d1b3836482395a7c916fJesse Wilson    /**
1665f29ad8a60254345d1943d1b3836482395a7c916fJesse Wilson     * We explicitly permit apps to close the upload stream even after it has
1666f29ad8a60254345d1943d1b3836482395a7c916fJesse Wilson     * been transmitted.  We also permit flush so that buffered streams can
1667f29ad8a60254345d1943d1b3836482395a7c916fJesse Wilson     * do a no-op flush when they are closed. http://b/3038470
1668f29ad8a60254345d1943d1b3836482395a7c916fJesse Wilson     */
1669f29ad8a60254345d1943d1b3836482395a7c916fJesse Wilson    private void testFlushAfterStreamTransmitted(TransferKind transferKind) throws IOException {
1670f29ad8a60254345d1943d1b3836482395a7c916fJesse Wilson        server.enqueue(new MockResponse().setBody("abc"));
1671f29ad8a60254345d1943d1b3836482395a7c916fJesse Wilson        server.play();
1672f29ad8a60254345d1943d1b3836482395a7c916fJesse Wilson
1673f29ad8a60254345d1943d1b3836482395a7c916fJesse Wilson        HttpURLConnection connection = (HttpURLConnection) server.getUrl("/").openConnection();
1674f29ad8a60254345d1943d1b3836482395a7c916fJesse Wilson        connection.setDoOutput(true);
1675f29ad8a60254345d1943d1b3836482395a7c916fJesse Wilson        byte[] upload = "def".getBytes("UTF-8");
1676f29ad8a60254345d1943d1b3836482395a7c916fJesse Wilson
1677f29ad8a60254345d1943d1b3836482395a7c916fJesse Wilson        if (transferKind == TransferKind.CHUNKED) {
1678f29ad8a60254345d1943d1b3836482395a7c916fJesse Wilson            connection.setChunkedStreamingMode(0);
1679f29ad8a60254345d1943d1b3836482395a7c916fJesse Wilson        } else if (transferKind == TransferKind.FIXED_LENGTH) {
1680f29ad8a60254345d1943d1b3836482395a7c916fJesse Wilson            connection.setFixedLengthStreamingMode(upload.length);
1681f29ad8a60254345d1943d1b3836482395a7c916fJesse Wilson        }
1682f29ad8a60254345d1943d1b3836482395a7c916fJesse Wilson
1683f29ad8a60254345d1943d1b3836482395a7c916fJesse Wilson        OutputStream out = connection.getOutputStream();
1684f29ad8a60254345d1943d1b3836482395a7c916fJesse Wilson        out.write(upload);
1685f29ad8a60254345d1943d1b3836482395a7c916fJesse Wilson        assertEquals("abc", readAscii(connection.getInputStream(), Integer.MAX_VALUE));
1686f29ad8a60254345d1943d1b3836482395a7c916fJesse Wilson
1687f29ad8a60254345d1943d1b3836482395a7c916fJesse Wilson        out.flush(); // dubious but permitted
1688f29ad8a60254345d1943d1b3836482395a7c916fJesse Wilson        try {
1689f29ad8a60254345d1943d1b3836482395a7c916fJesse Wilson            out.write("ghi".getBytes("UTF-8"));
1690f29ad8a60254345d1943d1b3836482395a7c916fJesse Wilson            fail();
1691f29ad8a60254345d1943d1b3836482395a7c916fJesse Wilson        } catch (IOException expected) {
1692f29ad8a60254345d1943d1b3836482395a7c916fJesse Wilson        }
1693f29ad8a60254345d1943d1b3836482395a7c916fJesse Wilson    }
1694f29ad8a60254345d1943d1b3836482395a7c916fJesse Wilson
1695c6dae581716b9362a5c7f166c80a7f2b46ed1124Jesse Wilson    public void testGetHeadersThrows() throws IOException {
1696e942f46f10bb9384a1b186b3d7b74f9704c57090Jesse Wilson        server.enqueue(new MockResponse().setSocketPolicy(DISCONNECT_AT_START));
1697c6dae581716b9362a5c7f166c80a7f2b46ed1124Jesse Wilson        server.play();
1698c6dae581716b9362a5c7f166c80a7f2b46ed1124Jesse Wilson
1699c6dae581716b9362a5c7f166c80a7f2b46ed1124Jesse Wilson        HttpURLConnection connection = (HttpURLConnection) server.getUrl("/").openConnection();
1700c6dae581716b9362a5c7f166c80a7f2b46ed1124Jesse Wilson        try {
1701c6dae581716b9362a5c7f166c80a7f2b46ed1124Jesse Wilson            connection.getInputStream();
1702c6dae581716b9362a5c7f166c80a7f2b46ed1124Jesse Wilson            fail();
1703c6dae581716b9362a5c7f166c80a7f2b46ed1124Jesse Wilson        } catch (IOException expected) {
1704c6dae581716b9362a5c7f166c80a7f2b46ed1124Jesse Wilson        }
1705c6dae581716b9362a5c7f166c80a7f2b46ed1124Jesse Wilson
1706c6dae581716b9362a5c7f166c80a7f2b46ed1124Jesse Wilson        try {
1707c6dae581716b9362a5c7f166c80a7f2b46ed1124Jesse Wilson            connection.getInputStream();
1708c6dae581716b9362a5c7f166c80a7f2b46ed1124Jesse Wilson            fail();
1709f29ad8a60254345d1943d1b3836482395a7c916fJesse Wilson        } catch (IOException expected) {
1710f29ad8a60254345d1943d1b3836482395a7c916fJesse Wilson        }
1711f29ad8a60254345d1943d1b3836482395a7c916fJesse Wilson    }
1712f29ad8a60254345d1943d1b3836482395a7c916fJesse Wilson
1713b7f4d6c3968c372767b2510f38a3d506067aced6Jesse Wilson    public void testGetKeepAlive() throws Exception {
1714b7f4d6c3968c372767b2510f38a3d506067aced6Jesse Wilson        MockWebServer server = new MockWebServer();
1715b7f4d6c3968c372767b2510f38a3d506067aced6Jesse Wilson        server.enqueue(new MockResponse().setBody("ABC"));
1716b7f4d6c3968c372767b2510f38a3d506067aced6Jesse Wilson        server.play();
1717b7f4d6c3968c372767b2510f38a3d506067aced6Jesse Wilson
1718b7f4d6c3968c372767b2510f38a3d506067aced6Jesse Wilson        // The request should work once and then fail
1719b7f4d6c3968c372767b2510f38a3d506067aced6Jesse Wilson        URLConnection connection = server.getUrl("").openConnection();
1720b7f4d6c3968c372767b2510f38a3d506067aced6Jesse Wilson        InputStream input = connection.getInputStream();
1721b7f4d6c3968c372767b2510f38a3d506067aced6Jesse Wilson        assertEquals("ABC", readAscii(input, Integer.MAX_VALUE));
1722b7f4d6c3968c372767b2510f38a3d506067aced6Jesse Wilson        input.close();
1723b7f4d6c3968c372767b2510f38a3d506067aced6Jesse Wilson        try {
1724b7f4d6c3968c372767b2510f38a3d506067aced6Jesse Wilson            server.getUrl("").openConnection().getInputStream();
1725b7f4d6c3968c372767b2510f38a3d506067aced6Jesse Wilson            fail();
1726b7f4d6c3968c372767b2510f38a3d506067aced6Jesse Wilson        } catch (ConnectException expected) {
1727b7f4d6c3968c372767b2510f38a3d506067aced6Jesse Wilson        }
1728b7f4d6c3968c372767b2510f38a3d506067aced6Jesse Wilson    }
1729b7f4d6c3968c372767b2510f38a3d506067aced6Jesse Wilson
1730b7f4d6c3968c372767b2510f38a3d506067aced6Jesse Wilson    /**
1731d1b5e5da828434388e486a388710d21e4306dae0Jesse Wilson     * This test goes through the exhaustive set of interesting ASCII characters
1732d1b5e5da828434388e486a388710d21e4306dae0Jesse Wilson     * because most of those characters are interesting in some way according to
1733d1b5e5da828434388e486a388710d21e4306dae0Jesse Wilson     * RFC 2396 and RFC 2732. http://b/1158780
1734b7f4d6c3968c372767b2510f38a3d506067aced6Jesse Wilson     */
1735d1b5e5da828434388e486a388710d21e4306dae0Jesse Wilson    public void testLenientUrlToUri() throws Exception {
1736d1b5e5da828434388e486a388710d21e4306dae0Jesse Wilson        // alphanum
1737d1b5e5da828434388e486a388710d21e4306dae0Jesse Wilson        testUrlToUriMapping("abzABZ09", "abzABZ09", "abzABZ09", "abzABZ09", "abzABZ09");
1738d1b5e5da828434388e486a388710d21e4306dae0Jesse Wilson
1739d1b5e5da828434388e486a388710d21e4306dae0Jesse Wilson        // control characters
1740d1b5e5da828434388e486a388710d21e4306dae0Jesse Wilson        testUrlToUriMapping("\u0001", "%01", "%01", "%01", "%01");
1741d1b5e5da828434388e486a388710d21e4306dae0Jesse Wilson        testUrlToUriMapping("\u001f", "%1F", "%1F", "%1F", "%1F");
1742d1b5e5da828434388e486a388710d21e4306dae0Jesse Wilson
1743d1b5e5da828434388e486a388710d21e4306dae0Jesse Wilson        // ascii characters
1744d1b5e5da828434388e486a388710d21e4306dae0Jesse Wilson        testUrlToUriMapping("%20", "%20", "%20", "%20", "%20");
1745d1b5e5da828434388e486a388710d21e4306dae0Jesse Wilson        testUrlToUriMapping("%20", "%20", "%20", "%20", "%20");
1746d1b5e5da828434388e486a388710d21e4306dae0Jesse Wilson        testUrlToUriMapping(" ", "%20", "%20", "%20", "%20");
1747d1b5e5da828434388e486a388710d21e4306dae0Jesse Wilson        testUrlToUriMapping("!", "!", "!", "!", "!");
1748d1b5e5da828434388e486a388710d21e4306dae0Jesse Wilson        testUrlToUriMapping("\"", "%22", "%22", "%22", "%22");
1749d1b5e5da828434388e486a388710d21e4306dae0Jesse Wilson        testUrlToUriMapping("#", null, null, null, "%23");
1750d1b5e5da828434388e486a388710d21e4306dae0Jesse Wilson        testUrlToUriMapping("$", "$", "$", "$", "$");
1751d1b5e5da828434388e486a388710d21e4306dae0Jesse Wilson        testUrlToUriMapping("&", "&", "&", "&", "&");
1752d1b5e5da828434388e486a388710d21e4306dae0Jesse Wilson        testUrlToUriMapping("'", "'", "'", "'", "'");
1753d1b5e5da828434388e486a388710d21e4306dae0Jesse Wilson        testUrlToUriMapping("(", "(", "(", "(", "(");
1754d1b5e5da828434388e486a388710d21e4306dae0Jesse Wilson        testUrlToUriMapping(")", ")", ")", ")", ")");
1755d1b5e5da828434388e486a388710d21e4306dae0Jesse Wilson        testUrlToUriMapping("*", "*", "*", "*", "*");
1756d1b5e5da828434388e486a388710d21e4306dae0Jesse Wilson        testUrlToUriMapping("+", "+", "+", "+", "+");
1757d1b5e5da828434388e486a388710d21e4306dae0Jesse Wilson        testUrlToUriMapping(",", ",", ",", ",", ",");
1758d1b5e5da828434388e486a388710d21e4306dae0Jesse Wilson        testUrlToUriMapping("-", "-", "-", "-", "-");
1759d1b5e5da828434388e486a388710d21e4306dae0Jesse Wilson        testUrlToUriMapping(".", ".", ".", ".", ".");
1760d1b5e5da828434388e486a388710d21e4306dae0Jesse Wilson        testUrlToUriMapping("/", null, "/", "/", "/");
1761d1b5e5da828434388e486a388710d21e4306dae0Jesse Wilson        testUrlToUriMapping(":", null, ":", ":", ":");
1762d1b5e5da828434388e486a388710d21e4306dae0Jesse Wilson        testUrlToUriMapping(";", ";", ";", ";", ";");
1763d1b5e5da828434388e486a388710d21e4306dae0Jesse Wilson        testUrlToUriMapping("<", "%3C", "%3C", "%3C", "%3C");
1764d1b5e5da828434388e486a388710d21e4306dae0Jesse Wilson        testUrlToUriMapping("=", "=", "=", "=", "=");
1765d1b5e5da828434388e486a388710d21e4306dae0Jesse Wilson        testUrlToUriMapping(">", "%3E", "%3E", "%3E", "%3E");
1766d1b5e5da828434388e486a388710d21e4306dae0Jesse Wilson        testUrlToUriMapping("?", null, null, "?", "?");
1767d1b5e5da828434388e486a388710d21e4306dae0Jesse Wilson        testUrlToUriMapping("@", "@", "@", "@", "@");
1768d1b5e5da828434388e486a388710d21e4306dae0Jesse Wilson        testUrlToUriMapping("[", null, "%5B", null, "%5B");
1769d1b5e5da828434388e486a388710d21e4306dae0Jesse Wilson        testUrlToUriMapping("\\", "%5C", "%5C", "%5C", "%5C");
1770d1b5e5da828434388e486a388710d21e4306dae0Jesse Wilson        testUrlToUriMapping("]", null, "%5D", null, "%5D");
1771d1b5e5da828434388e486a388710d21e4306dae0Jesse Wilson        testUrlToUriMapping("^", "%5E", "%5E", "%5E", "%5E");
1772d1b5e5da828434388e486a388710d21e4306dae0Jesse Wilson        testUrlToUriMapping("_", "_", "_", "_", "_");
1773d1b5e5da828434388e486a388710d21e4306dae0Jesse Wilson        testUrlToUriMapping("`", "%60", "%60", "%60", "%60");
1774d1b5e5da828434388e486a388710d21e4306dae0Jesse Wilson        testUrlToUriMapping("{", "%7B", "%7B", "%7B", "%7B");
1775d1b5e5da828434388e486a388710d21e4306dae0Jesse Wilson        testUrlToUriMapping("|", "%7C", "%7C", "%7C", "%7C");
1776d1b5e5da828434388e486a388710d21e4306dae0Jesse Wilson        testUrlToUriMapping("}", "%7D", "%7D", "%7D", "%7D");
1777d1b5e5da828434388e486a388710d21e4306dae0Jesse Wilson        testUrlToUriMapping("~", "~", "~", "~", "~");
1778d1b5e5da828434388e486a388710d21e4306dae0Jesse Wilson        testUrlToUriMapping("~", "~", "~", "~", "~");
1779d1b5e5da828434388e486a388710d21e4306dae0Jesse Wilson        testUrlToUriMapping("\u007f", "%7F", "%7F", "%7F", "%7F");
1780d1b5e5da828434388e486a388710d21e4306dae0Jesse Wilson
1781d1b5e5da828434388e486a388710d21e4306dae0Jesse Wilson        // beyond ascii
1782d1b5e5da828434388e486a388710d21e4306dae0Jesse Wilson        testUrlToUriMapping("\u0080", "%C2%80", "%C2%80", "%C2%80", "%C2%80");
1783d1b5e5da828434388e486a388710d21e4306dae0Jesse Wilson        testUrlToUriMapping("\u20ac", "\u20ac", "\u20ac", "\u20ac", "\u20ac");
178432559028b14b9b321b10eede050afd554a376569Jesse Wilson        testUrlToUriMapping("\ud842\udf9f",
178532559028b14b9b321b10eede050afd554a376569Jesse Wilson                "\ud842\udf9f", "\ud842\udf9f", "\ud842\udf9f", "\ud842\udf9f");
1786d1b5e5da828434388e486a388710d21e4306dae0Jesse Wilson    }
1787d1b5e5da828434388e486a388710d21e4306dae0Jesse Wilson
1788d1b5e5da828434388e486a388710d21e4306dae0Jesse Wilson    public void testLenientUrlToUriNul() throws Exception {
1789d1b5e5da828434388e486a388710d21e4306dae0Jesse Wilson        testUrlToUriMapping("\u0000", "%00", "%00", "%00", "%00"); // RI fails this
1790d1b5e5da828434388e486a388710d21e4306dae0Jesse Wilson    }
1791d1b5e5da828434388e486a388710d21e4306dae0Jesse Wilson
1792d1b5e5da828434388e486a388710d21e4306dae0Jesse Wilson    private void testUrlToUriMapping(String string, String asAuthority, String asFile,
1793d1b5e5da828434388e486a388710d21e4306dae0Jesse Wilson            String asQuery, String asFragment) throws Exception {
1794d1b5e5da828434388e486a388710d21e4306dae0Jesse Wilson        if (asAuthority != null) {
1795d1b5e5da828434388e486a388710d21e4306dae0Jesse Wilson            assertEquals("http://host" + asAuthority + ".tld/",
1796d1b5e5da828434388e486a388710d21e4306dae0Jesse Wilson                    backdoorUrlToUri(new URL("http://host" + string + ".tld/")).toString());
1797d1b5e5da828434388e486a388710d21e4306dae0Jesse Wilson        }
1798d1b5e5da828434388e486a388710d21e4306dae0Jesse Wilson        if (asFile != null) {
1799d1b5e5da828434388e486a388710d21e4306dae0Jesse Wilson            assertEquals("http://host.tld/file" + asFile + "/",
1800d1b5e5da828434388e486a388710d21e4306dae0Jesse Wilson                    backdoorUrlToUri(new URL("http://host.tld/file" + string + "/")).toString());
1801d1b5e5da828434388e486a388710d21e4306dae0Jesse Wilson        }
1802d1b5e5da828434388e486a388710d21e4306dae0Jesse Wilson        if (asQuery != null) {
1803d1b5e5da828434388e486a388710d21e4306dae0Jesse Wilson            assertEquals("http://host.tld/file?q" + asQuery + "=x",
1804d1b5e5da828434388e486a388710d21e4306dae0Jesse Wilson                    backdoorUrlToUri(new URL("http://host.tld/file?q" + string + "=x")).toString());
1805d1b5e5da828434388e486a388710d21e4306dae0Jesse Wilson        }
1806d1b5e5da828434388e486a388710d21e4306dae0Jesse Wilson        assertEquals("http://host.tld/file#" + asFragment + "-x",
1807d1b5e5da828434388e486a388710d21e4306dae0Jesse Wilson                backdoorUrlToUri(new URL("http://host.tld/file#" + asFragment + "-x")).toString());
1808d1b5e5da828434388e486a388710d21e4306dae0Jesse Wilson    }
1809b7f4d6c3968c372767b2510f38a3d506067aced6Jesse Wilson
1810d1b5e5da828434388e486a388710d21e4306dae0Jesse Wilson    /**
1811d1b5e5da828434388e486a388710d21e4306dae0Jesse Wilson     * Exercises HttpURLConnection to convert URL to a URI. Unlike URL#toURI,
1812d1b5e5da828434388e486a388710d21e4306dae0Jesse Wilson     * HttpURLConnection recovers from URLs with unescaped but unsupported URI
1813d1b5e5da828434388e486a388710d21e4306dae0Jesse Wilson     * characters like '{' and '|' by escaping these characters.
1814d1b5e5da828434388e486a388710d21e4306dae0Jesse Wilson     */
1815d1b5e5da828434388e486a388710d21e4306dae0Jesse Wilson    private URI backdoorUrlToUri(URL url) throws Exception {
1816d1b5e5da828434388e486a388710d21e4306dae0Jesse Wilson        final AtomicReference<URI> uriReference = new AtomicReference<URI>();
1817d1b5e5da828434388e486a388710d21e4306dae0Jesse Wilson
1818d1b5e5da828434388e486a388710d21e4306dae0Jesse Wilson        ResponseCache.setDefault(new ResponseCache() {
1819d1b5e5da828434388e486a388710d21e4306dae0Jesse Wilson            @Override public CacheRequest put(URI uri, URLConnection connection) throws IOException {
1820d1b5e5da828434388e486a388710d21e4306dae0Jesse Wilson                return null;
1821d1b5e5da828434388e486a388710d21e4306dae0Jesse Wilson            }
1822d1b5e5da828434388e486a388710d21e4306dae0Jesse Wilson            @Override public CacheResponse get(URI uri, String requestMethod,
1823d1b5e5da828434388e486a388710d21e4306dae0Jesse Wilson                    Map<String, List<String>> requestHeaders) throws IOException {
1824d1b5e5da828434388e486a388710d21e4306dae0Jesse Wilson                uriReference.set(uri);
1825d1b5e5da828434388e486a388710d21e4306dae0Jesse Wilson                throw new UnsupportedOperationException();
1826d1b5e5da828434388e486a388710d21e4306dae0Jesse Wilson            }
1827d1b5e5da828434388e486a388710d21e4306dae0Jesse Wilson        });
1828d1b5e5da828434388e486a388710d21e4306dae0Jesse Wilson
1829d1b5e5da828434388e486a388710d21e4306dae0Jesse Wilson        try {
1830d1b5e5da828434388e486a388710d21e4306dae0Jesse Wilson            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
1831d1b5e5da828434388e486a388710d21e4306dae0Jesse Wilson            connection.getResponseCode();
1832d1b5e5da828434388e486a388710d21e4306dae0Jesse Wilson        } catch (Exception expected) {
1833d1b5e5da828434388e486a388710d21e4306dae0Jesse Wilson        }
1834d1b5e5da828434388e486a388710d21e4306dae0Jesse Wilson
1835d1b5e5da828434388e486a388710d21e4306dae0Jesse Wilson        return uriReference.get();
1836b7f4d6c3968c372767b2510f38a3d506067aced6Jesse Wilson    }
1837b7f4d6c3968c372767b2510f38a3d506067aced6Jesse Wilson
1838afd9b157f467b7c4f2f0b5592dca72f18d844602Jesse Wilson    /**
1839afd9b157f467b7c4f2f0b5592dca72f18d844602Jesse Wilson     * Don't explode if the cache returns a null body. http://b/3373699
1840afd9b157f467b7c4f2f0b5592dca72f18d844602Jesse Wilson     */
1841afd9b157f467b7c4f2f0b5592dca72f18d844602Jesse Wilson    public void testResponseCacheReturnsNullOutputStream() throws Exception {
1842afd9b157f467b7c4f2f0b5592dca72f18d844602Jesse Wilson        final AtomicBoolean aborted = new AtomicBoolean();
1843afd9b157f467b7c4f2f0b5592dca72f18d844602Jesse Wilson        ResponseCache.setDefault(new ResponseCache() {
1844afd9b157f467b7c4f2f0b5592dca72f18d844602Jesse Wilson            @Override public CacheResponse get(URI uri, String requestMethod,
1845afd9b157f467b7c4f2f0b5592dca72f18d844602Jesse Wilson                    Map<String, List<String>> requestHeaders) throws IOException {
1846afd9b157f467b7c4f2f0b5592dca72f18d844602Jesse Wilson                return null;
1847afd9b157f467b7c4f2f0b5592dca72f18d844602Jesse Wilson            }
1848afd9b157f467b7c4f2f0b5592dca72f18d844602Jesse Wilson            @Override public CacheRequest put(URI uri, URLConnection connection) throws IOException {
1849afd9b157f467b7c4f2f0b5592dca72f18d844602Jesse Wilson                return new CacheRequest() {
1850afd9b157f467b7c4f2f0b5592dca72f18d844602Jesse Wilson                    @Override public void abort() {
1851afd9b157f467b7c4f2f0b5592dca72f18d844602Jesse Wilson                        aborted.set(true);
1852afd9b157f467b7c4f2f0b5592dca72f18d844602Jesse Wilson                    }
1853afd9b157f467b7c4f2f0b5592dca72f18d844602Jesse Wilson                    @Override public OutputStream getBody() throws IOException {
1854afd9b157f467b7c4f2f0b5592dca72f18d844602Jesse Wilson                        return null;
1855afd9b157f467b7c4f2f0b5592dca72f18d844602Jesse Wilson                    }
1856afd9b157f467b7c4f2f0b5592dca72f18d844602Jesse Wilson                };
1857afd9b157f467b7c4f2f0b5592dca72f18d844602Jesse Wilson            }
1858afd9b157f467b7c4f2f0b5592dca72f18d844602Jesse Wilson        });
1859afd9b157f467b7c4f2f0b5592dca72f18d844602Jesse Wilson
1860afd9b157f467b7c4f2f0b5592dca72f18d844602Jesse Wilson        server.enqueue(new MockResponse().setBody("abcdef"));
1861afd9b157f467b7c4f2f0b5592dca72f18d844602Jesse Wilson        server.play();
1862afd9b157f467b7c4f2f0b5592dca72f18d844602Jesse Wilson
1863afd9b157f467b7c4f2f0b5592dca72f18d844602Jesse Wilson        HttpURLConnection connection = (HttpURLConnection) server.getUrl("/").openConnection();
1864afd9b157f467b7c4f2f0b5592dca72f18d844602Jesse Wilson        InputStream in = connection.getInputStream();
1865afd9b157f467b7c4f2f0b5592dca72f18d844602Jesse Wilson        assertEquals("abc", readAscii(in, 3));
1866afd9b157f467b7c4f2f0b5592dca72f18d844602Jesse Wilson        in.close();
1867afd9b157f467b7c4f2f0b5592dca72f18d844602Jesse Wilson        assertFalse(aborted.get()); // The best behavior is ambiguous, but RI 6 doesn't abort here
1868afd9b157f467b7c4f2f0b5592dca72f18d844602Jesse Wilson    }
1869d1b5e5da828434388e486a388710d21e4306dae0Jesse Wilson
18705e8b5a55eda914b67c62b4e77152922d5c77eb68Jesse Wilson
18715e8b5a55eda914b67c62b4e77152922d5c77eb68Jesse Wilson    /**
18725e8b5a55eda914b67c62b4e77152922d5c77eb68Jesse Wilson     * http://code.google.com/p/android/issues/detail?id=14562
18735e8b5a55eda914b67c62b4e77152922d5c77eb68Jesse Wilson     */
18745e8b5a55eda914b67c62b4e77152922d5c77eb68Jesse Wilson    public void testReadAfterLastByte() throws Exception {
18755e8b5a55eda914b67c62b4e77152922d5c77eb68Jesse Wilson        server.enqueue(new MockResponse()
18765e8b5a55eda914b67c62b4e77152922d5c77eb68Jesse Wilson                .setBody("ABC")
18775e8b5a55eda914b67c62b4e77152922d5c77eb68Jesse Wilson                .clearHeaders()
18785e8b5a55eda914b67c62b4e77152922d5c77eb68Jesse Wilson                .addHeader("Connection: close")
18795e8b5a55eda914b67c62b4e77152922d5c77eb68Jesse Wilson                .setSocketPolicy(SocketPolicy.DISCONNECT_AT_END));
18805e8b5a55eda914b67c62b4e77152922d5c77eb68Jesse Wilson        server.play();
18815e8b5a55eda914b67c62b4e77152922d5c77eb68Jesse Wilson
18825e8b5a55eda914b67c62b4e77152922d5c77eb68Jesse Wilson        HttpURLConnection connection = (HttpURLConnection) server.getUrl("/").openConnection();
18835e8b5a55eda914b67c62b4e77152922d5c77eb68Jesse Wilson        InputStream in = connection.getInputStream();
18845e8b5a55eda914b67c62b4e77152922d5c77eb68Jesse Wilson        assertEquals("ABC", readAscii(in, 3));
18855e8b5a55eda914b67c62b4e77152922d5c77eb68Jesse Wilson        assertEquals(-1, in.read());
1886bc4c79c6a2059003f695f7ad204de36700e8d701Jesse Wilson        assertEquals(-1, in.read()); // throws IOException in Gingerbread
1887bc4c79c6a2059003f695f7ad204de36700e8d701Jesse Wilson    }
1888bc4c79c6a2059003f695f7ad204de36700e8d701Jesse Wilson
1889ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson    public void testGetContent() throws Exception {
1890ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson        server.enqueue(new MockResponse().setBody("A"));
1891ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson        server.play();
1892ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson        HttpURLConnection connection = (HttpURLConnection) server.getUrl("/").openConnection();
1893ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson        InputStream in = (InputStream) connection.getContent();
1894ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson        assertEquals("A", readAscii(in, Integer.MAX_VALUE));
1895ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson    }
1896ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson
1897ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson    public void testGetContentOfType() throws Exception {
1898ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson        server.enqueue(new MockResponse().setBody("A"));
1899ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson        server.play();
1900ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson        HttpURLConnection connection = (HttpURLConnection) server.getUrl("/").openConnection();
1901ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson        try {
1902ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson            connection.getContent(null);
1903ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson            fail();
1904ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson        } catch (NullPointerException expected) {
1905ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson        }
1906ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson        try {
1907ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson            connection.getContent(new Class[] { null });
1908ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson            fail();
1909ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson        } catch (NullPointerException expected) {
1910ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson        }
1911ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson        assertNull(connection.getContent(new Class[] { getClass() }));
1912ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson        connection.disconnect();
1913ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson    }
1914ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson
1915ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson    public void testGetOutputStreamOnGetFails() throws Exception {
1916ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson        server.enqueue(new MockResponse());
1917ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson        server.play();
1918ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson        HttpURLConnection connection = (HttpURLConnection) server.getUrl("/").openConnection();
1919ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson        try {
1920ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson            connection.getOutputStream();
1921ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson            fail();
1922ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson        } catch (ProtocolException expected) {
1923ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson        }
1924ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson    }
1925ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson
1926ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson    public void testGetOutputAfterGetInputStreamFails() throws Exception {
1927ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson        server.enqueue(new MockResponse());
1928ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson        server.play();
1929ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson        HttpURLConnection connection = (HttpURLConnection) server.getUrl("/").openConnection();
1930ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson        connection.setDoOutput(true);
1931ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson        try {
1932ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson            connection.getInputStream();
1933ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson            connection.getOutputStream();
1934ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson            fail();
1935ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson        } catch (ProtocolException expected) {
1936ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson        }
1937ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson    }
1938ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson
1939ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson    public void testSetDoOutputOrDoInputAfterConnectFails() throws Exception {
1940ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson        server.enqueue(new MockResponse());
1941ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson        server.play();
1942ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson        HttpURLConnection connection = (HttpURLConnection) server.getUrl("/").openConnection();
1943ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson        connection.connect();
1944ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson        try {
1945ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson            connection.setDoOutput(true);
1946ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson            fail();
1947ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson        } catch (IllegalStateException expected) {
1948ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson        }
1949ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson        try {
1950ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson            connection.setDoInput(true);
1951ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson            fail();
1952ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson        } catch (IllegalStateException expected) {
1953ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson        }
1954ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson        connection.disconnect();
1955ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson    }
1956ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson
1957ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson    public void testClientSendsContentLength() throws Exception {
1958ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson        server.enqueue(new MockResponse().setBody("A"));
1959ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson        server.play();
1960ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson        HttpURLConnection connection = (HttpURLConnection) server.getUrl("/").openConnection();
1961ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson        connection.setDoOutput(true);
1962ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson        OutputStream out = connection.getOutputStream();
1963ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson        out.write(new byte[] { 'A', 'B', 'C' });
1964ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson        out.close();
1965ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson        assertEquals("A", readAscii(connection.getInputStream(), Integer.MAX_VALUE));
1966ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson        RecordedRequest request = server.takeRequest();
1967ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson        assertContains(request.getHeaders(), "Content-Length: 3");
1968ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson    }
1969ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson
1970ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson    public void testGetContentLengthConnects() throws Exception {
1971ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson        server.enqueue(new MockResponse().setBody("ABC"));
1972ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson        server.play();
1973ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson        HttpURLConnection connection = (HttpURLConnection) server.getUrl("/").openConnection();
1974ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson        assertEquals(3, connection.getContentLength());
1975ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson        connection.disconnect();
1976ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson    }
1977ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson
1978ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson    public void testGetContentTypeConnects() throws Exception {
1979ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson        server.enqueue(new MockResponse()
1980ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson                .addHeader("Content-Type: text/plain")
1981ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson                .setBody("ABC"));
1982ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson        server.play();
1983ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson        HttpURLConnection connection = (HttpURLConnection) server.getUrl("/").openConnection();
1984ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson        assertEquals("text/plain", connection.getContentType());
1985ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson        connection.disconnect();
1986ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson    }
1987ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson
1988ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson    public void testGetContentEncodingConnects() throws Exception {
1989ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson        server.enqueue(new MockResponse()
1990ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson                .addHeader("Content-Encoding: identity")
1991ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson                .setBody("ABC"));
1992ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson        server.play();
1993ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson        HttpURLConnection connection = (HttpURLConnection) server.getUrl("/").openConnection();
1994ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson        assertEquals("identity", connection.getContentEncoding());
1995ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson        connection.disconnect();
1996ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson    }
1997ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson
19985292410e4ebf7fb5149eefd2f52fcb94c46690a6Jesse Wilson    // http://b/4361656
19995292410e4ebf7fb5149eefd2f52fcb94c46690a6Jesse Wilson    public void testUrlContainsQueryButNoPath() throws Exception {
20005292410e4ebf7fb5149eefd2f52fcb94c46690a6Jesse Wilson        server.enqueue(new MockResponse().setBody("A"));
20015292410e4ebf7fb5149eefd2f52fcb94c46690a6Jesse Wilson        server.play();
20025292410e4ebf7fb5149eefd2f52fcb94c46690a6Jesse Wilson        URL url = new URL("http", server.getHostName(), server.getPort(), "?query");
20035292410e4ebf7fb5149eefd2f52fcb94c46690a6Jesse Wilson        assertEquals("A", readAscii(url.openConnection().getInputStream(), Integer.MAX_VALUE));
20045292410e4ebf7fb5149eefd2f52fcb94c46690a6Jesse Wilson        RecordedRequest request = server.takeRequest();
20055292410e4ebf7fb5149eefd2f52fcb94c46690a6Jesse Wilson        assertEquals("GET /?query HTTP/1.1", request.getRequestLine());
20065292410e4ebf7fb5149eefd2f52fcb94c46690a6Jesse Wilson    }
20075292410e4ebf7fb5149eefd2f52fcb94c46690a6Jesse Wilson
200825a753691a80186cd4d7086b12c0e52225d95897Jesse Wilson    // http://code.google.com/p/android/issues/detail?id=20442
200925a753691a80186cd4d7086b12c0e52225d95897Jesse Wilson    public void testInputStreamAvailableWithChunkedEncoding() throws Exception {
201025a753691a80186cd4d7086b12c0e52225d95897Jesse Wilson        testInputStreamAvailable(TransferKind.CHUNKED);
201125a753691a80186cd4d7086b12c0e52225d95897Jesse Wilson    }
201225a753691a80186cd4d7086b12c0e52225d95897Jesse Wilson
201325a753691a80186cd4d7086b12c0e52225d95897Jesse Wilson    public void testInputStreamAvailableWithContentLengthHeader() throws Exception {
201425a753691a80186cd4d7086b12c0e52225d95897Jesse Wilson        testInputStreamAvailable(TransferKind.FIXED_LENGTH);
201525a753691a80186cd4d7086b12c0e52225d95897Jesse Wilson    }
201625a753691a80186cd4d7086b12c0e52225d95897Jesse Wilson
201725a753691a80186cd4d7086b12c0e52225d95897Jesse Wilson    public void testInputStreamAvailableWithNoLengthHeaders() throws Exception {
201825a753691a80186cd4d7086b12c0e52225d95897Jesse Wilson        testInputStreamAvailable(TransferKind.END_OF_STREAM);
201925a753691a80186cd4d7086b12c0e52225d95897Jesse Wilson    }
202025a753691a80186cd4d7086b12c0e52225d95897Jesse Wilson
202125a753691a80186cd4d7086b12c0e52225d95897Jesse Wilson    private void testInputStreamAvailable(TransferKind transferKind) throws IOException {
202225a753691a80186cd4d7086b12c0e52225d95897Jesse Wilson        String body = "ABCDEFGH";
202325a753691a80186cd4d7086b12c0e52225d95897Jesse Wilson        MockResponse response = new MockResponse();
202425a753691a80186cd4d7086b12c0e52225d95897Jesse Wilson        transferKind.setBody(response, body, 4);
202525a753691a80186cd4d7086b12c0e52225d95897Jesse Wilson        server.enqueue(response);
202625a753691a80186cd4d7086b12c0e52225d95897Jesse Wilson        server.play();
202725a753691a80186cd4d7086b12c0e52225d95897Jesse Wilson        URLConnection connection = server.getUrl("/").openConnection();
202825a753691a80186cd4d7086b12c0e52225d95897Jesse Wilson        InputStream in = connection.getInputStream();
202925a753691a80186cd4d7086b12c0e52225d95897Jesse Wilson        for (int i = 0; i < body.length(); i++) {
203025a753691a80186cd4d7086b12c0e52225d95897Jesse Wilson            assertTrue(in.available() >= 0);
203125a753691a80186cd4d7086b12c0e52225d95897Jesse Wilson            assertEquals(body.charAt(i), in.read());
203225a753691a80186cd4d7086b12c0e52225d95897Jesse Wilson        }
203325a753691a80186cd4d7086b12c0e52225d95897Jesse Wilson        assertEquals(0, in.available());
203425a753691a80186cd4d7086b12c0e52225d95897Jesse Wilson        assertEquals(-1, in.read());
203525a753691a80186cd4d7086b12c0e52225d95897Jesse Wilson    }
203625a753691a80186cd4d7086b12c0e52225d95897Jesse Wilson
2037d0d626655f1d452070d3116678037e8759f807f4Jesse Wilson    // http://code.google.com/p/android/issues/detail?id=16895
2038d0d626655f1d452070d3116678037e8759f807f4Jesse Wilson    public void testUrlWithSpaceInHost() throws Exception {
2039d0d626655f1d452070d3116678037e8759f807f4Jesse Wilson        URLConnection urlConnection = new URL("http://and roid.com/").openConnection();
2040d0d626655f1d452070d3116678037e8759f807f4Jesse Wilson        try {
2041d0d626655f1d452070d3116678037e8759f807f4Jesse Wilson            urlConnection.getInputStream();
2042d0d626655f1d452070d3116678037e8759f807f4Jesse Wilson            fail();
2043d0d626655f1d452070d3116678037e8759f807f4Jesse Wilson        } catch (UnknownHostException expected) {
2044d0d626655f1d452070d3116678037e8759f807f4Jesse Wilson        }
2045d0d626655f1d452070d3116678037e8759f807f4Jesse Wilson    }
2046d0d626655f1d452070d3116678037e8759f807f4Jesse Wilson
2047d0d626655f1d452070d3116678037e8759f807f4Jesse Wilson    public void testUrlWithSpaceInHostViaHttpProxy() throws Exception {
2048d0d626655f1d452070d3116678037e8759f807f4Jesse Wilson        server.enqueue(new MockResponse());
2049d0d626655f1d452070d3116678037e8759f807f4Jesse Wilson        server.play();
2050d0d626655f1d452070d3116678037e8759f807f4Jesse Wilson        URLConnection urlConnection = new URL("http://and roid.com/")
2051d0d626655f1d452070d3116678037e8759f807f4Jesse Wilson                .openConnection(server.toProxyAddress());
2052d0d626655f1d452070d3116678037e8759f807f4Jesse Wilson        try {
2053d0d626655f1d452070d3116678037e8759f807f4Jesse Wilson            urlConnection.getInputStream();
2054d0d626655f1d452070d3116678037e8759f807f4Jesse Wilson            fail(); // the RI makes a bogus proxy request for "GET http://and roid.com/ HTTP/1.1"
2055d0d626655f1d452070d3116678037e8759f807f4Jesse Wilson        } catch (UnknownHostException expected) {
2056d0d626655f1d452070d3116678037e8759f807f4Jesse Wilson        }
2057d0d626655f1d452070d3116678037e8759f807f4Jesse Wilson    }
2058d0d626655f1d452070d3116678037e8759f807f4Jesse Wilson
2059abe4e615f473b387b1c00a738062a7c428f05a33Jesse Wilson    public void testSslFallback() throws Exception {
2060abe4e615f473b387b1c00a738062a7c428f05a33Jesse Wilson        TestSSLContext testSSLContext = TestSSLContext.create();
2061abe4e615f473b387b1c00a738062a7c428f05a33Jesse Wilson        server.useHttps(testSSLContext.serverContext.getSocketFactory(), false);
2062abe4e615f473b387b1c00a738062a7c428f05a33Jesse Wilson        server.enqueue(new MockResponse().setSocketPolicy(SocketPolicy.FAIL_HANDSHAKE));
2063abe4e615f473b387b1c00a738062a7c428f05a33Jesse Wilson        server.enqueue(new MockResponse().setBody("This required a 2nd handshake"));
2064abe4e615f473b387b1c00a738062a7c428f05a33Jesse Wilson        server.play();
2065abe4e615f473b387b1c00a738062a7c428f05a33Jesse Wilson
2066abe4e615f473b387b1c00a738062a7c428f05a33Jesse Wilson        HttpsURLConnection connection = (HttpsURLConnection) server.getUrl("/").openConnection();
2067abe4e615f473b387b1c00a738062a7c428f05a33Jesse Wilson        connection.setSSLSocketFactory(testSSLContext.clientContext.getSocketFactory());
2068abe4e615f473b387b1c00a738062a7c428f05a33Jesse Wilson        assertEquals("This required a 2nd handshake",
2069abe4e615f473b387b1c00a738062a7c428f05a33Jesse Wilson                readAscii(connection.getInputStream(), Integer.MAX_VALUE));
2070abe4e615f473b387b1c00a738062a7c428f05a33Jesse Wilson
2071abe4e615f473b387b1c00a738062a7c428f05a33Jesse Wilson        RecordedRequest first = server.takeRequest();
2072abe4e615f473b387b1c00a738062a7c428f05a33Jesse Wilson        assertEquals(0, first.getSequenceNumber());
2073abe4e615f473b387b1c00a738062a7c428f05a33Jesse Wilson        RecordedRequest retry = server.takeRequest();
2074abe4e615f473b387b1c00a738062a7c428f05a33Jesse Wilson        assertEquals(0, retry.getSequenceNumber());
2075abe4e615f473b387b1c00a738062a7c428f05a33Jesse Wilson        assertEquals("SSLv3", retry.getSslProtocol());
2076abe4e615f473b387b1c00a738062a7c428f05a33Jesse Wilson    }
2077abe4e615f473b387b1c00a738062a7c428f05a33Jesse Wilson
2078a468471e8ccc2f642d5b2ae3c75873a74267ece2Jesse Wilson    public void testInspectSslBeforeConnect() throws Exception {
2079a468471e8ccc2f642d5b2ae3c75873a74267ece2Jesse Wilson        TestSSLContext testSSLContext = TestSSLContext.create();
2080a468471e8ccc2f642d5b2ae3c75873a74267ece2Jesse Wilson        server.useHttps(testSSLContext.serverContext.getSocketFactory(), false);
2081a468471e8ccc2f642d5b2ae3c75873a74267ece2Jesse Wilson        server.enqueue(new MockResponse());
2082a468471e8ccc2f642d5b2ae3c75873a74267ece2Jesse Wilson        server.play();
2083a468471e8ccc2f642d5b2ae3c75873a74267ece2Jesse Wilson
2084a468471e8ccc2f642d5b2ae3c75873a74267ece2Jesse Wilson        HttpsURLConnection connection = (HttpsURLConnection) server.getUrl("/").openConnection();
2085a468471e8ccc2f642d5b2ae3c75873a74267ece2Jesse Wilson        connection.setSSLSocketFactory(testSSLContext.clientContext.getSocketFactory());
2086a468471e8ccc2f642d5b2ae3c75873a74267ece2Jesse Wilson        assertNotNull(connection.getHostnameVerifier());
2087a468471e8ccc2f642d5b2ae3c75873a74267ece2Jesse Wilson        try {
2088a468471e8ccc2f642d5b2ae3c75873a74267ece2Jesse Wilson            connection.getLocalCertificates();
2089a468471e8ccc2f642d5b2ae3c75873a74267ece2Jesse Wilson            fail();
2090a468471e8ccc2f642d5b2ae3c75873a74267ece2Jesse Wilson        } catch (IllegalStateException expected) {
2091a468471e8ccc2f642d5b2ae3c75873a74267ece2Jesse Wilson        }
2092a468471e8ccc2f642d5b2ae3c75873a74267ece2Jesse Wilson        try {
2093a468471e8ccc2f642d5b2ae3c75873a74267ece2Jesse Wilson            connection.getServerCertificates();
2094a468471e8ccc2f642d5b2ae3c75873a74267ece2Jesse Wilson            fail();
2095a468471e8ccc2f642d5b2ae3c75873a74267ece2Jesse Wilson        } catch (IllegalStateException expected) {
2096a468471e8ccc2f642d5b2ae3c75873a74267ece2Jesse Wilson        }
2097a468471e8ccc2f642d5b2ae3c75873a74267ece2Jesse Wilson        try {
2098a468471e8ccc2f642d5b2ae3c75873a74267ece2Jesse Wilson            connection.getCipherSuite();
2099a468471e8ccc2f642d5b2ae3c75873a74267ece2Jesse Wilson            fail();
2100a468471e8ccc2f642d5b2ae3c75873a74267ece2Jesse Wilson        } catch (IllegalStateException expected) {
2101a468471e8ccc2f642d5b2ae3c75873a74267ece2Jesse Wilson        }
2102a468471e8ccc2f642d5b2ae3c75873a74267ece2Jesse Wilson        try {
2103a468471e8ccc2f642d5b2ae3c75873a74267ece2Jesse Wilson            connection.getPeerPrincipal();
2104a468471e8ccc2f642d5b2ae3c75873a74267ece2Jesse Wilson            fail();
2105a468471e8ccc2f642d5b2ae3c75873a74267ece2Jesse Wilson        } catch (IllegalStateException expected) {
2106a468471e8ccc2f642d5b2ae3c75873a74267ece2Jesse Wilson        }
2107a468471e8ccc2f642d5b2ae3c75873a74267ece2Jesse Wilson    }
2108a468471e8ccc2f642d5b2ae3c75873a74267ece2Jesse Wilson
2109a468471e8ccc2f642d5b2ae3c75873a74267ece2Jesse Wilson    /**
2110a468471e8ccc2f642d5b2ae3c75873a74267ece2Jesse Wilson     * Test that we can inspect the SSL session after connect().
2111a468471e8ccc2f642d5b2ae3c75873a74267ece2Jesse Wilson     * http://code.google.com/p/android/issues/detail?id=24431
2112a468471e8ccc2f642d5b2ae3c75873a74267ece2Jesse Wilson     */
2113a468471e8ccc2f642d5b2ae3c75873a74267ece2Jesse Wilson    public void testInspectSslAfterConnect() throws Exception {
2114a468471e8ccc2f642d5b2ae3c75873a74267ece2Jesse Wilson        TestSSLContext testSSLContext = TestSSLContext.create();
2115a468471e8ccc2f642d5b2ae3c75873a74267ece2Jesse Wilson        server.useHttps(testSSLContext.serverContext.getSocketFactory(), false);
2116a468471e8ccc2f642d5b2ae3c75873a74267ece2Jesse Wilson        server.enqueue(new MockResponse());
2117a468471e8ccc2f642d5b2ae3c75873a74267ece2Jesse Wilson        server.play();
2118a468471e8ccc2f642d5b2ae3c75873a74267ece2Jesse Wilson
2119a468471e8ccc2f642d5b2ae3c75873a74267ece2Jesse Wilson        HttpsURLConnection connection = (HttpsURLConnection) server.getUrl("/").openConnection();
2120a468471e8ccc2f642d5b2ae3c75873a74267ece2Jesse Wilson        connection.setSSLSocketFactory(testSSLContext.clientContext.getSocketFactory());
2121a468471e8ccc2f642d5b2ae3c75873a74267ece2Jesse Wilson        connection.connect();
2122a468471e8ccc2f642d5b2ae3c75873a74267ece2Jesse Wilson        assertNotNull(connection.getHostnameVerifier());
2123a468471e8ccc2f642d5b2ae3c75873a74267ece2Jesse Wilson        assertNull(connection.getLocalCertificates());
2124a468471e8ccc2f642d5b2ae3c75873a74267ece2Jesse Wilson        assertNotNull(connection.getServerCertificates());
2125a468471e8ccc2f642d5b2ae3c75873a74267ece2Jesse Wilson        assertNotNull(connection.getCipherSuite());
2126a468471e8ccc2f642d5b2ae3c75873a74267ece2Jesse Wilson        assertNotNull(connection.getPeerPrincipal());
2127a468471e8ccc2f642d5b2ae3c75873a74267ece2Jesse Wilson    }
2128a468471e8ccc2f642d5b2ae3c75873a74267ece2Jesse Wilson
2129bc4c79c6a2059003f695f7ad204de36700e8d701Jesse Wilson    /**
21300c59055dd24e1659f85d9ff7e2148883f663bd62Jesse Wilson     * Returns a gzipped copy of {@code bytes}.
2131deb236fb06f2a14861e7d40dea959f181cd5cf28Jesse Wilson     */
2132deb236fb06f2a14861e7d40dea959f181cd5cf28Jesse Wilson    public byte[] gzip(byte[] bytes) throws IOException {
2133deb236fb06f2a14861e7d40dea959f181cd5cf28Jesse Wilson        ByteArrayOutputStream bytesOut = new ByteArrayOutputStream();
2134deb236fb06f2a14861e7d40dea959f181cd5cf28Jesse Wilson        OutputStream gzippedOut = new GZIPOutputStream(bytesOut);
2135deb236fb06f2a14861e7d40dea959f181cd5cf28Jesse Wilson        gzippedOut.write(bytes);
2136deb236fb06f2a14861e7d40dea959f181cd5cf28Jesse Wilson        gzippedOut.close();
2137deb236fb06f2a14861e7d40dea959f181cd5cf28Jesse Wilson        return bytesOut.toByteArray();
2138deb236fb06f2a14861e7d40dea959f181cd5cf28Jesse Wilson    }
2139deb236fb06f2a14861e7d40dea959f181cd5cf28Jesse Wilson
2140c8977f474b30c5f3807398859a6b16687af6fc7bJesse Wilson    /**
2141c8977f474b30c5f3807398859a6b16687af6fc7bJesse Wilson     * Reads at most {@code limit} characters from {@code in} and asserts that
2142c8977f474b30c5f3807398859a6b16687af6fc7bJesse Wilson     * content equals {@code expected}.
2143c8977f474b30c5f3807398859a6b16687af6fc7bJesse Wilson     */
2144c8977f474b30c5f3807398859a6b16687af6fc7bJesse Wilson    private void assertContent(String expected, URLConnection connection, int limit)
2145c8977f474b30c5f3807398859a6b16687af6fc7bJesse Wilson            throws IOException {
2146f02c695ed03e708623d9365dec26d533356ef2d0Brian Carlstrom        connection.connect();
214751e468abf2628ce964d3657042f3ac8f2c947504Jesse Wilson        assertEquals(expected, readAscii(connection.getInputStream(), limit));
2148c8977f474b30c5f3807398859a6b16687af6fc7bJesse Wilson        ((HttpURLConnection) connection).disconnect();
2149c8977f474b30c5f3807398859a6b16687af6fc7bJesse Wilson    }
2150c8977f474b30c5f3807398859a6b16687af6fc7bJesse Wilson
2151c8977f474b30c5f3807398859a6b16687af6fc7bJesse Wilson    private void assertContent(String expected, URLConnection connection) throws IOException {
2152c8977f474b30c5f3807398859a6b16687af6fc7bJesse Wilson        assertContent(expected, connection, Integer.MAX_VALUE);
2153c8977f474b30c5f3807398859a6b16687af6fc7bJesse Wilson    }
2154c8977f474b30c5f3807398859a6b16687af6fc7bJesse Wilson
215560476787f0e0f052366d8031c74e507ffd3d16a3Jesse Wilson    private void assertContains(List<String> headers, String header) {
215660476787f0e0f052366d8031c74e507ffd3d16a3Jesse Wilson        assertTrue(headers.toString(), headers.contains(header));
215760476787f0e0f052366d8031c74e507ffd3d16a3Jesse Wilson    }
215851e468abf2628ce964d3657042f3ac8f2c947504Jesse Wilson
2159ffd579b668428272b78f5c6c64f9c89766f37c1aJesse Wilson    private void assertContainsNoneMatching(List<String> headers, String pattern) {
2160ffd579b668428272b78f5c6c64f9c89766f37c1aJesse Wilson        for (String header : headers) {
2161ffd579b668428272b78f5c6c64f9c89766f37c1aJesse Wilson            if (header.matches(pattern)) {
2162ffd579b668428272b78f5c6c64f9c89766f37c1aJesse Wilson                fail("Header " + header + " matches " + pattern);
2163ffd579b668428272b78f5c6c64f9c89766f37c1aJesse Wilson            }
2164ffd579b668428272b78f5c6c64f9c89766f37c1aJesse Wilson        }
2165ffd579b668428272b78f5c6c64f9c89766f37c1aJesse Wilson    }
2166ffd579b668428272b78f5c6c64f9c89766f37c1aJesse Wilson
2167eafede536f2059bb6c869e7a5f07fd7ad9758e28Jesse Wilson    private Set<String> newSet(String... elements) {
216883a47d4d0c536e06fc53eda9d5a1a5d93f9accc6Jesse Wilson        return new HashSet<String>(Arrays.asList(elements));
216983a47d4d0c536e06fc53eda9d5a1a5d93f9accc6Jesse Wilson    }
217083a47d4d0c536e06fc53eda9d5a1a5d93f9accc6Jesse Wilson
217151e468abf2628ce964d3657042f3ac8f2c947504Jesse Wilson    enum TransferKind {
217251e468abf2628ce964d3657042f3ac8f2c947504Jesse Wilson        CHUNKED() {
2173deb236fb06f2a14861e7d40dea959f181cd5cf28Jesse Wilson            @Override void setBody(MockResponse response, byte[] content, int chunkSize)
217451e468abf2628ce964d3657042f3ac8f2c947504Jesse Wilson                    throws IOException {
217551e468abf2628ce964d3657042f3ac8f2c947504Jesse Wilson                response.setChunkedBody(content, chunkSize);
217651e468abf2628ce964d3657042f3ac8f2c947504Jesse Wilson            }
217751e468abf2628ce964d3657042f3ac8f2c947504Jesse Wilson        },
217851e468abf2628ce964d3657042f3ac8f2c947504Jesse Wilson        FIXED_LENGTH() {
2179deb236fb06f2a14861e7d40dea959f181cd5cf28Jesse Wilson            @Override void setBody(MockResponse response, byte[] content, int chunkSize) {
218051e468abf2628ce964d3657042f3ac8f2c947504Jesse Wilson                response.setBody(content);
218151e468abf2628ce964d3657042f3ac8f2c947504Jesse Wilson            }
218251e468abf2628ce964d3657042f3ac8f2c947504Jesse Wilson        },
218351e468abf2628ce964d3657042f3ac8f2c947504Jesse Wilson        END_OF_STREAM() {
2184deb236fb06f2a14861e7d40dea959f181cd5cf28Jesse Wilson            @Override void setBody(MockResponse response, byte[] content, int chunkSize) {
218551e468abf2628ce964d3657042f3ac8f2c947504Jesse Wilson                response.setBody(content);
2186e942f46f10bb9384a1b186b3d7b74f9704c57090Jesse Wilson                response.setSocketPolicy(DISCONNECT_AT_END);
218751e468abf2628ce964d3657042f3ac8f2c947504Jesse Wilson                for (Iterator<String> h = response.getHeaders().iterator(); h.hasNext(); ) {
218851e468abf2628ce964d3657042f3ac8f2c947504Jesse Wilson                    if (h.next().startsWith("Content-Length:")) {
218951e468abf2628ce964d3657042f3ac8f2c947504Jesse Wilson                        h.remove();
219051e468abf2628ce964d3657042f3ac8f2c947504Jesse Wilson                        break;
219151e468abf2628ce964d3657042f3ac8f2c947504Jesse Wilson                    }
219251e468abf2628ce964d3657042f3ac8f2c947504Jesse Wilson                }
219351e468abf2628ce964d3657042f3ac8f2c947504Jesse Wilson            }
219451e468abf2628ce964d3657042f3ac8f2c947504Jesse Wilson        };
219551e468abf2628ce964d3657042f3ac8f2c947504Jesse Wilson
2196deb236fb06f2a14861e7d40dea959f181cd5cf28Jesse Wilson        abstract void setBody(MockResponse response, byte[] content, int chunkSize)
219751e468abf2628ce964d3657042f3ac8f2c947504Jesse Wilson                throws IOException;
2198deb236fb06f2a14861e7d40dea959f181cd5cf28Jesse Wilson
2199deb236fb06f2a14861e7d40dea959f181cd5cf28Jesse Wilson        void setBody(MockResponse response, String content, int chunkSize) throws IOException {
2200deb236fb06f2a14861e7d40dea959f181cd5cf28Jesse Wilson            setBody(response, content.getBytes("UTF-8"), chunkSize);
2201deb236fb06f2a14861e7d40dea959f181cd5cf28Jesse Wilson        }
220251e468abf2628ce964d3657042f3ac8f2c947504Jesse Wilson    }
2203c0372d90016d241ac979faa6fa1731f30b6f2a03Jesse Wilson
2204984fcff696380abd6ea14e80030f9fd2d09dbad0Jesse Wilson    enum ProxyConfig {
2205f02c695ed03e708623d9365dec26d533356ef2d0Brian Carlstrom        NO_PROXY() {
2206f02c695ed03e708623d9365dec26d533356ef2d0Brian Carlstrom            @Override public HttpURLConnection connect(MockWebServer server, URL url)
2207f02c695ed03e708623d9365dec26d533356ef2d0Brian Carlstrom                    throws IOException {
2208f02c695ed03e708623d9365dec26d533356ef2d0Brian Carlstrom                return (HttpURLConnection) url.openConnection(Proxy.NO_PROXY);
2209f02c695ed03e708623d9365dec26d533356ef2d0Brian Carlstrom            }
2210f02c695ed03e708623d9365dec26d533356ef2d0Brian Carlstrom        },
2211f02c695ed03e708623d9365dec26d533356ef2d0Brian Carlstrom
2212984fcff696380abd6ea14e80030f9fd2d09dbad0Jesse Wilson        CREATE_ARG() {
2213984fcff696380abd6ea14e80030f9fd2d09dbad0Jesse Wilson            @Override public HttpURLConnection connect(MockWebServer server, URL url)
2214984fcff696380abd6ea14e80030f9fd2d09dbad0Jesse Wilson                    throws IOException {
2215984fcff696380abd6ea14e80030f9fd2d09dbad0Jesse Wilson                return (HttpURLConnection) url.openConnection(server.toProxyAddress());
2216984fcff696380abd6ea14e80030f9fd2d09dbad0Jesse Wilson            }
2217984fcff696380abd6ea14e80030f9fd2d09dbad0Jesse Wilson        },
2218984fcff696380abd6ea14e80030f9fd2d09dbad0Jesse Wilson
2219984fcff696380abd6ea14e80030f9fd2d09dbad0Jesse Wilson        PROXY_SYSTEM_PROPERTY() {
2220984fcff696380abd6ea14e80030f9fd2d09dbad0Jesse Wilson            @Override public HttpURLConnection connect(MockWebServer server, URL url)
2221984fcff696380abd6ea14e80030f9fd2d09dbad0Jesse Wilson                    throws IOException {
2222984fcff696380abd6ea14e80030f9fd2d09dbad0Jesse Wilson                System.setProperty("proxyHost", "localhost");
2223984fcff696380abd6ea14e80030f9fd2d09dbad0Jesse Wilson                System.setProperty("proxyPort", Integer.toString(server.getPort()));
2224984fcff696380abd6ea14e80030f9fd2d09dbad0Jesse Wilson                return (HttpURLConnection) url.openConnection();
2225984fcff696380abd6ea14e80030f9fd2d09dbad0Jesse Wilson            }
2226984fcff696380abd6ea14e80030f9fd2d09dbad0Jesse Wilson        },
2227984fcff696380abd6ea14e80030f9fd2d09dbad0Jesse Wilson
2228984fcff696380abd6ea14e80030f9fd2d09dbad0Jesse Wilson        HTTP_PROXY_SYSTEM_PROPERTY() {
2229984fcff696380abd6ea14e80030f9fd2d09dbad0Jesse Wilson            @Override public HttpURLConnection connect(MockWebServer server, URL url)
2230984fcff696380abd6ea14e80030f9fd2d09dbad0Jesse Wilson                    throws IOException {
2231984fcff696380abd6ea14e80030f9fd2d09dbad0Jesse Wilson                System.setProperty("http.proxyHost", "localhost");
2232984fcff696380abd6ea14e80030f9fd2d09dbad0Jesse Wilson                System.setProperty("http.proxyPort", Integer.toString(server.getPort()));
2233984fcff696380abd6ea14e80030f9fd2d09dbad0Jesse Wilson                return (HttpURLConnection) url.openConnection();
2234984fcff696380abd6ea14e80030f9fd2d09dbad0Jesse Wilson            }
2235984fcff696380abd6ea14e80030f9fd2d09dbad0Jesse Wilson        },
2236984fcff696380abd6ea14e80030f9fd2d09dbad0Jesse Wilson
2237984fcff696380abd6ea14e80030f9fd2d09dbad0Jesse Wilson        HTTPS_PROXY_SYSTEM_PROPERTY() {
2238984fcff696380abd6ea14e80030f9fd2d09dbad0Jesse Wilson            @Override public HttpURLConnection connect(MockWebServer server, URL url)
2239984fcff696380abd6ea14e80030f9fd2d09dbad0Jesse Wilson                    throws IOException {
2240984fcff696380abd6ea14e80030f9fd2d09dbad0Jesse Wilson                System.setProperty("https.proxyHost", "localhost");
2241984fcff696380abd6ea14e80030f9fd2d09dbad0Jesse Wilson                System.setProperty("https.proxyPort", Integer.toString(server.getPort()));
2242984fcff696380abd6ea14e80030f9fd2d09dbad0Jesse Wilson                return (HttpURLConnection) url.openConnection();
2243984fcff696380abd6ea14e80030f9fd2d09dbad0Jesse Wilson            }
2244984fcff696380abd6ea14e80030f9fd2d09dbad0Jesse Wilson        };
2245984fcff696380abd6ea14e80030f9fd2d09dbad0Jesse Wilson
2246984fcff696380abd6ea14e80030f9fd2d09dbad0Jesse Wilson        public abstract HttpURLConnection connect(MockWebServer server, URL url) throws IOException;
2247984fcff696380abd6ea14e80030f9fd2d09dbad0Jesse Wilson    }
2248984fcff696380abd6ea14e80030f9fd2d09dbad0Jesse Wilson
2249c0372d90016d241ac979faa6fa1731f30b6f2a03Jesse Wilson    private static class RecordingTrustManager implements X509TrustManager {
2250c0372d90016d241ac979faa6fa1731f30b6f2a03Jesse Wilson        private final List<String> calls = new ArrayList<String>();
2251c0372d90016d241ac979faa6fa1731f30b6f2a03Jesse Wilson
2252c0372d90016d241ac979faa6fa1731f30b6f2a03Jesse Wilson        public X509Certificate[] getAcceptedIssuers() {
2253c0372d90016d241ac979faa6fa1731f30b6f2a03Jesse Wilson            calls.add("getAcceptedIssuers");
2254c0372d90016d241ac979faa6fa1731f30b6f2a03Jesse Wilson            return new X509Certificate[] {};
2255c0372d90016d241ac979faa6fa1731f30b6f2a03Jesse Wilson        }
2256c0372d90016d241ac979faa6fa1731f30b6f2a03Jesse Wilson
2257c0372d90016d241ac979faa6fa1731f30b6f2a03Jesse Wilson        public void checkClientTrusted(X509Certificate[] chain, String authType)
2258c0372d90016d241ac979faa6fa1731f30b6f2a03Jesse Wilson                throws CertificateException {
2259c0372d90016d241ac979faa6fa1731f30b6f2a03Jesse Wilson            calls.add("checkClientTrusted " + certificatesToString(chain) + " " + authType);
2260c0372d90016d241ac979faa6fa1731f30b6f2a03Jesse Wilson        }
2261c0372d90016d241ac979faa6fa1731f30b6f2a03Jesse Wilson
2262c0372d90016d241ac979faa6fa1731f30b6f2a03Jesse Wilson        public void checkServerTrusted(X509Certificate[] chain, String authType)
2263c0372d90016d241ac979faa6fa1731f30b6f2a03Jesse Wilson                throws CertificateException {
2264c0372d90016d241ac979faa6fa1731f30b6f2a03Jesse Wilson            calls.add("checkServerTrusted " + certificatesToString(chain) + " " + authType);
2265c0372d90016d241ac979faa6fa1731f30b6f2a03Jesse Wilson        }
2266c0372d90016d241ac979faa6fa1731f30b6f2a03Jesse Wilson
2267c0372d90016d241ac979faa6fa1731f30b6f2a03Jesse Wilson        private String certificatesToString(X509Certificate[] certificates) {
2268c0372d90016d241ac979faa6fa1731f30b6f2a03Jesse Wilson            List<String> result = new ArrayList<String>();
2269c0372d90016d241ac979faa6fa1731f30b6f2a03Jesse Wilson            for (X509Certificate certificate : certificates) {
2270c0372d90016d241ac979faa6fa1731f30b6f2a03Jesse Wilson                result.add(certificate.getSubjectDN() + " " + certificate.getSerialNumber());
2271c0372d90016d241ac979faa6fa1731f30b6f2a03Jesse Wilson            }
2272c0372d90016d241ac979faa6fa1731f30b6f2a03Jesse Wilson            return result.toString();
2273c0372d90016d241ac979faa6fa1731f30b6f2a03Jesse Wilson        }
2274c0372d90016d241ac979faa6fa1731f30b6f2a03Jesse Wilson    }
2275c0372d90016d241ac979faa6fa1731f30b6f2a03Jesse Wilson
2276c0372d90016d241ac979faa6fa1731f30b6f2a03Jesse Wilson    private static class RecordingHostnameVerifier implements HostnameVerifier {
2277c0372d90016d241ac979faa6fa1731f30b6f2a03Jesse Wilson        private final List<String> calls = new ArrayList<String>();
2278c0372d90016d241ac979faa6fa1731f30b6f2a03Jesse Wilson
2279c0372d90016d241ac979faa6fa1731f30b6f2a03Jesse Wilson        public boolean verify(String hostname, SSLSession session) {
2280c0372d90016d241ac979faa6fa1731f30b6f2a03Jesse Wilson            calls.add("verify " + hostname);
2281c0372d90016d241ac979faa6fa1731f30b6f2a03Jesse Wilson            return true;
2282c0372d90016d241ac979faa6fa1731f30b6f2a03Jesse Wilson        }
2283c0372d90016d241ac979faa6fa1731f30b6f2a03Jesse Wilson    }
22845757cb35ad2e58d7accb7f5d3db6f2d5e72f097dJesse Wilson
22855757cb35ad2e58d7accb7f5d3db6f2d5e72f097dJesse Wilson    private static class SimpleAuthenticator extends Authenticator {
22865757cb35ad2e58d7accb7f5d3db6f2d5e72f097dJesse Wilson        /** base64("username:password") */
22875757cb35ad2e58d7accb7f5d3db6f2d5e72f097dJesse Wilson        private static final String BASE_64_CREDENTIALS = "dXNlcm5hbWU6cGFzc3dvcmQ=";
22885757cb35ad2e58d7accb7f5d3db6f2d5e72f097dJesse Wilson
22895757cb35ad2e58d7accb7f5d3db6f2d5e72f097dJesse Wilson        private String expectedPrompt;
22905757cb35ad2e58d7accb7f5d3db6f2d5e72f097dJesse Wilson        private RequestorType requestorType;
22915757cb35ad2e58d7accb7f5d3db6f2d5e72f097dJesse Wilson        private int requestingPort;
22925757cb35ad2e58d7accb7f5d3db6f2d5e72f097dJesse Wilson        private InetAddress requestingSite;
22935757cb35ad2e58d7accb7f5d3db6f2d5e72f097dJesse Wilson        private String requestingPrompt;
22945757cb35ad2e58d7accb7f5d3db6f2d5e72f097dJesse Wilson        private String requestingProtocol;
22955757cb35ad2e58d7accb7f5d3db6f2d5e72f097dJesse Wilson        private String requestingScheme;
22965757cb35ad2e58d7accb7f5d3db6f2d5e72f097dJesse Wilson
22975757cb35ad2e58d7accb7f5d3db6f2d5e72f097dJesse Wilson        protected PasswordAuthentication getPasswordAuthentication() {
22985757cb35ad2e58d7accb7f5d3db6f2d5e72f097dJesse Wilson            requestorType = getRequestorType();
22995757cb35ad2e58d7accb7f5d3db6f2d5e72f097dJesse Wilson            requestingPort = getRequestingPort();
23005757cb35ad2e58d7accb7f5d3db6f2d5e72f097dJesse Wilson            requestingSite = getRequestingSite();
23015757cb35ad2e58d7accb7f5d3db6f2d5e72f097dJesse Wilson            requestingPrompt = getRequestingPrompt();
23025757cb35ad2e58d7accb7f5d3db6f2d5e72f097dJesse Wilson            requestingProtocol = getRequestingProtocol();
23035757cb35ad2e58d7accb7f5d3db6f2d5e72f097dJesse Wilson            requestingScheme = getRequestingScheme();
23045757cb35ad2e58d7accb7f5d3db6f2d5e72f097dJesse Wilson            return (expectedPrompt == null || expectedPrompt.equals(requestingPrompt))
23055757cb35ad2e58d7accb7f5d3db6f2d5e72f097dJesse Wilson                    ? new PasswordAuthentication("username", "password".toCharArray())
23065757cb35ad2e58d7accb7f5d3db6f2d5e72f097dJesse Wilson                    : null;
23075757cb35ad2e58d7accb7f5d3db6f2d5e72f097dJesse Wilson        }
23085757cb35ad2e58d7accb7f5d3db6f2d5e72f097dJesse Wilson    }
2309e40c9e3935a5024c0f3ebfb3f1441fcd5c48ed86Elliott Hughes}
2310