URLConnectionTest.java revision 5757cb35ad2e58d7accb7f5d3db6f2d5e72f097d
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());
45260476787f0e0f052366d8031c74e507ffd3d16a3Jesse Wilson    }
45360476787f0e0f052366d8031c74e507ffd3d16a3Jesse Wilson
454096aac7b8a607d3da237900f52cab1c5066bf992Jesse Wilson    public void testConnectViaHttpsReusingConnections() throws IOException, InterruptedException {
455096aac7b8a607d3da237900f52cab1c5066bf992Jesse Wilson        TestSSLContext testSSLContext = TestSSLContext.create();
456096aac7b8a607d3da237900f52cab1c5066bf992Jesse Wilson
457059dbc04218144f985b20a228bbe98139d400d0cBrian Carlstrom        server.useHttps(testSSLContext.serverContext.getSocketFactory(), false);
458096aac7b8a607d3da237900f52cab1c5066bf992Jesse Wilson        server.enqueue(new MockResponse().setBody("this response comes via HTTPS"));
459096aac7b8a607d3da237900f52cab1c5066bf992Jesse Wilson        server.enqueue(new MockResponse().setBody("another response via HTTPS"));
460096aac7b8a607d3da237900f52cab1c5066bf992Jesse Wilson        server.play();
461096aac7b8a607d3da237900f52cab1c5066bf992Jesse Wilson
462b7155fd57239e986bbaba254a91aeb9600d60305Jesse Wilson        HttpsURLConnection connection = (HttpsURLConnection) server.getUrl("/").openConnection();
463b7155fd57239e986bbaba254a91aeb9600d60305Jesse Wilson        connection.setSSLSocketFactory(testSSLContext.clientContext.getSocketFactory());
464b7155fd57239e986bbaba254a91aeb9600d60305Jesse Wilson        assertContent("this response comes via HTTPS", connection);
465b7155fd57239e986bbaba254a91aeb9600d60305Jesse Wilson
466b7155fd57239e986bbaba254a91aeb9600d60305Jesse Wilson        connection = (HttpsURLConnection) server.getUrl("/").openConnection();
467b7155fd57239e986bbaba254a91aeb9600d60305Jesse Wilson        connection.setSSLSocketFactory(testSSLContext.clientContext.getSocketFactory());
468b7155fd57239e986bbaba254a91aeb9600d60305Jesse Wilson        assertContent("another response via HTTPS", connection);
469b7155fd57239e986bbaba254a91aeb9600d60305Jesse Wilson
470b7155fd57239e986bbaba254a91aeb9600d60305Jesse Wilson        assertEquals(0, server.takeRequest().getSequenceNumber());
471b7155fd57239e986bbaba254a91aeb9600d60305Jesse Wilson        assertEquals(1, server.takeRequest().getSequenceNumber());
472b7155fd57239e986bbaba254a91aeb9600d60305Jesse Wilson    }
473b7155fd57239e986bbaba254a91aeb9600d60305Jesse Wilson
4748116f7e97e00d223e7fbe5c950c9a5e3277de124Jesse Wilson    public void testConnectViaHttpsReusingConnectionsDifferentFactories()
475b7155fd57239e986bbaba254a91aeb9600d60305Jesse Wilson            throws IOException, InterruptedException {
476b7155fd57239e986bbaba254a91aeb9600d60305Jesse Wilson        TestSSLContext testSSLContext = TestSSLContext.create();
477b7155fd57239e986bbaba254a91aeb9600d60305Jesse Wilson
478b7155fd57239e986bbaba254a91aeb9600d60305Jesse Wilson        server.useHttps(testSSLContext.serverContext.getSocketFactory(), false);
479b7155fd57239e986bbaba254a91aeb9600d60305Jesse Wilson        server.enqueue(new MockResponse().setBody("this response comes via HTTPS"));
480b7155fd57239e986bbaba254a91aeb9600d60305Jesse Wilson        server.enqueue(new MockResponse().setBody("another response via HTTPS"));
481b7155fd57239e986bbaba254a91aeb9600d60305Jesse Wilson        server.play();
482b7155fd57239e986bbaba254a91aeb9600d60305Jesse Wilson
483096aac7b8a607d3da237900f52cab1c5066bf992Jesse Wilson        // install a custom SSL socket factory so the server can be authorized
484096aac7b8a607d3da237900f52cab1c5066bf992Jesse Wilson        HttpsURLConnection connection = (HttpsURLConnection) server.getUrl("/").openConnection();
485059dbc04218144f985b20a228bbe98139d400d0cBrian Carlstrom        connection.setSSLSocketFactory(testSSLContext.clientContext.getSocketFactory());
486096aac7b8a607d3da237900f52cab1c5066bf992Jesse Wilson        assertContent("this response comes via HTTPS", connection);
487096aac7b8a607d3da237900f52cab1c5066bf992Jesse Wilson
488096aac7b8a607d3da237900f52cab1c5066bf992Jesse Wilson        connection = (HttpsURLConnection) server.getUrl("/").openConnection();
489096aac7b8a607d3da237900f52cab1c5066bf992Jesse Wilson        try {
490096aac7b8a607d3da237900f52cab1c5066bf992Jesse Wilson            readAscii(connection.getInputStream(), Integer.MAX_VALUE);
491b7155fd57239e986bbaba254a91aeb9600d60305Jesse Wilson            fail("without an SSL socket factory, the connection should fail");
492096aac7b8a607d3da237900f52cab1c5066bf992Jesse Wilson        } catch (SSLException expected) {
493096aac7b8a607d3da237900f52cab1c5066bf992Jesse Wilson        }
494096aac7b8a607d3da237900f52cab1c5066bf992Jesse Wilson    }
495096aac7b8a607d3da237900f52cab1c5066bf992Jesse Wilson
4964559b1d37edcb5d7f1da086cf2e3290388d74f46Brian Carlstrom    public void testConnectViaHttpsWithSSLFallback() throws IOException, InterruptedException {
4974559b1d37edcb5d7f1da086cf2e3290388d74f46Brian Carlstrom        TestSSLContext testSSLContext = TestSSLContext.create();
4984559b1d37edcb5d7f1da086cf2e3290388d74f46Brian Carlstrom
4994559b1d37edcb5d7f1da086cf2e3290388d74f46Brian Carlstrom        server.useHttps(testSSLContext.serverContext.getSocketFactory(), false);
500e942f46f10bb9384a1b186b3d7b74f9704c57090Jesse Wilson        server.enqueue(new MockResponse().setSocketPolicy(DISCONNECT_AT_START));
5014559b1d37edcb5d7f1da086cf2e3290388d74f46Brian Carlstrom        server.enqueue(new MockResponse().setBody("this response comes via SSL"));
5024559b1d37edcb5d7f1da086cf2e3290388d74f46Brian Carlstrom        server.play();
5034559b1d37edcb5d7f1da086cf2e3290388d74f46Brian Carlstrom
5044559b1d37edcb5d7f1da086cf2e3290388d74f46Brian Carlstrom        HttpsURLConnection connection = (HttpsURLConnection) server.getUrl("/foo").openConnection();
5054559b1d37edcb5d7f1da086cf2e3290388d74f46Brian Carlstrom        connection.setSSLSocketFactory(testSSLContext.clientContext.getSocketFactory());
5064559b1d37edcb5d7f1da086cf2e3290388d74f46Brian Carlstrom
5074559b1d37edcb5d7f1da086cf2e3290388d74f46Brian Carlstrom        assertContent("this response comes via SSL", connection);
5084559b1d37edcb5d7f1da086cf2e3290388d74f46Brian Carlstrom
5094559b1d37edcb5d7f1da086cf2e3290388d74f46Brian Carlstrom        RecordedRequest request = server.takeRequest();
5104559b1d37edcb5d7f1da086cf2e3290388d74f46Brian Carlstrom        assertEquals("GET /foo HTTP/1.1", request.getRequestLine());
5114559b1d37edcb5d7f1da086cf2e3290388d74f46Brian Carlstrom    }
5124559b1d37edcb5d7f1da086cf2e3290388d74f46Brian Carlstrom
5132915378e253f08e47fe5a9bfd026cd1ca7c6c351Brian Carlstrom    /**
5142915378e253f08e47fe5a9bfd026cd1ca7c6c351Brian Carlstrom     * Verify that we don't retry connections on certificate verification errors.
5152915378e253f08e47fe5a9bfd026cd1ca7c6c351Brian Carlstrom     *
5162915378e253f08e47fe5a9bfd026cd1ca7c6c351Brian Carlstrom     * http://code.google.com/p/android/issues/detail?id=13178
5172915378e253f08e47fe5a9bfd026cd1ca7c6c351Brian Carlstrom     */
5182915378e253f08e47fe5a9bfd026cd1ca7c6c351Brian Carlstrom    public void testConnectViaHttpsToUntrustedServer() throws IOException, InterruptedException {
5192915378e253f08e47fe5a9bfd026cd1ca7c6c351Brian Carlstrom        TestSSLContext testSSLContext = TestSSLContext.create(TestKeyStore.getClientCA2(),
5202915378e253f08e47fe5a9bfd026cd1ca7c6c351Brian Carlstrom                                                              TestKeyStore.getServer());
5212915378e253f08e47fe5a9bfd026cd1ca7c6c351Brian Carlstrom
5222915378e253f08e47fe5a9bfd026cd1ca7c6c351Brian Carlstrom        server.useHttps(testSSLContext.serverContext.getSocketFactory(), false);
5232915378e253f08e47fe5a9bfd026cd1ca7c6c351Brian Carlstrom        server.enqueue(new MockResponse()); // unused
5242915378e253f08e47fe5a9bfd026cd1ca7c6c351Brian Carlstrom        server.play();
5252915378e253f08e47fe5a9bfd026cd1ca7c6c351Brian Carlstrom
5262915378e253f08e47fe5a9bfd026cd1ca7c6c351Brian Carlstrom        HttpsURLConnection connection = (HttpsURLConnection) server.getUrl("/foo").openConnection();
5272915378e253f08e47fe5a9bfd026cd1ca7c6c351Brian Carlstrom        connection.setSSLSocketFactory(testSSLContext.clientContext.getSocketFactory());
5282915378e253f08e47fe5a9bfd026cd1ca7c6c351Brian Carlstrom        try {
5292915378e253f08e47fe5a9bfd026cd1ca7c6c351Brian Carlstrom            connection.getInputStream();
5302915378e253f08e47fe5a9bfd026cd1ca7c6c351Brian Carlstrom            fail();
5312915378e253f08e47fe5a9bfd026cd1ca7c6c351Brian Carlstrom        } catch (SSLHandshakeException expected) {
5322915378e253f08e47fe5a9bfd026cd1ca7c6c351Brian Carlstrom            assertTrue(expected.getCause() instanceof CertificateException);
5332915378e253f08e47fe5a9bfd026cd1ca7c6c351Brian Carlstrom        }
5342915378e253f08e47fe5a9bfd026cd1ca7c6c351Brian Carlstrom        assertEquals(0, server.getRequestCount());
5352915378e253f08e47fe5a9bfd026cd1ca7c6c351Brian Carlstrom    }
5362915378e253f08e47fe5a9bfd026cd1ca7c6c351Brian Carlstrom
537984fcff696380abd6ea14e80030f9fd2d09dbad0Jesse Wilson    public void testConnectViaProxyUsingProxyArg() throws Exception {
538984fcff696380abd6ea14e80030f9fd2d09dbad0Jesse Wilson        testConnectViaProxy(ProxyConfig.CREATE_ARG);
539984fcff696380abd6ea14e80030f9fd2d09dbad0Jesse Wilson    }
540984fcff696380abd6ea14e80030f9fd2d09dbad0Jesse Wilson
541984fcff696380abd6ea14e80030f9fd2d09dbad0Jesse Wilson    public void testConnectViaProxyUsingProxySystemProperty() throws Exception {
542984fcff696380abd6ea14e80030f9fd2d09dbad0Jesse Wilson        testConnectViaProxy(ProxyConfig.PROXY_SYSTEM_PROPERTY);
543984fcff696380abd6ea14e80030f9fd2d09dbad0Jesse Wilson    }
544984fcff696380abd6ea14e80030f9fd2d09dbad0Jesse Wilson
545984fcff696380abd6ea14e80030f9fd2d09dbad0Jesse Wilson    public void testConnectViaProxyUsingHttpProxySystemProperty() throws Exception {
546984fcff696380abd6ea14e80030f9fd2d09dbad0Jesse Wilson        testConnectViaProxy(ProxyConfig.HTTP_PROXY_SYSTEM_PROPERTY);
547984fcff696380abd6ea14e80030f9fd2d09dbad0Jesse Wilson    }
548984fcff696380abd6ea14e80030f9fd2d09dbad0Jesse Wilson
549984fcff696380abd6ea14e80030f9fd2d09dbad0Jesse Wilson    private void testConnectViaProxy(ProxyConfig proxyConfig) throws Exception {
550c0372d90016d241ac979faa6fa1731f30b6f2a03Jesse Wilson        MockResponse mockResponse = new MockResponse().setBody("this response comes via a proxy");
55151e468abf2628ce964d3657042f3ac8f2c947504Jesse Wilson        server.enqueue(mockResponse);
55251e468abf2628ce964d3657042f3ac8f2c947504Jesse Wilson        server.play();
55360476787f0e0f052366d8031c74e507ffd3d16a3Jesse Wilson
554984fcff696380abd6ea14e80030f9fd2d09dbad0Jesse Wilson        URL url = new URL("http://android.com/foo");
555984fcff696380abd6ea14e80030f9fd2d09dbad0Jesse Wilson        HttpURLConnection connection = proxyConfig.connect(server, url);
556c8977f474b30c5f3807398859a6b16687af6fc7bJesse Wilson        assertContent("this response comes via a proxy", connection);
55760476787f0e0f052366d8031c74e507ffd3d16a3Jesse Wilson
55851e468abf2628ce964d3657042f3ac8f2c947504Jesse Wilson        RecordedRequest request = server.takeRequest();
55960476787f0e0f052366d8031c74e507ffd3d16a3Jesse Wilson        assertEquals("GET http://android.com/foo HTTP/1.1", request.getRequestLine());
56060476787f0e0f052366d8031c74e507ffd3d16a3Jesse Wilson        assertContains(request.getHeaders(), "Host: android.com");
56160476787f0e0f052366d8031c74e507ffd3d16a3Jesse Wilson    }
56260476787f0e0f052366d8031c74e507ffd3d16a3Jesse Wilson
563c8977f474b30c5f3807398859a6b16687af6fc7bJesse Wilson    public void testContentDisagreesWithContentLengthHeader() throws IOException {
564c8977f474b30c5f3807398859a6b16687af6fc7bJesse Wilson        server.enqueue(new MockResponse()
565c8977f474b30c5f3807398859a6b16687af6fc7bJesse Wilson                .setBody("abc\r\nYOU SHOULD NOT SEE THIS")
566c8977f474b30c5f3807398859a6b16687af6fc7bJesse Wilson                .clearHeaders()
567c8977f474b30c5f3807398859a6b16687af6fc7bJesse Wilson                .addHeader("Content-Length: 3"));
568c8977f474b30c5f3807398859a6b16687af6fc7bJesse Wilson        server.play();
569c8977f474b30c5f3807398859a6b16687af6fc7bJesse Wilson
570c8977f474b30c5f3807398859a6b16687af6fc7bJesse Wilson        assertContent("abc", server.getUrl("/").openConnection());
571c8977f474b30c5f3807398859a6b16687af6fc7bJesse Wilson    }
572c8977f474b30c5f3807398859a6b16687af6fc7bJesse Wilson
573c8977f474b30c5f3807398859a6b16687af6fc7bJesse Wilson    public void testContentDisagreesWithChunkedHeader() throws IOException {
574c8977f474b30c5f3807398859a6b16687af6fc7bJesse Wilson        MockResponse mockResponse = new MockResponse();
575c8977f474b30c5f3807398859a6b16687af6fc7bJesse Wilson        mockResponse.setChunkedBody("abc", 3);
576c8977f474b30c5f3807398859a6b16687af6fc7bJesse Wilson        ByteArrayOutputStream bytesOut = new ByteArrayOutputStream();
577c8977f474b30c5f3807398859a6b16687af6fc7bJesse Wilson        bytesOut.write(mockResponse.getBody());
578c8977f474b30c5f3807398859a6b16687af6fc7bJesse Wilson        bytesOut.write("\r\nYOU SHOULD NOT SEE THIS".getBytes());
579c8977f474b30c5f3807398859a6b16687af6fc7bJesse Wilson        mockResponse.setBody(bytesOut.toByteArray());
580c8977f474b30c5f3807398859a6b16687af6fc7bJesse Wilson        mockResponse.clearHeaders();
581c8977f474b30c5f3807398859a6b16687af6fc7bJesse Wilson        mockResponse.addHeader("Transfer-encoding: chunked");
582c8977f474b30c5f3807398859a6b16687af6fc7bJesse Wilson
583c8977f474b30c5f3807398859a6b16687af6fc7bJesse Wilson        server.enqueue(mockResponse);
584c8977f474b30c5f3807398859a6b16687af6fc7bJesse Wilson        server.play();
585c8977f474b30c5f3807398859a6b16687af6fc7bJesse Wilson
586c8977f474b30c5f3807398859a6b16687af6fc7bJesse Wilson        assertContent("abc", server.getUrl("/").openConnection());
587c8977f474b30c5f3807398859a6b16687af6fc7bJesse Wilson    }
588c8977f474b30c5f3807398859a6b16687af6fc7bJesse Wilson
589f02c695ed03e708623d9365dec26d533356ef2d0Brian Carlstrom    public void testConnectViaHttpProxyToHttpsUsingProxyArgWithNoProxy() throws Exception {
590f02c695ed03e708623d9365dec26d533356ef2d0Brian Carlstrom        testConnectViaDirectProxyToHttps(ProxyConfig.NO_PROXY);
591f02c695ed03e708623d9365dec26d533356ef2d0Brian Carlstrom    }
592f02c695ed03e708623d9365dec26d533356ef2d0Brian Carlstrom
593f02c695ed03e708623d9365dec26d533356ef2d0Brian Carlstrom    public void testConnectViaHttpProxyToHttpsUsingHttpProxySystemProperty() throws Exception {
594f02c695ed03e708623d9365dec26d533356ef2d0Brian Carlstrom        // https should not use http proxy
595f02c695ed03e708623d9365dec26d533356ef2d0Brian Carlstrom        testConnectViaDirectProxyToHttps(ProxyConfig.HTTP_PROXY_SYSTEM_PROPERTY);
596f02c695ed03e708623d9365dec26d533356ef2d0Brian Carlstrom    }
597f02c695ed03e708623d9365dec26d533356ef2d0Brian Carlstrom
598f02c695ed03e708623d9365dec26d533356ef2d0Brian Carlstrom    private void testConnectViaDirectProxyToHttps(ProxyConfig proxyConfig) throws Exception {
599f02c695ed03e708623d9365dec26d533356ef2d0Brian Carlstrom        TestSSLContext testSSLContext = TestSSLContext.create();
600f02c695ed03e708623d9365dec26d533356ef2d0Brian Carlstrom
601f02c695ed03e708623d9365dec26d533356ef2d0Brian Carlstrom        server.useHttps(testSSLContext.serverContext.getSocketFactory(), false);
602f02c695ed03e708623d9365dec26d533356ef2d0Brian Carlstrom        server.enqueue(new MockResponse().setBody("this response comes via HTTPS"));
603f02c695ed03e708623d9365dec26d533356ef2d0Brian Carlstrom        server.play();
604f02c695ed03e708623d9365dec26d533356ef2d0Brian Carlstrom
605f02c695ed03e708623d9365dec26d533356ef2d0Brian Carlstrom        URL url = server.getUrl("/foo");
606f02c695ed03e708623d9365dec26d533356ef2d0Brian Carlstrom        HttpsURLConnection connection = (HttpsURLConnection) proxyConfig.connect(server, url);
607f02c695ed03e708623d9365dec26d533356ef2d0Brian Carlstrom        connection.setSSLSocketFactory(testSSLContext.clientContext.getSocketFactory());
608f02c695ed03e708623d9365dec26d533356ef2d0Brian Carlstrom
609f02c695ed03e708623d9365dec26d533356ef2d0Brian Carlstrom        assertContent("this response comes via HTTPS", connection);
610f02c695ed03e708623d9365dec26d533356ef2d0Brian Carlstrom
611f02c695ed03e708623d9365dec26d533356ef2d0Brian Carlstrom        RecordedRequest request = server.takeRequest();
612f02c695ed03e708623d9365dec26d533356ef2d0Brian Carlstrom        assertEquals("GET /foo HTTP/1.1", request.getRequestLine());
613f02c695ed03e708623d9365dec26d533356ef2d0Brian Carlstrom    }
614f02c695ed03e708623d9365dec26d533356ef2d0Brian Carlstrom
615f02c695ed03e708623d9365dec26d533356ef2d0Brian Carlstrom
616984fcff696380abd6ea14e80030f9fd2d09dbad0Jesse Wilson    public void testConnectViaHttpProxyToHttpsUsingProxyArg() throws Exception {
617984fcff696380abd6ea14e80030f9fd2d09dbad0Jesse Wilson        testConnectViaHttpProxyToHttps(ProxyConfig.CREATE_ARG);
618984fcff696380abd6ea14e80030f9fd2d09dbad0Jesse Wilson    }
619984fcff696380abd6ea14e80030f9fd2d09dbad0Jesse Wilson
620984fcff696380abd6ea14e80030f9fd2d09dbad0Jesse Wilson    /**
621984fcff696380abd6ea14e80030f9fd2d09dbad0Jesse Wilson     * We weren't honoring all of the appropriate proxy system properties when
622984fcff696380abd6ea14e80030f9fd2d09dbad0Jesse Wilson     * connecting via HTTPS. http://b/3097518
623984fcff696380abd6ea14e80030f9fd2d09dbad0Jesse Wilson     */
624984fcff696380abd6ea14e80030f9fd2d09dbad0Jesse Wilson    public void testConnectViaHttpProxyToHttpsUsingProxySystemProperty() throws Exception {
625984fcff696380abd6ea14e80030f9fd2d09dbad0Jesse Wilson        testConnectViaHttpProxyToHttps(ProxyConfig.PROXY_SYSTEM_PROPERTY);
626984fcff696380abd6ea14e80030f9fd2d09dbad0Jesse Wilson    }
627984fcff696380abd6ea14e80030f9fd2d09dbad0Jesse Wilson
628984fcff696380abd6ea14e80030f9fd2d09dbad0Jesse Wilson    public void testConnectViaHttpProxyToHttpsUsingHttpsProxySystemProperty() throws Exception {
629984fcff696380abd6ea14e80030f9fd2d09dbad0Jesse Wilson        testConnectViaHttpProxyToHttps(ProxyConfig.HTTPS_PROXY_SYSTEM_PROPERTY);
630984fcff696380abd6ea14e80030f9fd2d09dbad0Jesse Wilson    }
631984fcff696380abd6ea14e80030f9fd2d09dbad0Jesse Wilson
632984fcff696380abd6ea14e80030f9fd2d09dbad0Jesse Wilson    /**
633984fcff696380abd6ea14e80030f9fd2d09dbad0Jesse Wilson     * We were verifying the wrong hostname when connecting to an HTTPS site
634984fcff696380abd6ea14e80030f9fd2d09dbad0Jesse Wilson     * through a proxy. http://b/3097277
635984fcff696380abd6ea14e80030f9fd2d09dbad0Jesse Wilson     */
636984fcff696380abd6ea14e80030f9fd2d09dbad0Jesse Wilson    private void testConnectViaHttpProxyToHttps(ProxyConfig proxyConfig) throws Exception {
63760476787f0e0f052366d8031c74e507ffd3d16a3Jesse Wilson        TestSSLContext testSSLContext = TestSSLContext.create();
638984fcff696380abd6ea14e80030f9fd2d09dbad0Jesse Wilson        RecordingHostnameVerifier hostnameVerifier = new RecordingHostnameVerifier();
63960476787f0e0f052366d8031c74e507ffd3d16a3Jesse Wilson
640059dbc04218144f985b20a228bbe98139d400d0cBrian Carlstrom        server.useHttps(testSSLContext.serverContext.getSocketFactory(), true);
641c996149b500fc4825156106554457fe2394ae087Jesse Wilson        server.enqueue(new MockResponse()
642c996149b500fc4825156106554457fe2394ae087Jesse Wilson                .setSocketPolicy(SocketPolicy.UPGRADE_TO_SSL_AT_END)
643c996149b500fc4825156106554457fe2394ae087Jesse Wilson                .clearHeaders());
644c0372d90016d241ac979faa6fa1731f30b6f2a03Jesse Wilson        server.enqueue(new MockResponse().setBody("this response comes via a secure proxy"));
64551e468abf2628ce964d3657042f3ac8f2c947504Jesse Wilson        server.play();
64660476787f0e0f052366d8031c74e507ffd3d16a3Jesse Wilson
64760476787f0e0f052366d8031c74e507ffd3d16a3Jesse Wilson        URL url = new URL("https://android.com/foo");
648984fcff696380abd6ea14e80030f9fd2d09dbad0Jesse Wilson        HttpsURLConnection connection = (HttpsURLConnection) proxyConfig.connect(server, url);
649059dbc04218144f985b20a228bbe98139d400d0cBrian Carlstrom        connection.setSSLSocketFactory(testSSLContext.clientContext.getSocketFactory());
650984fcff696380abd6ea14e80030f9fd2d09dbad0Jesse Wilson        connection.setHostnameVerifier(hostnameVerifier);
65160476787f0e0f052366d8031c74e507ffd3d16a3Jesse Wilson
652c8977f474b30c5f3807398859a6b16687af6fc7bJesse Wilson        assertContent("this response comes via a secure proxy", connection);
65360476787f0e0f052366d8031c74e507ffd3d16a3Jesse Wilson
65451e468abf2628ce964d3657042f3ac8f2c947504Jesse Wilson        RecordedRequest connect = server.takeRequest();
65560476787f0e0f052366d8031c74e507ffd3d16a3Jesse Wilson        assertEquals("Connect line failure on proxy",
65660476787f0e0f052366d8031c74e507ffd3d16a3Jesse Wilson                "CONNECT android.com:443 HTTP/1.1", connect.getRequestLine());
65760476787f0e0f052366d8031c74e507ffd3d16a3Jesse Wilson        assertContains(connect.getHeaders(), "Host: android.com");
65860476787f0e0f052366d8031c74e507ffd3d16a3Jesse Wilson
65951e468abf2628ce964d3657042f3ac8f2c947504Jesse Wilson        RecordedRequest get = server.takeRequest();
66060476787f0e0f052366d8031c74e507ffd3d16a3Jesse Wilson        assertEquals("GET /foo HTTP/1.1", get.getRequestLine());
66160476787f0e0f052366d8031c74e507ffd3d16a3Jesse Wilson        assertContains(get.getHeaders(), "Host: android.com");
662984fcff696380abd6ea14e80030f9fd2d09dbad0Jesse Wilson        assertEquals(Arrays.asList("verify android.com"), hostnameVerifier.calls);
66360476787f0e0f052366d8031c74e507ffd3d16a3Jesse Wilson    }
66460476787f0e0f052366d8031c74e507ffd3d16a3Jesse Wilson
665d4bddd7d1fb7b1b7f0836648228235c6e4b56a18Jesse Wilson    /**
666d4bddd7d1fb7b1b7f0836648228235c6e4b56a18Jesse Wilson     * Test which headers are sent unencrypted to the HTTP proxy.
667d4bddd7d1fb7b1b7f0836648228235c6e4b56a18Jesse Wilson     */
668d4bddd7d1fb7b1b7f0836648228235c6e4b56a18Jesse Wilson    public void testProxyConnectIncludesProxyHeadersOnly()
669d4bddd7d1fb7b1b7f0836648228235c6e4b56a18Jesse Wilson            throws IOException, InterruptedException {
670984fcff696380abd6ea14e80030f9fd2d09dbad0Jesse Wilson        RecordingHostnameVerifier hostnameVerifier = new RecordingHostnameVerifier();
671d4bddd7d1fb7b1b7f0836648228235c6e4b56a18Jesse Wilson        TestSSLContext testSSLContext = TestSSLContext.create();
672d4bddd7d1fb7b1b7f0836648228235c6e4b56a18Jesse Wilson
673d4bddd7d1fb7b1b7f0836648228235c6e4b56a18Jesse Wilson        server.useHttps(testSSLContext.serverContext.getSocketFactory(), true);
674c996149b500fc4825156106554457fe2394ae087Jesse Wilson        server.enqueue(new MockResponse()
675c996149b500fc4825156106554457fe2394ae087Jesse Wilson                .setSocketPolicy(SocketPolicy.UPGRADE_TO_SSL_AT_END)
676c996149b500fc4825156106554457fe2394ae087Jesse Wilson                .clearHeaders());
677d4bddd7d1fb7b1b7f0836648228235c6e4b56a18Jesse Wilson        server.enqueue(new MockResponse().setBody("encrypted response from the origin server"));
678d4bddd7d1fb7b1b7f0836648228235c6e4b56a18Jesse Wilson        server.play();
679d4bddd7d1fb7b1b7f0836648228235c6e4b56a18Jesse Wilson
680d4bddd7d1fb7b1b7f0836648228235c6e4b56a18Jesse Wilson        URL url = new URL("https://android.com/foo");
681d4bddd7d1fb7b1b7f0836648228235c6e4b56a18Jesse Wilson        HttpsURLConnection connection = (HttpsURLConnection) url.openConnection(
682d4bddd7d1fb7b1b7f0836648228235c6e4b56a18Jesse Wilson                server.toProxyAddress());
683d4bddd7d1fb7b1b7f0836648228235c6e4b56a18Jesse Wilson        connection.addRequestProperty("Private", "Secret");
684d4bddd7d1fb7b1b7f0836648228235c6e4b56a18Jesse Wilson        connection.addRequestProperty("Proxy-Authorization", "bar");
685d4bddd7d1fb7b1b7f0836648228235c6e4b56a18Jesse Wilson        connection.addRequestProperty("User-Agent", "baz");
686d4bddd7d1fb7b1b7f0836648228235c6e4b56a18Jesse Wilson        connection.setSSLSocketFactory(testSSLContext.clientContext.getSocketFactory());
687984fcff696380abd6ea14e80030f9fd2d09dbad0Jesse Wilson        connection.setHostnameVerifier(hostnameVerifier);
688d4bddd7d1fb7b1b7f0836648228235c6e4b56a18Jesse Wilson        assertContent("encrypted response from the origin server", connection);
689d4bddd7d1fb7b1b7f0836648228235c6e4b56a18Jesse Wilson
690d4bddd7d1fb7b1b7f0836648228235c6e4b56a18Jesse Wilson        RecordedRequest connect = server.takeRequest();
691d4bddd7d1fb7b1b7f0836648228235c6e4b56a18Jesse Wilson        assertContainsNoneMatching(connect.getHeaders(), "Private.*");
692d4bddd7d1fb7b1b7f0836648228235c6e4b56a18Jesse Wilson        assertContains(connect.getHeaders(), "Proxy-Authorization: bar");
693d4bddd7d1fb7b1b7f0836648228235c6e4b56a18Jesse Wilson        assertContains(connect.getHeaders(), "User-Agent: baz");
694d4bddd7d1fb7b1b7f0836648228235c6e4b56a18Jesse Wilson        assertContains(connect.getHeaders(), "Host: android.com");
695d4bddd7d1fb7b1b7f0836648228235c6e4b56a18Jesse Wilson        assertContains(connect.getHeaders(), "Proxy-Connection: Keep-Alive");
696d4bddd7d1fb7b1b7f0836648228235c6e4b56a18Jesse Wilson
697d4bddd7d1fb7b1b7f0836648228235c6e4b56a18Jesse Wilson        RecordedRequest get = server.takeRequest();
698d4bddd7d1fb7b1b7f0836648228235c6e4b56a18Jesse Wilson        assertContains(get.getHeaders(), "Private: Secret");
699984fcff696380abd6ea14e80030f9fd2d09dbad0Jesse Wilson        assertEquals(Arrays.asList("verify android.com"), hostnameVerifier.calls);
700d4bddd7d1fb7b1b7f0836648228235c6e4b56a18Jesse Wilson    }
701d4bddd7d1fb7b1b7f0836648228235c6e4b56a18Jesse Wilson
702c996149b500fc4825156106554457fe2394ae087Jesse Wilson    public void testProxyAuthenticateOnConnect() throws Exception {
7035757cb35ad2e58d7accb7f5d3db6f2d5e72f097dJesse Wilson        Authenticator.setDefault(new SimpleAuthenticator());
704c996149b500fc4825156106554457fe2394ae087Jesse Wilson        TestSSLContext testSSLContext = TestSSLContext.create();
705c996149b500fc4825156106554457fe2394ae087Jesse Wilson        server.useHttps(testSSLContext.serverContext.getSocketFactory(), true);
706c996149b500fc4825156106554457fe2394ae087Jesse Wilson        server.enqueue(new MockResponse()
707c996149b500fc4825156106554457fe2394ae087Jesse Wilson                .setResponseCode(407)
708c996149b500fc4825156106554457fe2394ae087Jesse Wilson                .addHeader("Proxy-Authenticate: Basic realm=\"localhost\""));
709c996149b500fc4825156106554457fe2394ae087Jesse Wilson        server.enqueue(new MockResponse()
710c996149b500fc4825156106554457fe2394ae087Jesse Wilson                .setSocketPolicy(SocketPolicy.UPGRADE_TO_SSL_AT_END)
711c996149b500fc4825156106554457fe2394ae087Jesse Wilson                .clearHeaders());
712c996149b500fc4825156106554457fe2394ae087Jesse Wilson        server.enqueue(new MockResponse().setBody("A"));
713c996149b500fc4825156106554457fe2394ae087Jesse Wilson        server.play();
714c996149b500fc4825156106554457fe2394ae087Jesse Wilson
715c996149b500fc4825156106554457fe2394ae087Jesse Wilson        URL url = new URL("https://android.com/foo");
716c996149b500fc4825156106554457fe2394ae087Jesse Wilson        HttpsURLConnection connection = (HttpsURLConnection) url.openConnection(
717c996149b500fc4825156106554457fe2394ae087Jesse Wilson                server.toProxyAddress());
718c996149b500fc4825156106554457fe2394ae087Jesse Wilson        connection.setSSLSocketFactory(testSSLContext.clientContext.getSocketFactory());
719c996149b500fc4825156106554457fe2394ae087Jesse Wilson        connection.setHostnameVerifier(new RecordingHostnameVerifier());
720c996149b500fc4825156106554457fe2394ae087Jesse Wilson        assertContent("A", connection);
721c996149b500fc4825156106554457fe2394ae087Jesse Wilson
722c996149b500fc4825156106554457fe2394ae087Jesse Wilson        RecordedRequest connect1 = server.takeRequest();
723c996149b500fc4825156106554457fe2394ae087Jesse Wilson        assertEquals("CONNECT android.com:443 HTTP/1.1", connect1.getRequestLine());
724c996149b500fc4825156106554457fe2394ae087Jesse Wilson        assertContainsNoneMatching(connect1.getHeaders(), "Proxy\\-Authorization.*");
725c996149b500fc4825156106554457fe2394ae087Jesse Wilson
726c996149b500fc4825156106554457fe2394ae087Jesse Wilson        RecordedRequest connect2 = server.takeRequest();
727c996149b500fc4825156106554457fe2394ae087Jesse Wilson        assertEquals("CONNECT android.com:443 HTTP/1.1", connect2.getRequestLine());
7285757cb35ad2e58d7accb7f5d3db6f2d5e72f097dJesse Wilson        assertContains(connect2.getHeaders(), "Proxy-Authorization: Basic "
7295757cb35ad2e58d7accb7f5d3db6f2d5e72f097dJesse Wilson                + SimpleAuthenticator.BASE_64_CREDENTIALS);
730c996149b500fc4825156106554457fe2394ae087Jesse Wilson
731c996149b500fc4825156106554457fe2394ae087Jesse Wilson        RecordedRequest get = server.takeRequest();
732c996149b500fc4825156106554457fe2394ae087Jesse Wilson        assertEquals("GET /foo HTTP/1.1", get.getRequestLine());
733c996149b500fc4825156106554457fe2394ae087Jesse Wilson        assertContainsNoneMatching(get.getHeaders(), "Proxy\\-Authorization.*");
734c996149b500fc4825156106554457fe2394ae087Jesse Wilson    }
735c996149b500fc4825156106554457fe2394ae087Jesse Wilson
736d4bddd7d1fb7b1b7f0836648228235c6e4b56a18Jesse Wilson    public void testDisconnectedConnection() throws IOException {
737d4bddd7d1fb7b1b7f0836648228235c6e4b56a18Jesse Wilson        server.enqueue(new MockResponse().setBody("ABCDEFGHIJKLMNOPQR"));
738d4bddd7d1fb7b1b7f0836648228235c6e4b56a18Jesse Wilson        server.play();
739d4bddd7d1fb7b1b7f0836648228235c6e4b56a18Jesse Wilson
740d4bddd7d1fb7b1b7f0836648228235c6e4b56a18Jesse Wilson        HttpURLConnection connection = (HttpURLConnection) server.getUrl("/").openConnection();
741d4bddd7d1fb7b1b7f0836648228235c6e4b56a18Jesse Wilson        InputStream in = connection.getInputStream();
742d4bddd7d1fb7b1b7f0836648228235c6e4b56a18Jesse Wilson        assertEquals('A', (char) in.read());
743d4bddd7d1fb7b1b7f0836648228235c6e4b56a18Jesse Wilson        connection.disconnect();
744d4bddd7d1fb7b1b7f0836648228235c6e4b56a18Jesse Wilson        try {
745d4bddd7d1fb7b1b7f0836648228235c6e4b56a18Jesse Wilson            in.read();
746d4bddd7d1fb7b1b7f0836648228235c6e4b56a18Jesse Wilson            fail("Expected a connection closed exception");
747d4bddd7d1fb7b1b7f0836648228235c6e4b56a18Jesse Wilson        } catch (IOException expected) {
748d4bddd7d1fb7b1b7f0836648228235c6e4b56a18Jesse Wilson        }
749d4bddd7d1fb7b1b7f0836648228235c6e4b56a18Jesse Wilson    }
750d4bddd7d1fb7b1b7f0836648228235c6e4b56a18Jesse Wilson
751d742d7fc7f0593eb8c6e4ac9dd4c0f6a80374e46Jesse Wilson    public void testDisconnectBeforeConnect() throws IOException {
752d742d7fc7f0593eb8c6e4ac9dd4c0f6a80374e46Jesse Wilson        server.enqueue(new MockResponse().setBody("A"));
753d742d7fc7f0593eb8c6e4ac9dd4c0f6a80374e46Jesse Wilson        server.play();
754d742d7fc7f0593eb8c6e4ac9dd4c0f6a80374e46Jesse Wilson
755d742d7fc7f0593eb8c6e4ac9dd4c0f6a80374e46Jesse Wilson        HttpURLConnection connection = (HttpURLConnection) server.getUrl("/").openConnection();
756d742d7fc7f0593eb8c6e4ac9dd4c0f6a80374e46Jesse Wilson        connection.disconnect();
757d742d7fc7f0593eb8c6e4ac9dd4c0f6a80374e46Jesse Wilson
758d742d7fc7f0593eb8c6e4ac9dd4c0f6a80374e46Jesse Wilson        assertContent("A", connection);
759d742d7fc7f0593eb8c6e4ac9dd4c0f6a80374e46Jesse Wilson        assertEquals(200, connection.getResponseCode());
760d742d7fc7f0593eb8c6e4ac9dd4c0f6a80374e46Jesse Wilson    }
761d742d7fc7f0593eb8c6e4ac9dd4c0f6a80374e46Jesse Wilson
762d742d7fc7f0593eb8c6e4ac9dd4c0f6a80374e46Jesse Wilson    public void testDefaultRequestProperty() throws Exception {
763d742d7fc7f0593eb8c6e4ac9dd4c0f6a80374e46Jesse Wilson        URLConnection.setDefaultRequestProperty("X-testSetDefaultRequestProperty", "A");
764d742d7fc7f0593eb8c6e4ac9dd4c0f6a80374e46Jesse Wilson        assertNull(URLConnection.getDefaultRequestProperty("X-setDefaultRequestProperty"));
765d742d7fc7f0593eb8c6e4ac9dd4c0f6a80374e46Jesse Wilson    }
766d742d7fc7f0593eb8c6e4ac9dd4c0f6a80374e46Jesse Wilson
76751e468abf2628ce964d3657042f3ac8f2c947504Jesse Wilson    /**
76851e468abf2628ce964d3657042f3ac8f2c947504Jesse Wilson     * Reads {@code count} characters from the stream. If the stream is
76951e468abf2628ce964d3657042f3ac8f2c947504Jesse Wilson     * exhausted before {@code count} characters can be read, the remaining
77051e468abf2628ce964d3657042f3ac8f2c947504Jesse Wilson     * characters are returned and the stream is closed.
77151e468abf2628ce964d3657042f3ac8f2c947504Jesse Wilson     */
77251e468abf2628ce964d3657042f3ac8f2c947504Jesse Wilson    private String readAscii(InputStream in, int count) throws IOException {
77351e468abf2628ce964d3657042f3ac8f2c947504Jesse Wilson        StringBuilder result = new StringBuilder();
77451e468abf2628ce964d3657042f3ac8f2c947504Jesse Wilson        for (int i = 0; i < count; i++) {
77551e468abf2628ce964d3657042f3ac8f2c947504Jesse Wilson            int value = in.read();
77651e468abf2628ce964d3657042f3ac8f2c947504Jesse Wilson            if (value == -1) {
77751e468abf2628ce964d3657042f3ac8f2c947504Jesse Wilson                in.close();
77851e468abf2628ce964d3657042f3ac8f2c947504Jesse Wilson                break;
77951e468abf2628ce964d3657042f3ac8f2c947504Jesse Wilson            }
78051e468abf2628ce964d3657042f3ac8f2c947504Jesse Wilson            result.append((char) value);
78151e468abf2628ce964d3657042f3ac8f2c947504Jesse Wilson        }
78251e468abf2628ce964d3657042f3ac8f2c947504Jesse Wilson        return result.toString();
78351e468abf2628ce964d3657042f3ac8f2c947504Jesse Wilson    }
78451e468abf2628ce964d3657042f3ac8f2c947504Jesse Wilson
78551e468abf2628ce964d3657042f3ac8f2c947504Jesse Wilson    public void testMarkAndResetWithContentLengthHeader() throws IOException {
78651e468abf2628ce964d3657042f3ac8f2c947504Jesse Wilson        testMarkAndReset(TransferKind.FIXED_LENGTH);
78751e468abf2628ce964d3657042f3ac8f2c947504Jesse Wilson    }
78851e468abf2628ce964d3657042f3ac8f2c947504Jesse Wilson
78951e468abf2628ce964d3657042f3ac8f2c947504Jesse Wilson    public void testMarkAndResetWithChunkedEncoding() throws IOException {
79051e468abf2628ce964d3657042f3ac8f2c947504Jesse Wilson        testMarkAndReset(TransferKind.CHUNKED);
79151e468abf2628ce964d3657042f3ac8f2c947504Jesse Wilson    }
79251e468abf2628ce964d3657042f3ac8f2c947504Jesse Wilson
79351e468abf2628ce964d3657042f3ac8f2c947504Jesse Wilson    public void testMarkAndResetWithNoLengthHeaders() throws IOException {
79451e468abf2628ce964d3657042f3ac8f2c947504Jesse Wilson        testMarkAndReset(TransferKind.END_OF_STREAM);
79551e468abf2628ce964d3657042f3ac8f2c947504Jesse Wilson    }
79651e468abf2628ce964d3657042f3ac8f2c947504Jesse Wilson
7970c2fd828abec671333b8b88281825fd27a783723Jesse Wilson    private void testMarkAndReset(TransferKind transferKind) throws IOException {
79851e468abf2628ce964d3657042f3ac8f2c947504Jesse Wilson        MockResponse response = new MockResponse();
79951e468abf2628ce964d3657042f3ac8f2c947504Jesse Wilson        transferKind.setBody(response, "ABCDEFGHIJKLMNOPQRSTUVWXYZ", 1024);
80051e468abf2628ce964d3657042f3ac8f2c947504Jesse Wilson        server.enqueue(response);
801953df613522e12a418cb7cb73248594d6c9f53d4Jesse Wilson        server.enqueue(response);
80251e468abf2628ce964d3657042f3ac8f2c947504Jesse Wilson        server.play();
80351e468abf2628ce964d3657042f3ac8f2c947504Jesse Wilson
80451e468abf2628ce964d3657042f3ac8f2c947504Jesse Wilson        InputStream in = server.getUrl("/").openConnection().getInputStream();
80551e468abf2628ce964d3657042f3ac8f2c947504Jesse Wilson        assertFalse("This implementation claims to support mark().", in.markSupported());
80651e468abf2628ce964d3657042f3ac8f2c947504Jesse Wilson        in.mark(5);
80751e468abf2628ce964d3657042f3ac8f2c947504Jesse Wilson        assertEquals("ABCDE", readAscii(in, 5));
80851e468abf2628ce964d3657042f3ac8f2c947504Jesse Wilson        try {
80951e468abf2628ce964d3657042f3ac8f2c947504Jesse Wilson            in.reset();
81051e468abf2628ce964d3657042f3ac8f2c947504Jesse Wilson            fail();
81151e468abf2628ce964d3657042f3ac8f2c947504Jesse Wilson        } catch (IOException expected) {
81251e468abf2628ce964d3657042f3ac8f2c947504Jesse Wilson        }
81351e468abf2628ce964d3657042f3ac8f2c947504Jesse Wilson        assertEquals("FGHIJKLMNOPQRSTUVWXYZ", readAscii(in, Integer.MAX_VALUE));
81451e468abf2628ce964d3657042f3ac8f2c947504Jesse Wilson        assertContent("ABCDEFGHIJKLMNOPQRSTUVWXYZ", server.getUrl("/").openConnection());
81551e468abf2628ce964d3657042f3ac8f2c947504Jesse Wilson    }
81651e468abf2628ce964d3657042f3ac8f2c947504Jesse Wilson
81751e468abf2628ce964d3657042f3ac8f2c947504Jesse Wilson    /**
81851e468abf2628ce964d3657042f3ac8f2c947504Jesse Wilson     * We've had a bug where we forget the HTTP response when we see response
81951e468abf2628ce964d3657042f3ac8f2c947504Jesse Wilson     * code 401. This causes a new HTTP request to be issued for every call into
82051e468abf2628ce964d3657042f3ac8f2c947504Jesse Wilson     * the URLConnection.
82151e468abf2628ce964d3657042f3ac8f2c947504Jesse Wilson     */
82251e468abf2628ce964d3657042f3ac8f2c947504Jesse Wilson    public void testUnauthorizedResponseHandling() throws IOException {
82351e468abf2628ce964d3657042f3ac8f2c947504Jesse Wilson        MockResponse response = new MockResponse()
8245757cb35ad2e58d7accb7f5d3db6f2d5e72f097dJesse Wilson                .addHeader("WWW-Authenticate: Basic realm=\"protected area\"")
82551e468abf2628ce964d3657042f3ac8f2c947504Jesse Wilson                .setResponseCode(401) // UNAUTHORIZED
82651e468abf2628ce964d3657042f3ac8f2c947504Jesse Wilson                .setBody("Unauthorized");
82751e468abf2628ce964d3657042f3ac8f2c947504Jesse Wilson        server.enqueue(response);
82851e468abf2628ce964d3657042f3ac8f2c947504Jesse Wilson        server.enqueue(response);
82951e468abf2628ce964d3657042f3ac8f2c947504Jesse Wilson        server.enqueue(response);
83051e468abf2628ce964d3657042f3ac8f2c947504Jesse Wilson        server.play();
83151e468abf2628ce964d3657042f3ac8f2c947504Jesse Wilson
83251e468abf2628ce964d3657042f3ac8f2c947504Jesse Wilson        URL url = server.getUrl("/");
83351e468abf2628ce964d3657042f3ac8f2c947504Jesse Wilson        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
83451e468abf2628ce964d3657042f3ac8f2c947504Jesse Wilson
83551e468abf2628ce964d3657042f3ac8f2c947504Jesse Wilson        assertEquals(401, conn.getResponseCode());
83651e468abf2628ce964d3657042f3ac8f2c947504Jesse Wilson        assertEquals(401, conn.getResponseCode());
83751e468abf2628ce964d3657042f3ac8f2c947504Jesse Wilson        assertEquals(401, conn.getResponseCode());
83851e468abf2628ce964d3657042f3ac8f2c947504Jesse Wilson        assertEquals(1, server.getRequestCount());
83951e468abf2628ce964d3657042f3ac8f2c947504Jesse Wilson    }
84051e468abf2628ce964d3657042f3ac8f2c947504Jesse Wilson
8416906b0c12dcf3216883d0373973a252812a20d32Jesse Wilson    public void testNonHexChunkSize() throws IOException {
8426906b0c12dcf3216883d0373973a252812a20d32Jesse Wilson        server.enqueue(new MockResponse()
8436906b0c12dcf3216883d0373973a252812a20d32Jesse Wilson                .setBody("5\r\nABCDE\r\nG\r\nFGHIJKLMNOPQRSTU\r\n0\r\n\r\n")
8446906b0c12dcf3216883d0373973a252812a20d32Jesse Wilson                .clearHeaders()
8456906b0c12dcf3216883d0373973a252812a20d32Jesse Wilson                .addHeader("Transfer-encoding: chunked"));
8466906b0c12dcf3216883d0373973a252812a20d32Jesse Wilson        server.play();
8476906b0c12dcf3216883d0373973a252812a20d32Jesse Wilson
8486906b0c12dcf3216883d0373973a252812a20d32Jesse Wilson        URLConnection connection = server.getUrl("/").openConnection();
8496906b0c12dcf3216883d0373973a252812a20d32Jesse Wilson        try {
8506906b0c12dcf3216883d0373973a252812a20d32Jesse Wilson            readAscii(connection.getInputStream(), Integer.MAX_VALUE);
8516906b0c12dcf3216883d0373973a252812a20d32Jesse Wilson            fail();
8526906b0c12dcf3216883d0373973a252812a20d32Jesse Wilson        } catch (IOException e) {
8536906b0c12dcf3216883d0373973a252812a20d32Jesse Wilson        }
8546906b0c12dcf3216883d0373973a252812a20d32Jesse Wilson    }
8556906b0c12dcf3216883d0373973a252812a20d32Jesse Wilson
8566906b0c12dcf3216883d0373973a252812a20d32Jesse Wilson    public void testMissingChunkBody() throws IOException {
8576906b0c12dcf3216883d0373973a252812a20d32Jesse Wilson        server.enqueue(new MockResponse()
8586906b0c12dcf3216883d0373973a252812a20d32Jesse Wilson                .setBody("5")
8596906b0c12dcf3216883d0373973a252812a20d32Jesse Wilson                .clearHeaders()
8606906b0c12dcf3216883d0373973a252812a20d32Jesse Wilson                .addHeader("Transfer-encoding: chunked")
861e942f46f10bb9384a1b186b3d7b74f9704c57090Jesse Wilson                .setSocketPolicy(DISCONNECT_AT_END));
8626906b0c12dcf3216883d0373973a252812a20d32Jesse Wilson        server.play();
8636906b0c12dcf3216883d0373973a252812a20d32Jesse Wilson
8646906b0c12dcf3216883d0373973a252812a20d32Jesse Wilson        URLConnection connection = server.getUrl("/").openConnection();
8656906b0c12dcf3216883d0373973a252812a20d32Jesse Wilson        try {
8666906b0c12dcf3216883d0373973a252812a20d32Jesse Wilson            readAscii(connection.getInputStream(), Integer.MAX_VALUE);
8676906b0c12dcf3216883d0373973a252812a20d32Jesse Wilson            fail();
8686906b0c12dcf3216883d0373973a252812a20d32Jesse Wilson        } catch (IOException e) {
8696906b0c12dcf3216883d0373973a252812a20d32Jesse Wilson        }
8706906b0c12dcf3216883d0373973a252812a20d32Jesse Wilson    }
8716906b0c12dcf3216883d0373973a252812a20d32Jesse Wilson
87250ae32218918eae80298bd1ab8e4f588bbbabdb2Jesse Wilson    /**
87350ae32218918eae80298bd1ab8e4f588bbbabdb2Jesse Wilson     * This test checks whether connections are gzipped by default. This
87450ae32218918eae80298bd1ab8e4f588bbbabdb2Jesse Wilson     * behavior in not required by the API, so a failure of this test does not
87550ae32218918eae80298bd1ab8e4f588bbbabdb2Jesse Wilson     * imply a bug in the implementation.
87650ae32218918eae80298bd1ab8e4f588bbbabdb2Jesse Wilson     */
87750ae32218918eae80298bd1ab8e4f588bbbabdb2Jesse Wilson    public void testGzipEncodingEnabledByDefault() throws IOException, InterruptedException {
87850ae32218918eae80298bd1ab8e4f588bbbabdb2Jesse Wilson        server.enqueue(new MockResponse()
87950ae32218918eae80298bd1ab8e4f588bbbabdb2Jesse Wilson                .setBody(gzip("ABCABCABC".getBytes("UTF-8")))
88050ae32218918eae80298bd1ab8e4f588bbbabdb2Jesse Wilson                .addHeader("Content-Encoding: gzip"));
88150ae32218918eae80298bd1ab8e4f588bbbabdb2Jesse Wilson        server.play();
88250ae32218918eae80298bd1ab8e4f588bbbabdb2Jesse Wilson
88350ae32218918eae80298bd1ab8e4f588bbbabdb2Jesse Wilson        URLConnection connection = server.getUrl("/").openConnection();
88450ae32218918eae80298bd1ab8e4f588bbbabdb2Jesse Wilson        assertEquals("ABCABCABC", readAscii(connection.getInputStream(), Integer.MAX_VALUE));
8858116f7e97e00d223e7fbe5c950c9a5e3277de124Jesse Wilson        assertNull(connection.getContentEncoding());
88650ae32218918eae80298bd1ab8e4f588bbbabdb2Jesse Wilson
88750ae32218918eae80298bd1ab8e4f588bbbabdb2Jesse Wilson        RecordedRequest request = server.takeRequest();
88850ae32218918eae80298bd1ab8e4f588bbbabdb2Jesse Wilson        assertContains(request.getHeaders(), "Accept-Encoding: gzip");
88950ae32218918eae80298bd1ab8e4f588bbbabdb2Jesse Wilson    }
89050ae32218918eae80298bd1ab8e4f588bbbabdb2Jesse Wilson
891deb236fb06f2a14861e7d40dea959f181cd5cf28Jesse Wilson    public void testClientConfiguredGzipContentEncoding() throws Exception {
892deb236fb06f2a14861e7d40dea959f181cd5cf28Jesse Wilson        server.enqueue(new MockResponse()
893deb236fb06f2a14861e7d40dea959f181cd5cf28Jesse Wilson                .setBody(gzip("ABCDEFGHIJKLMNOPQRSTUVWXYZ".getBytes("UTF-8")))
894deb236fb06f2a14861e7d40dea959f181cd5cf28Jesse Wilson                .addHeader("Content-Encoding: gzip"));
895deb236fb06f2a14861e7d40dea959f181cd5cf28Jesse Wilson        server.play();
896deb236fb06f2a14861e7d40dea959f181cd5cf28Jesse Wilson
897deb236fb06f2a14861e7d40dea959f181cd5cf28Jesse Wilson        URLConnection connection = server.getUrl("/").openConnection();
898deb236fb06f2a14861e7d40dea959f181cd5cf28Jesse Wilson        connection.addRequestProperty("Accept-Encoding", "gzip");
899deb236fb06f2a14861e7d40dea959f181cd5cf28Jesse Wilson        InputStream gunzippedIn = new GZIPInputStream(connection.getInputStream());
900deb236fb06f2a14861e7d40dea959f181cd5cf28Jesse Wilson        assertEquals("ABCDEFGHIJKLMNOPQRSTUVWXYZ", readAscii(gunzippedIn, Integer.MAX_VALUE));
901deb236fb06f2a14861e7d40dea959f181cd5cf28Jesse Wilson
902deb236fb06f2a14861e7d40dea959f181cd5cf28Jesse Wilson        RecordedRequest request = server.takeRequest();
903deb236fb06f2a14861e7d40dea959f181cd5cf28Jesse Wilson        assertContains(request.getHeaders(), "Accept-Encoding: gzip");
904deb236fb06f2a14861e7d40dea959f181cd5cf28Jesse Wilson    }
905deb236fb06f2a14861e7d40dea959f181cd5cf28Jesse Wilson
906deb236fb06f2a14861e7d40dea959f181cd5cf28Jesse Wilson    public void testGzipAndConnectionReuseWithFixedLength() throws Exception {
907deb236fb06f2a14861e7d40dea959f181cd5cf28Jesse Wilson        testClientConfiguredGzipContentEncodingAndConnectionReuse(TransferKind.FIXED_LENGTH);
908deb236fb06f2a14861e7d40dea959f181cd5cf28Jesse Wilson    }
909deb236fb06f2a14861e7d40dea959f181cd5cf28Jesse Wilson
910deb236fb06f2a14861e7d40dea959f181cd5cf28Jesse Wilson    public void testGzipAndConnectionReuseWithChunkedEncoding() throws Exception {
911deb236fb06f2a14861e7d40dea959f181cd5cf28Jesse Wilson        testClientConfiguredGzipContentEncodingAndConnectionReuse(TransferKind.CHUNKED);
912deb236fb06f2a14861e7d40dea959f181cd5cf28Jesse Wilson    }
913deb236fb06f2a14861e7d40dea959f181cd5cf28Jesse Wilson
91450ae32218918eae80298bd1ab8e4f588bbbabdb2Jesse Wilson    public void testClientConfiguredCustomContentEncoding() throws Exception {
91550ae32218918eae80298bd1ab8e4f588bbbabdb2Jesse Wilson        server.enqueue(new MockResponse()
91650ae32218918eae80298bd1ab8e4f588bbbabdb2Jesse Wilson                .setBody("ABCDE")
91750ae32218918eae80298bd1ab8e4f588bbbabdb2Jesse Wilson                .addHeader("Content-Encoding: custom"));
91850ae32218918eae80298bd1ab8e4f588bbbabdb2Jesse Wilson        server.play();
91950ae32218918eae80298bd1ab8e4f588bbbabdb2Jesse Wilson
92050ae32218918eae80298bd1ab8e4f588bbbabdb2Jesse Wilson        URLConnection connection = server.getUrl("/").openConnection();
92150ae32218918eae80298bd1ab8e4f588bbbabdb2Jesse Wilson        connection.addRequestProperty("Accept-Encoding", "custom");
92250ae32218918eae80298bd1ab8e4f588bbbabdb2Jesse Wilson        assertEquals("ABCDE", readAscii(connection.getInputStream(), Integer.MAX_VALUE));
92350ae32218918eae80298bd1ab8e4f588bbbabdb2Jesse Wilson
92450ae32218918eae80298bd1ab8e4f588bbbabdb2Jesse Wilson        RecordedRequest request = server.takeRequest();
92550ae32218918eae80298bd1ab8e4f588bbbabdb2Jesse Wilson        assertContains(request.getHeaders(), "Accept-Encoding: custom");
92650ae32218918eae80298bd1ab8e4f588bbbabdb2Jesse Wilson    }
92750ae32218918eae80298bd1ab8e4f588bbbabdb2Jesse Wilson
928deb236fb06f2a14861e7d40dea959f181cd5cf28Jesse Wilson    /**
929deb236fb06f2a14861e7d40dea959f181cd5cf28Jesse Wilson     * Test a bug where gzip input streams weren't exhausting the input stream,
930deb236fb06f2a14861e7d40dea959f181cd5cf28Jesse Wilson     * which corrupted the request that followed.
931deb236fb06f2a14861e7d40dea959f181cd5cf28Jesse Wilson     * http://code.google.com/p/android/issues/detail?id=7059
932deb236fb06f2a14861e7d40dea959f181cd5cf28Jesse Wilson     */
933deb236fb06f2a14861e7d40dea959f181cd5cf28Jesse Wilson    private void testClientConfiguredGzipContentEncodingAndConnectionReuse(
934deb236fb06f2a14861e7d40dea959f181cd5cf28Jesse Wilson            TransferKind transferKind) throws Exception {
935deb236fb06f2a14861e7d40dea959f181cd5cf28Jesse Wilson        MockResponse responseOne = new MockResponse();
936deb236fb06f2a14861e7d40dea959f181cd5cf28Jesse Wilson        responseOne.addHeader("Content-Encoding: gzip");
937deb236fb06f2a14861e7d40dea959f181cd5cf28Jesse Wilson        transferKind.setBody(responseOne, gzip("one (gzipped)".getBytes("UTF-8")), 5);
938deb236fb06f2a14861e7d40dea959f181cd5cf28Jesse Wilson        server.enqueue(responseOne);
939deb236fb06f2a14861e7d40dea959f181cd5cf28Jesse Wilson        MockResponse responseTwo = new MockResponse();
940deb236fb06f2a14861e7d40dea959f181cd5cf28Jesse Wilson        transferKind.setBody(responseTwo, "two (identity)", 5);
941deb236fb06f2a14861e7d40dea959f181cd5cf28Jesse Wilson        server.enqueue(responseTwo);
942deb236fb06f2a14861e7d40dea959f181cd5cf28Jesse Wilson        server.play();
943deb236fb06f2a14861e7d40dea959f181cd5cf28Jesse Wilson
944deb236fb06f2a14861e7d40dea959f181cd5cf28Jesse Wilson        URLConnection connection = server.getUrl("/").openConnection();
945deb236fb06f2a14861e7d40dea959f181cd5cf28Jesse Wilson        connection.addRequestProperty("Accept-Encoding", "gzip");
946deb236fb06f2a14861e7d40dea959f181cd5cf28Jesse Wilson        InputStream gunzippedIn = new GZIPInputStream(connection.getInputStream());
947deb236fb06f2a14861e7d40dea959f181cd5cf28Jesse Wilson        assertEquals("one (gzipped)", readAscii(gunzippedIn, Integer.MAX_VALUE));
948deb236fb06f2a14861e7d40dea959f181cd5cf28Jesse Wilson        assertEquals(0, server.takeRequest().getSequenceNumber());
949deb236fb06f2a14861e7d40dea959f181cd5cf28Jesse Wilson
950deb236fb06f2a14861e7d40dea959f181cd5cf28Jesse Wilson        connection = server.getUrl("/").openConnection();
951deb236fb06f2a14861e7d40dea959f181cd5cf28Jesse Wilson        assertEquals("two (identity)", readAscii(connection.getInputStream(), Integer.MAX_VALUE));
952deb236fb06f2a14861e7d40dea959f181cd5cf28Jesse Wilson        assertEquals(1, server.takeRequest().getSequenceNumber());
953deb236fb06f2a14861e7d40dea959f181cd5cf28Jesse Wilson    }
954deb236fb06f2a14861e7d40dea959f181cd5cf28Jesse Wilson
955deb236fb06f2a14861e7d40dea959f181cd5cf28Jesse Wilson    /**
956ffd579b668428272b78f5c6c64f9c89766f37c1aJesse Wilson     * Obnoxiously test that the chunk sizes transmitted exactly equal the
957ffd579b668428272b78f5c6c64f9c89766f37c1aJesse Wilson     * requested data+chunk header size. Although setChunkedStreamingMode()
958ffd579b668428272b78f5c6c64f9c89766f37c1aJesse Wilson     * isn't specific about whether the size applies to the data or the
959ffd579b668428272b78f5c6c64f9c89766f37c1aJesse Wilson     * complete chunk, the RI interprets it as a complete chunk.
960ffd579b668428272b78f5c6c64f9c89766f37c1aJesse Wilson     */
961ffd579b668428272b78f5c6c64f9c89766f37c1aJesse Wilson    public void testSetChunkedStreamingMode() throws IOException, InterruptedException {
962ffd579b668428272b78f5c6c64f9c89766f37c1aJesse Wilson        server.enqueue(new MockResponse());
963ffd579b668428272b78f5c6c64f9c89766f37c1aJesse Wilson        server.play();
964ffd579b668428272b78f5c6c64f9c89766f37c1aJesse Wilson
965ffd579b668428272b78f5c6c64f9c89766f37c1aJesse Wilson        HttpURLConnection urlConnection = (HttpURLConnection) server.getUrl("/").openConnection();
966ffd579b668428272b78f5c6c64f9c89766f37c1aJesse Wilson        urlConnection.setChunkedStreamingMode(8);
967ffd579b668428272b78f5c6c64f9c89766f37c1aJesse Wilson        urlConnection.setDoOutput(true);
968ffd579b668428272b78f5c6c64f9c89766f37c1aJesse Wilson        OutputStream outputStream = urlConnection.getOutputStream();
969ffd579b668428272b78f5c6c64f9c89766f37c1aJesse Wilson        outputStream.write("ABCDEFGHIJKLMNOPQ".getBytes("US-ASCII"));
970ffd579b668428272b78f5c6c64f9c89766f37c1aJesse Wilson        assertEquals(200, urlConnection.getResponseCode());
971ffd579b668428272b78f5c6c64f9c89766f37c1aJesse Wilson
972ffd579b668428272b78f5c6c64f9c89766f37c1aJesse Wilson        RecordedRequest request = server.takeRequest();
973ffd579b668428272b78f5c6c64f9c89766f37c1aJesse Wilson        assertEquals("ABCDEFGHIJKLMNOPQ", new String(request.getBody(), "US-ASCII"));
974ffd579b668428272b78f5c6c64f9c89766f37c1aJesse Wilson        assertEquals(Arrays.asList(3, 3, 3, 3, 3, 2), request.getChunkSizes());
975ffd579b668428272b78f5c6c64f9c89766f37c1aJesse Wilson    }
976ffd579b668428272b78f5c6c64f9c89766f37c1aJesse Wilson
977ffd579b668428272b78f5c6c64f9c89766f37c1aJesse Wilson    public void testAuthenticateWithFixedLengthStreaming() throws Exception {
978ffd579b668428272b78f5c6c64f9c89766f37c1aJesse Wilson        testAuthenticateWithStreamingPost(StreamingMode.FIXED_LENGTH);
979ffd579b668428272b78f5c6c64f9c89766f37c1aJesse Wilson    }
980ffd579b668428272b78f5c6c64f9c89766f37c1aJesse Wilson
981ffd579b668428272b78f5c6c64f9c89766f37c1aJesse Wilson    public void testAuthenticateWithChunkedStreaming() throws Exception {
982ffd579b668428272b78f5c6c64f9c89766f37c1aJesse Wilson        testAuthenticateWithStreamingPost(StreamingMode.CHUNKED);
983ffd579b668428272b78f5c6c64f9c89766f37c1aJesse Wilson    }
984ffd579b668428272b78f5c6c64f9c89766f37c1aJesse Wilson
985ffd579b668428272b78f5c6c64f9c89766f37c1aJesse Wilson    private void testAuthenticateWithStreamingPost(StreamingMode streamingMode) throws Exception {
986ffd579b668428272b78f5c6c64f9c89766f37c1aJesse Wilson        MockResponse pleaseAuthenticate = new MockResponse()
987ffd579b668428272b78f5c6c64f9c89766f37c1aJesse Wilson                .setResponseCode(401)
988ffd579b668428272b78f5c6c64f9c89766f37c1aJesse Wilson                .addHeader("WWW-Authenticate: Basic realm=\"protected area\"")
989ffd579b668428272b78f5c6c64f9c89766f37c1aJesse Wilson                .setBody("Please authenticate.");
990ffd579b668428272b78f5c6c64f9c89766f37c1aJesse Wilson        server.enqueue(pleaseAuthenticate);
991ffd579b668428272b78f5c6c64f9c89766f37c1aJesse Wilson        server.play();
992ffd579b668428272b78f5c6c64f9c89766f37c1aJesse Wilson
9935757cb35ad2e58d7accb7f5d3db6f2d5e72f097dJesse Wilson        Authenticator.setDefault(new SimpleAuthenticator());
994ffd579b668428272b78f5c6c64f9c89766f37c1aJesse Wilson        HttpURLConnection connection = (HttpURLConnection) server.getUrl("/").openConnection();
995ffd579b668428272b78f5c6c64f9c89766f37c1aJesse Wilson        connection.setDoOutput(true);
996ffd579b668428272b78f5c6c64f9c89766f37c1aJesse Wilson        byte[] requestBody = { 'A', 'B', 'C', 'D' };
997ffd579b668428272b78f5c6c64f9c89766f37c1aJesse Wilson        if (streamingMode == StreamingMode.FIXED_LENGTH) {
998ffd579b668428272b78f5c6c64f9c89766f37c1aJesse Wilson            connection.setFixedLengthStreamingMode(requestBody.length);
999ffd579b668428272b78f5c6c64f9c89766f37c1aJesse Wilson        } else if (streamingMode == StreamingMode.CHUNKED) {
1000ffd579b668428272b78f5c6c64f9c89766f37c1aJesse Wilson            connection.setChunkedStreamingMode(0);
1001ffd579b668428272b78f5c6c64f9c89766f37c1aJesse Wilson        }
1002ffd579b668428272b78f5c6c64f9c89766f37c1aJesse Wilson        OutputStream outputStream = connection.getOutputStream();
1003ffd579b668428272b78f5c6c64f9c89766f37c1aJesse Wilson        outputStream.write(requestBody);
1004ffd579b668428272b78f5c6c64f9c89766f37c1aJesse Wilson        outputStream.close();
1005ffd579b668428272b78f5c6c64f9c89766f37c1aJesse Wilson        try {
1006ffd579b668428272b78f5c6c64f9c89766f37c1aJesse Wilson            connection.getInputStream();
1007ffd579b668428272b78f5c6c64f9c89766f37c1aJesse Wilson            fail();
1008ffd579b668428272b78f5c6c64f9c89766f37c1aJesse Wilson        } catch (HttpRetryException expected) {
1009ffd579b668428272b78f5c6c64f9c89766f37c1aJesse Wilson        }
1010ffd579b668428272b78f5c6c64f9c89766f37c1aJesse Wilson
1011ffd579b668428272b78f5c6c64f9c89766f37c1aJesse Wilson        // no authorization header for the request...
1012ffd579b668428272b78f5c6c64f9c89766f37c1aJesse Wilson        RecordedRequest request = server.takeRequest();
1013ffd579b668428272b78f5c6c64f9c89766f37c1aJesse Wilson        assertContainsNoneMatching(request.getHeaders(), "Authorization: Basic .*");
1014ffd579b668428272b78f5c6c64f9c89766f37c1aJesse Wilson        assertEquals(Arrays.toString(requestBody), Arrays.toString(request.getBody()));
1015ffd579b668428272b78f5c6c64f9c89766f37c1aJesse Wilson    }
1016ffd579b668428272b78f5c6c64f9c89766f37c1aJesse Wilson
1017ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson    public void testSetValidRequestMethod() throws Exception {
1018ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson        server.play();
1019ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson        assertValidRequestMethod("GET");
1020ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson        assertValidRequestMethod("DELETE");
1021ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson        assertValidRequestMethod("HEAD");
1022ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson        assertValidRequestMethod("OPTIONS");
1023ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson        assertValidRequestMethod("POST");
1024ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson        assertValidRequestMethod("PUT");
1025ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson        assertValidRequestMethod("TRACE");
1026ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson    }
1027ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson
1028ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson    private void assertValidRequestMethod(String requestMethod) throws Exception {
1029ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson        HttpURLConnection connection = (HttpURLConnection) server.getUrl("/").openConnection();
1030ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson        connection.setRequestMethod(requestMethod);
1031ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson        assertEquals(requestMethod, connection.getRequestMethod());
1032ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson    }
1033ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson
1034ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson    public void testSetInvalidRequestMethodLowercase() throws Exception {
1035ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson        server.play();
1036ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson        assertInvalidRequestMethod("get");
1037ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson    }
1038ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson
1039ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson    public void testSetInvalidRequestMethodConnect() throws Exception {
1040ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson        server.play();
1041ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson        assertInvalidRequestMethod("CONNECT");
1042ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson    }
1043ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson
1044ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson    private void assertInvalidRequestMethod(String requestMethod) throws Exception {
1045ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson        HttpURLConnection connection = (HttpURLConnection) server.getUrl("/").openConnection();
1046ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson        try {
1047ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson            connection.setRequestMethod(requestMethod);
1048ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson            fail();
1049ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson        } catch (ProtocolException expected) {
1050ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson        }
1051ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson    }
1052ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson
1053ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson    public void testCannotSetNegativeFixedLengthStreamingMode() throws Exception {
1054ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson        server.play();
1055ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson        HttpURLConnection connection = (HttpURLConnection) server.getUrl("/").openConnection();
1056ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson        try {
1057ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson            connection.setFixedLengthStreamingMode(-2);
1058ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson            fail();
1059ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson        } catch (IllegalArgumentException expected) {
1060ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson        }
1061ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson    }
1062ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson
1063ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson    public void testCanSetNegativeChunkedStreamingMode() throws Exception {
1064ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson        server.play();
1065ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson        HttpURLConnection connection = (HttpURLConnection) server.getUrl("/").openConnection();
1066ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson        connection.setChunkedStreamingMode(-2);
1067ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson    }
1068ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson
1069ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson    public void testCannotSetFixedLengthStreamingModeAfterConnect() throws Exception {
1070ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson        server.enqueue(new MockResponse().setBody("A"));
1071ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson        server.play();
1072ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson        HttpURLConnection connection = (HttpURLConnection) server.getUrl("/").openConnection();
1073ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson        assertEquals("A", readAscii(connection.getInputStream(), Integer.MAX_VALUE));
1074ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson        try {
1075ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson            connection.setFixedLengthStreamingMode(1);
1076ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson            fail();
1077ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson        } catch (IllegalStateException expected) {
1078ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson        }
1079ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson    }
1080ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson
1081ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson    public void testCannotSetChunkedStreamingModeAfterConnect() throws Exception {
1082ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson        server.enqueue(new MockResponse().setBody("A"));
1083ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson        server.play();
1084ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson        HttpURLConnection connection = (HttpURLConnection) server.getUrl("/").openConnection();
1085ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson        assertEquals("A", readAscii(connection.getInputStream(), Integer.MAX_VALUE));
1086ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson        try {
1087ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson            connection.setChunkedStreamingMode(1);
1088ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson            fail();
1089ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson        } catch (IllegalStateException expected) {
1090ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson        }
1091ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson    }
1092ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson
1093ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson    public void testCannotSetFixedLengthStreamingModeAfterChunkedStreamingMode() throws Exception {
1094ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson        server.play();
1095ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson        HttpURLConnection connection = (HttpURLConnection) server.getUrl("/").openConnection();
1096ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson        connection.setChunkedStreamingMode(1);
1097ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson        try {
1098ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson            connection.setFixedLengthStreamingMode(1);
1099ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson            fail();
1100ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson        } catch (IllegalStateException expected) {
1101ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson        }
1102ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson    }
1103ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson
1104ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson    public void testCannotSetChunkedStreamingModeAfterFixedLengthStreamingMode() throws Exception {
1105ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson        server.play();
1106ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson        HttpURLConnection connection = (HttpURLConnection) server.getUrl("/").openConnection();
1107ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson        connection.setFixedLengthStreamingMode(1);
1108ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson        try {
1109ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson            connection.setChunkedStreamingMode(1);
1110ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson            fail();
1111ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson        } catch (IllegalStateException expected) {
1112ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson        }
1113ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson    }
1114ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson
111535eef71e8ce721c4199c525890ecc1a263054596Jesse Wilson    public void testSecureFixedLengthStreaming() throws Exception {
111635eef71e8ce721c4199c525890ecc1a263054596Jesse Wilson        testSecureStreamingPost(StreamingMode.FIXED_LENGTH);
111735eef71e8ce721c4199c525890ecc1a263054596Jesse Wilson    }
111835eef71e8ce721c4199c525890ecc1a263054596Jesse Wilson
111935eef71e8ce721c4199c525890ecc1a263054596Jesse Wilson    public void testSecureChunkedStreaming() throws Exception {
112035eef71e8ce721c4199c525890ecc1a263054596Jesse Wilson        testSecureStreamingPost(StreamingMode.CHUNKED);
112135eef71e8ce721c4199c525890ecc1a263054596Jesse Wilson    }
112235eef71e8ce721c4199c525890ecc1a263054596Jesse Wilson
112335eef71e8ce721c4199c525890ecc1a263054596Jesse Wilson    /**
112435eef71e8ce721c4199c525890ecc1a263054596Jesse Wilson     * Users have reported problems using HTTPS with streaming request bodies.
112535eef71e8ce721c4199c525890ecc1a263054596Jesse Wilson     * http://code.google.com/p/android/issues/detail?id=12860
112635eef71e8ce721c4199c525890ecc1a263054596Jesse Wilson     */
112735eef71e8ce721c4199c525890ecc1a263054596Jesse Wilson    private void testSecureStreamingPost(StreamingMode streamingMode) throws Exception {
112835eef71e8ce721c4199c525890ecc1a263054596Jesse Wilson        TestSSLContext testSSLContext = TestSSLContext.create();
112935eef71e8ce721c4199c525890ecc1a263054596Jesse Wilson        server.useHttps(testSSLContext.serverContext.getSocketFactory(), false);
113035eef71e8ce721c4199c525890ecc1a263054596Jesse Wilson        server.enqueue(new MockResponse().setBody("Success!"));
113135eef71e8ce721c4199c525890ecc1a263054596Jesse Wilson        server.play();
113235eef71e8ce721c4199c525890ecc1a263054596Jesse Wilson
113335eef71e8ce721c4199c525890ecc1a263054596Jesse Wilson        HttpsURLConnection connection = (HttpsURLConnection) server.getUrl("/").openConnection();
113435eef71e8ce721c4199c525890ecc1a263054596Jesse Wilson        connection.setSSLSocketFactory(testSSLContext.clientContext.getSocketFactory());
113535eef71e8ce721c4199c525890ecc1a263054596Jesse Wilson        connection.setDoOutput(true);
113635eef71e8ce721c4199c525890ecc1a263054596Jesse Wilson        byte[] requestBody = { 'A', 'B', 'C', 'D' };
113735eef71e8ce721c4199c525890ecc1a263054596Jesse Wilson        if (streamingMode == StreamingMode.FIXED_LENGTH) {
113835eef71e8ce721c4199c525890ecc1a263054596Jesse Wilson            connection.setFixedLengthStreamingMode(requestBody.length);
113935eef71e8ce721c4199c525890ecc1a263054596Jesse Wilson        } else if (streamingMode == StreamingMode.CHUNKED) {
114035eef71e8ce721c4199c525890ecc1a263054596Jesse Wilson            connection.setChunkedStreamingMode(0);
114135eef71e8ce721c4199c525890ecc1a263054596Jesse Wilson        }
114235eef71e8ce721c4199c525890ecc1a263054596Jesse Wilson        OutputStream outputStream = connection.getOutputStream();
114335eef71e8ce721c4199c525890ecc1a263054596Jesse Wilson        outputStream.write(requestBody);
114435eef71e8ce721c4199c525890ecc1a263054596Jesse Wilson        outputStream.close();
114535eef71e8ce721c4199c525890ecc1a263054596Jesse Wilson        assertEquals("Success!", readAscii(connection.getInputStream(), Integer.MAX_VALUE));
114635eef71e8ce721c4199c525890ecc1a263054596Jesse Wilson
114735eef71e8ce721c4199c525890ecc1a263054596Jesse Wilson        RecordedRequest request = server.takeRequest();
114835eef71e8ce721c4199c525890ecc1a263054596Jesse Wilson        assertEquals("POST / HTTP/1.1", request.getRequestLine());
114935eef71e8ce721c4199c525890ecc1a263054596Jesse Wilson        if (streamingMode == StreamingMode.FIXED_LENGTH) {
115035eef71e8ce721c4199c525890ecc1a263054596Jesse Wilson            assertEquals(Collections.<Integer>emptyList(), request.getChunkSizes());
115135eef71e8ce721c4199c525890ecc1a263054596Jesse Wilson        } else if (streamingMode == StreamingMode.CHUNKED) {
115235eef71e8ce721c4199c525890ecc1a263054596Jesse Wilson            assertEquals(Arrays.asList(4), request.getChunkSizes());
115335eef71e8ce721c4199c525890ecc1a263054596Jesse Wilson        }
115435eef71e8ce721c4199c525890ecc1a263054596Jesse Wilson        assertEquals(Arrays.toString(requestBody), Arrays.toString(request.getBody()));
115535eef71e8ce721c4199c525890ecc1a263054596Jesse Wilson    }
115635eef71e8ce721c4199c525890ecc1a263054596Jesse Wilson
1157ffd579b668428272b78f5c6c64f9c89766f37c1aJesse Wilson    enum StreamingMode {
1158ffd579b668428272b78f5c6c64f9c89766f37c1aJesse Wilson        FIXED_LENGTH, CHUNKED
1159ffd579b668428272b78f5c6c64f9c89766f37c1aJesse Wilson    }
1160ffd579b668428272b78f5c6c64f9c89766f37c1aJesse Wilson
1161ffd579b668428272b78f5c6c64f9c89766f37c1aJesse Wilson    public void testAuthenticateWithPost() throws Exception {
1162ffd579b668428272b78f5c6c64f9c89766f37c1aJesse Wilson        MockResponse pleaseAuthenticate = new MockResponse()
1163ffd579b668428272b78f5c6c64f9c89766f37c1aJesse Wilson                .setResponseCode(401)
1164ffd579b668428272b78f5c6c64f9c89766f37c1aJesse Wilson                .addHeader("WWW-Authenticate: Basic realm=\"protected area\"")
1165ffd579b668428272b78f5c6c64f9c89766f37c1aJesse Wilson                .setBody("Please authenticate.");
1166ffd579b668428272b78f5c6c64f9c89766f37c1aJesse Wilson        // fail auth three times...
1167ffd579b668428272b78f5c6c64f9c89766f37c1aJesse Wilson        server.enqueue(pleaseAuthenticate);
1168ffd579b668428272b78f5c6c64f9c89766f37c1aJesse Wilson        server.enqueue(pleaseAuthenticate);
1169ffd579b668428272b78f5c6c64f9c89766f37c1aJesse Wilson        server.enqueue(pleaseAuthenticate);
1170ffd579b668428272b78f5c6c64f9c89766f37c1aJesse Wilson        // ...then succeed the fourth time
1171ffd579b668428272b78f5c6c64f9c89766f37c1aJesse Wilson        server.enqueue(new MockResponse().setBody("Successful auth!"));
1172ffd579b668428272b78f5c6c64f9c89766f37c1aJesse Wilson        server.play();
1173ffd579b668428272b78f5c6c64f9c89766f37c1aJesse Wilson
11745757cb35ad2e58d7accb7f5d3db6f2d5e72f097dJesse Wilson        Authenticator.setDefault(new SimpleAuthenticator());
1175ffd579b668428272b78f5c6c64f9c89766f37c1aJesse Wilson        HttpURLConnection connection = (HttpURLConnection) server.getUrl("/").openConnection();
1176ffd579b668428272b78f5c6c64f9c89766f37c1aJesse Wilson        connection.setDoOutput(true);
1177ffd579b668428272b78f5c6c64f9c89766f37c1aJesse Wilson        byte[] requestBody = { 'A', 'B', 'C', 'D' };
1178ffd579b668428272b78f5c6c64f9c89766f37c1aJesse Wilson        OutputStream outputStream = connection.getOutputStream();
1179ffd579b668428272b78f5c6c64f9c89766f37c1aJesse Wilson        outputStream.write(requestBody);
1180ffd579b668428272b78f5c6c64f9c89766f37c1aJesse Wilson        outputStream.close();
1181ffd579b668428272b78f5c6c64f9c89766f37c1aJesse Wilson        assertEquals("Successful auth!", readAscii(connection.getInputStream(), Integer.MAX_VALUE));
1182ffd579b668428272b78f5c6c64f9c89766f37c1aJesse Wilson
1183ffd579b668428272b78f5c6c64f9c89766f37c1aJesse Wilson        // no authorization header for the first request...
1184ffd579b668428272b78f5c6c64f9c89766f37c1aJesse Wilson        RecordedRequest request = server.takeRequest();
11855757cb35ad2e58d7accb7f5d3db6f2d5e72f097dJesse Wilson        assertContainsNoneMatching(request.getHeaders(), "Authorization: .*");
1186ffd579b668428272b78f5c6c64f9c89766f37c1aJesse Wilson
1187da289bcd0a9e207cc03c752f7c21c9004056e179Jesse Wilson        // ...but the three requests that follow include an authorization header
1188ffd579b668428272b78f5c6c64f9c89766f37c1aJesse Wilson        for (int i = 0; i < 3; i++) {
1189ffd579b668428272b78f5c6c64f9c89766f37c1aJesse Wilson            request = server.takeRequest();
1190ffd579b668428272b78f5c6c64f9c89766f37c1aJesse Wilson            assertEquals("POST / HTTP/1.1", request.getRequestLine());
11915757cb35ad2e58d7accb7f5d3db6f2d5e72f097dJesse Wilson            assertContains(request.getHeaders(), "Authorization: Basic "
11925757cb35ad2e58d7accb7f5d3db6f2d5e72f097dJesse Wilson                    + SimpleAuthenticator.BASE_64_CREDENTIALS);
1193ffd579b668428272b78f5c6c64f9c89766f37c1aJesse Wilson            assertEquals(Arrays.toString(requestBody), Arrays.toString(request.getBody()));
1194ffd579b668428272b78f5c6c64f9c89766f37c1aJesse Wilson        }
1195ffd579b668428272b78f5c6c64f9c89766f37c1aJesse Wilson    }
1196ffd579b668428272b78f5c6c64f9c89766f37c1aJesse Wilson
1197ffd579b668428272b78f5c6c64f9c89766f37c1aJesse Wilson    public void testAuthenticateWithGet() throws Exception {
1198ffd579b668428272b78f5c6c64f9c89766f37c1aJesse Wilson        MockResponse pleaseAuthenticate = new MockResponse()
1199ffd579b668428272b78f5c6c64f9c89766f37c1aJesse Wilson                .setResponseCode(401)
1200ffd579b668428272b78f5c6c64f9c89766f37c1aJesse Wilson                .addHeader("WWW-Authenticate: Basic realm=\"protected area\"")
1201ffd579b668428272b78f5c6c64f9c89766f37c1aJesse Wilson                .setBody("Please authenticate.");
1202ffd579b668428272b78f5c6c64f9c89766f37c1aJesse Wilson        // fail auth three times...
1203ffd579b668428272b78f5c6c64f9c89766f37c1aJesse Wilson        server.enqueue(pleaseAuthenticate);
1204ffd579b668428272b78f5c6c64f9c89766f37c1aJesse Wilson        server.enqueue(pleaseAuthenticate);
1205ffd579b668428272b78f5c6c64f9c89766f37c1aJesse Wilson        server.enqueue(pleaseAuthenticate);
1206ffd579b668428272b78f5c6c64f9c89766f37c1aJesse Wilson        // ...then succeed the fourth time
1207ffd579b668428272b78f5c6c64f9c89766f37c1aJesse Wilson        server.enqueue(new MockResponse().setBody("Successful auth!"));
1208ffd579b668428272b78f5c6c64f9c89766f37c1aJesse Wilson        server.play();
1209ffd579b668428272b78f5c6c64f9c89766f37c1aJesse Wilson
12105757cb35ad2e58d7accb7f5d3db6f2d5e72f097dJesse Wilson        SimpleAuthenticator authenticator = new SimpleAuthenticator();
12115757cb35ad2e58d7accb7f5d3db6f2d5e72f097dJesse Wilson        Authenticator.setDefault(authenticator);
1212ffd579b668428272b78f5c6c64f9c89766f37c1aJesse Wilson        HttpURLConnection connection = (HttpURLConnection) server.getUrl("/").openConnection();
1213ffd579b668428272b78f5c6c64f9c89766f37c1aJesse Wilson        assertEquals("Successful auth!", readAscii(connection.getInputStream(), Integer.MAX_VALUE));
12145757cb35ad2e58d7accb7f5d3db6f2d5e72f097dJesse Wilson        assertEquals(Authenticator.RequestorType.SERVER, authenticator.requestorType);
12155757cb35ad2e58d7accb7f5d3db6f2d5e72f097dJesse Wilson        assertEquals(server.getPort(), authenticator.requestingPort);
12165757cb35ad2e58d7accb7f5d3db6f2d5e72f097dJesse Wilson        assertEquals(InetAddress.getByName(server.getHostName()), authenticator.requestingSite);
12175757cb35ad2e58d7accb7f5d3db6f2d5e72f097dJesse Wilson        assertEquals("protected area", authenticator.requestingPrompt);
12185757cb35ad2e58d7accb7f5d3db6f2d5e72f097dJesse Wilson        assertEquals("http", authenticator.requestingProtocol);
12195757cb35ad2e58d7accb7f5d3db6f2d5e72f097dJesse Wilson        assertEquals("Basic", authenticator.requestingScheme);
1220ffd579b668428272b78f5c6c64f9c89766f37c1aJesse Wilson
1221ffd579b668428272b78f5c6c64f9c89766f37c1aJesse Wilson        // no authorization header for the first request...
1222ffd579b668428272b78f5c6c64f9c89766f37c1aJesse Wilson        RecordedRequest request = server.takeRequest();
12235757cb35ad2e58d7accb7f5d3db6f2d5e72f097dJesse Wilson        assertContainsNoneMatching(request.getHeaders(), "Authorization: .*");
1224ffd579b668428272b78f5c6c64f9c89766f37c1aJesse Wilson
1225ffd579b668428272b78f5c6c64f9c89766f37c1aJesse Wilson        // ...but the three requests that follow requests include an authorization header
1226ffd579b668428272b78f5c6c64f9c89766f37c1aJesse Wilson        for (int i = 0; i < 3; i++) {
1227ffd579b668428272b78f5c6c64f9c89766f37c1aJesse Wilson            request = server.takeRequest();
1228ffd579b668428272b78f5c6c64f9c89766f37c1aJesse Wilson            assertEquals("GET / HTTP/1.1", request.getRequestLine());
12295757cb35ad2e58d7accb7f5d3db6f2d5e72f097dJesse Wilson            assertContains(request.getHeaders(), "Authorization: Basic "
12305757cb35ad2e58d7accb7f5d3db6f2d5e72f097dJesse Wilson                    + SimpleAuthenticator.BASE_64_CREDENTIALS);
1231ffd579b668428272b78f5c6c64f9c89766f37c1aJesse Wilson        }
1232ffd579b668428272b78f5c6c64f9c89766f37c1aJesse Wilson    }
1233ffd579b668428272b78f5c6c64f9c89766f37c1aJesse Wilson
12345757cb35ad2e58d7accb7f5d3db6f2d5e72f097dJesse Wilson    // http://code.google.com/p/android/issues/detail?id=19081
12355757cb35ad2e58d7accb7f5d3db6f2d5e72f097dJesse Wilson    public void testAuthenticateWithCommaSeparatedAuthenticationMethods() throws Exception {
12365757cb35ad2e58d7accb7f5d3db6f2d5e72f097dJesse Wilson        server.enqueue(new MockResponse()
12375757cb35ad2e58d7accb7f5d3db6f2d5e72f097dJesse Wilson                .setResponseCode(401)
12385757cb35ad2e58d7accb7f5d3db6f2d5e72f097dJesse Wilson                .addHeader("WWW-Authenticate: Scheme1 realm=\"a\", Scheme2 realm=\"b\", "
12395757cb35ad2e58d7accb7f5d3db6f2d5e72f097dJesse Wilson                        + "Scheme3 realm=\"c\"")
12405757cb35ad2e58d7accb7f5d3db6f2d5e72f097dJesse Wilson                .setBody("Please authenticate."));
12415757cb35ad2e58d7accb7f5d3db6f2d5e72f097dJesse Wilson        server.enqueue(new MockResponse().setBody("Successful auth!"));
12425757cb35ad2e58d7accb7f5d3db6f2d5e72f097dJesse Wilson        server.play();
12435757cb35ad2e58d7accb7f5d3db6f2d5e72f097dJesse Wilson
12445757cb35ad2e58d7accb7f5d3db6f2d5e72f097dJesse Wilson        SimpleAuthenticator authenticator = new SimpleAuthenticator();
12455757cb35ad2e58d7accb7f5d3db6f2d5e72f097dJesse Wilson        authenticator.expectedPrompt = "b";
12465757cb35ad2e58d7accb7f5d3db6f2d5e72f097dJesse Wilson        Authenticator.setDefault(authenticator);
12475757cb35ad2e58d7accb7f5d3db6f2d5e72f097dJesse Wilson        HttpURLConnection connection = (HttpURLConnection) server.getUrl("/").openConnection();
12485757cb35ad2e58d7accb7f5d3db6f2d5e72f097dJesse Wilson        assertEquals("Successful auth!", readAscii(connection.getInputStream(), Integer.MAX_VALUE));
12495757cb35ad2e58d7accb7f5d3db6f2d5e72f097dJesse Wilson
12505757cb35ad2e58d7accb7f5d3db6f2d5e72f097dJesse Wilson        assertContainsNoneMatching(server.takeRequest().getHeaders(), "Authorization: .*");
12515757cb35ad2e58d7accb7f5d3db6f2d5e72f097dJesse Wilson        assertContains(server.takeRequest().getHeaders(),
12525757cb35ad2e58d7accb7f5d3db6f2d5e72f097dJesse Wilson                "Authorization: Scheme2 " + SimpleAuthenticator.BASE_64_CREDENTIALS);
12535757cb35ad2e58d7accb7f5d3db6f2d5e72f097dJesse Wilson        assertEquals("Scheme2", authenticator.requestingScheme);
12545757cb35ad2e58d7accb7f5d3db6f2d5e72f097dJesse Wilson    }
12555757cb35ad2e58d7accb7f5d3db6f2d5e72f097dJesse Wilson
12565757cb35ad2e58d7accb7f5d3db6f2d5e72f097dJesse Wilson    public void testAuthenticateWithMultipleAuthenticationHeaders() throws Exception {
12575757cb35ad2e58d7accb7f5d3db6f2d5e72f097dJesse Wilson        server.enqueue(new MockResponse()
12585757cb35ad2e58d7accb7f5d3db6f2d5e72f097dJesse Wilson                .setResponseCode(401)
12595757cb35ad2e58d7accb7f5d3db6f2d5e72f097dJesse Wilson                .addHeader("WWW-Authenticate: Scheme1 realm=\"a\"")
12605757cb35ad2e58d7accb7f5d3db6f2d5e72f097dJesse Wilson                .addHeader("WWW-Authenticate: Scheme2 realm=\"b\"")
12615757cb35ad2e58d7accb7f5d3db6f2d5e72f097dJesse Wilson                .addHeader("WWW-Authenticate: Scheme3 realm=\"c\"")
12625757cb35ad2e58d7accb7f5d3db6f2d5e72f097dJesse Wilson                .setBody("Please authenticate."));
12635757cb35ad2e58d7accb7f5d3db6f2d5e72f097dJesse Wilson        server.enqueue(new MockResponse().setBody("Successful auth!"));
12645757cb35ad2e58d7accb7f5d3db6f2d5e72f097dJesse Wilson        server.play();
12655757cb35ad2e58d7accb7f5d3db6f2d5e72f097dJesse Wilson
12665757cb35ad2e58d7accb7f5d3db6f2d5e72f097dJesse Wilson        SimpleAuthenticator authenticator = new SimpleAuthenticator();
12675757cb35ad2e58d7accb7f5d3db6f2d5e72f097dJesse Wilson        authenticator.expectedPrompt = "b";
12685757cb35ad2e58d7accb7f5d3db6f2d5e72f097dJesse Wilson        Authenticator.setDefault(authenticator);
12695757cb35ad2e58d7accb7f5d3db6f2d5e72f097dJesse Wilson        HttpURLConnection connection = (HttpURLConnection) server.getUrl("/").openConnection();
12705757cb35ad2e58d7accb7f5d3db6f2d5e72f097dJesse Wilson        assertEquals("Successful auth!", readAscii(connection.getInputStream(), Integer.MAX_VALUE));
12715757cb35ad2e58d7accb7f5d3db6f2d5e72f097dJesse Wilson
12725757cb35ad2e58d7accb7f5d3db6f2d5e72f097dJesse Wilson        assertContainsNoneMatching(server.takeRequest().getHeaders(), "Authorization: .*");
12735757cb35ad2e58d7accb7f5d3db6f2d5e72f097dJesse Wilson        assertContains(server.takeRequest().getHeaders(),
12745757cb35ad2e58d7accb7f5d3db6f2d5e72f097dJesse Wilson                "Authorization: Scheme2 " + SimpleAuthenticator.BASE_64_CREDENTIALS);
12755757cb35ad2e58d7accb7f5d3db6f2d5e72f097dJesse Wilson        assertEquals("Scheme2", authenticator.requestingScheme);
12765757cb35ad2e58d7accb7f5d3db6f2d5e72f097dJesse Wilson    }
12775757cb35ad2e58d7accb7f5d3db6f2d5e72f097dJesse Wilson
1278c0372d90016d241ac979faa6fa1731f30b6f2a03Jesse Wilson    public void testRedirectedWithChunkedEncoding() throws Exception {
1279c0372d90016d241ac979faa6fa1731f30b6f2a03Jesse Wilson        testRedirected(TransferKind.CHUNKED, true);
1280c0372d90016d241ac979faa6fa1731f30b6f2a03Jesse Wilson    }
1281c0372d90016d241ac979faa6fa1731f30b6f2a03Jesse Wilson
1282c0372d90016d241ac979faa6fa1731f30b6f2a03Jesse Wilson    public void testRedirectedWithContentLengthHeader() throws Exception {
1283c0372d90016d241ac979faa6fa1731f30b6f2a03Jesse Wilson        testRedirected(TransferKind.FIXED_LENGTH, true);
1284c0372d90016d241ac979faa6fa1731f30b6f2a03Jesse Wilson    }
1285c0372d90016d241ac979faa6fa1731f30b6f2a03Jesse Wilson
1286c0372d90016d241ac979faa6fa1731f30b6f2a03Jesse Wilson    public void testRedirectedWithNoLengthHeaders() throws Exception {
1287c0372d90016d241ac979faa6fa1731f30b6f2a03Jesse Wilson        testRedirected(TransferKind.END_OF_STREAM, false);
1288c0372d90016d241ac979faa6fa1731f30b6f2a03Jesse Wilson    }
1289c0372d90016d241ac979faa6fa1731f30b6f2a03Jesse Wilson
1290c0372d90016d241ac979faa6fa1731f30b6f2a03Jesse Wilson    private void testRedirected(TransferKind transferKind, boolean reuse) throws Exception {
1291c0372d90016d241ac979faa6fa1731f30b6f2a03Jesse Wilson        MockResponse response = new MockResponse()
1292c0372d90016d241ac979faa6fa1731f30b6f2a03Jesse Wilson                .setResponseCode(HttpURLConnection.HTTP_MOVED_TEMP)
1293c0372d90016d241ac979faa6fa1731f30b6f2a03Jesse Wilson                .addHeader("Location: /foo");
1294c0372d90016d241ac979faa6fa1731f30b6f2a03Jesse Wilson        transferKind.setBody(response, "This page has moved!", 10);
1295c0372d90016d241ac979faa6fa1731f30b6f2a03Jesse Wilson        server.enqueue(response);
1296c0372d90016d241ac979faa6fa1731f30b6f2a03Jesse Wilson        server.enqueue(new MockResponse().setBody("This is the new location!"));
1297c0372d90016d241ac979faa6fa1731f30b6f2a03Jesse Wilson        server.play();
1298c0372d90016d241ac979faa6fa1731f30b6f2a03Jesse Wilson
1299c0372d90016d241ac979faa6fa1731f30b6f2a03Jesse Wilson        URLConnection connection = server.getUrl("/").openConnection();
1300c0372d90016d241ac979faa6fa1731f30b6f2a03Jesse Wilson        assertEquals("This is the new location!",
1301c0372d90016d241ac979faa6fa1731f30b6f2a03Jesse Wilson                readAscii(connection.getInputStream(), Integer.MAX_VALUE));
1302c0372d90016d241ac979faa6fa1731f30b6f2a03Jesse Wilson
1303c0372d90016d241ac979faa6fa1731f30b6f2a03Jesse Wilson        RecordedRequest first = server.takeRequest();
1304c0372d90016d241ac979faa6fa1731f30b6f2a03Jesse Wilson        assertEquals("GET / HTTP/1.1", first.getRequestLine());
1305c0372d90016d241ac979faa6fa1731f30b6f2a03Jesse Wilson        RecordedRequest retry = server.takeRequest();
1306c0372d90016d241ac979faa6fa1731f30b6f2a03Jesse Wilson        assertEquals("GET /foo HTTP/1.1", retry.getRequestLine());
1307c0372d90016d241ac979faa6fa1731f30b6f2a03Jesse Wilson        if (reuse) {
1308c0372d90016d241ac979faa6fa1731f30b6f2a03Jesse Wilson            assertEquals("Expected connection reuse", 1, retry.getSequenceNumber());
1309c0372d90016d241ac979faa6fa1731f30b6f2a03Jesse Wilson        }
1310c0372d90016d241ac979faa6fa1731f30b6f2a03Jesse Wilson    }
1311c0372d90016d241ac979faa6fa1731f30b6f2a03Jesse Wilson
1312c0372d90016d241ac979faa6fa1731f30b6f2a03Jesse Wilson    public void testRedirectedOnHttps() throws IOException, InterruptedException {
1313c0372d90016d241ac979faa6fa1731f30b6f2a03Jesse Wilson        TestSSLContext testSSLContext = TestSSLContext.create();
1314059dbc04218144f985b20a228bbe98139d400d0cBrian Carlstrom        server.useHttps(testSSLContext.serverContext.getSocketFactory(), false);
1315c0372d90016d241ac979faa6fa1731f30b6f2a03Jesse Wilson        server.enqueue(new MockResponse()
1316c0372d90016d241ac979faa6fa1731f30b6f2a03Jesse Wilson                .setResponseCode(HttpURLConnection.HTTP_MOVED_TEMP)
1317c0372d90016d241ac979faa6fa1731f30b6f2a03Jesse Wilson                .addHeader("Location: /foo")
1318c0372d90016d241ac979faa6fa1731f30b6f2a03Jesse Wilson                .setBody("This page has moved!"));
1319c0372d90016d241ac979faa6fa1731f30b6f2a03Jesse Wilson        server.enqueue(new MockResponse().setBody("This is the new location!"));
1320c0372d90016d241ac979faa6fa1731f30b6f2a03Jesse Wilson        server.play();
1321c0372d90016d241ac979faa6fa1731f30b6f2a03Jesse Wilson
1322c0372d90016d241ac979faa6fa1731f30b6f2a03Jesse Wilson        HttpsURLConnection connection = (HttpsURLConnection) server.getUrl("/").openConnection();
1323059dbc04218144f985b20a228bbe98139d400d0cBrian Carlstrom        connection.setSSLSocketFactory(testSSLContext.clientContext.getSocketFactory());
1324c0372d90016d241ac979faa6fa1731f30b6f2a03Jesse Wilson        assertEquals("This is the new location!",
1325c0372d90016d241ac979faa6fa1731f30b6f2a03Jesse Wilson                readAscii(connection.getInputStream(), Integer.MAX_VALUE));
1326c0372d90016d241ac979faa6fa1731f30b6f2a03Jesse Wilson
1327c0372d90016d241ac979faa6fa1731f30b6f2a03Jesse Wilson        RecordedRequest first = server.takeRequest();
1328c0372d90016d241ac979faa6fa1731f30b6f2a03Jesse Wilson        assertEquals("GET / HTTP/1.1", first.getRequestLine());
1329c0372d90016d241ac979faa6fa1731f30b6f2a03Jesse Wilson        RecordedRequest retry = server.takeRequest();
1330c0372d90016d241ac979faa6fa1731f30b6f2a03Jesse Wilson        assertEquals("GET /foo HTTP/1.1", retry.getRequestLine());
1331c0372d90016d241ac979faa6fa1731f30b6f2a03Jesse Wilson        assertEquals("Expected connection reuse", 1, retry.getSequenceNumber());
1332c0372d90016d241ac979faa6fa1731f30b6f2a03Jesse Wilson    }
1333c0372d90016d241ac979faa6fa1731f30b6f2a03Jesse Wilson
1334c0372d90016d241ac979faa6fa1731f30b6f2a03Jesse Wilson    public void testNotRedirectedFromHttpsToHttp() throws IOException, InterruptedException {
1335c0372d90016d241ac979faa6fa1731f30b6f2a03Jesse Wilson        TestSSLContext testSSLContext = TestSSLContext.create();
1336059dbc04218144f985b20a228bbe98139d400d0cBrian Carlstrom        server.useHttps(testSSLContext.serverContext.getSocketFactory(), false);
1337c0372d90016d241ac979faa6fa1731f30b6f2a03Jesse Wilson        server.enqueue(new MockResponse()
1338c0372d90016d241ac979faa6fa1731f30b6f2a03Jesse Wilson                .setResponseCode(HttpURLConnection.HTTP_MOVED_TEMP)
1339c0372d90016d241ac979faa6fa1731f30b6f2a03Jesse Wilson                .addHeader("Location: http://anyhost/foo")
1340c0372d90016d241ac979faa6fa1731f30b6f2a03Jesse Wilson                .setBody("This page has moved!"));
1341c0372d90016d241ac979faa6fa1731f30b6f2a03Jesse Wilson        server.play();
1342c0372d90016d241ac979faa6fa1731f30b6f2a03Jesse Wilson
1343c0372d90016d241ac979faa6fa1731f30b6f2a03Jesse Wilson        HttpsURLConnection connection = (HttpsURLConnection) server.getUrl("/").openConnection();
1344059dbc04218144f985b20a228bbe98139d400d0cBrian Carlstrom        connection.setSSLSocketFactory(testSSLContext.clientContext.getSocketFactory());
1345c0372d90016d241ac979faa6fa1731f30b6f2a03Jesse Wilson        assertEquals("This page has moved!",
1346c0372d90016d241ac979faa6fa1731f30b6f2a03Jesse Wilson                readAscii(connection.getInputStream(), Integer.MAX_VALUE));
1347c0372d90016d241ac979faa6fa1731f30b6f2a03Jesse Wilson    }
1348c0372d90016d241ac979faa6fa1731f30b6f2a03Jesse Wilson
1349c0372d90016d241ac979faa6fa1731f30b6f2a03Jesse Wilson    public void testNotRedirectedFromHttpToHttps() throws IOException, InterruptedException {
1350c0372d90016d241ac979faa6fa1731f30b6f2a03Jesse Wilson        server.enqueue(new MockResponse()
1351c0372d90016d241ac979faa6fa1731f30b6f2a03Jesse Wilson                .setResponseCode(HttpURLConnection.HTTP_MOVED_TEMP)
1352c0372d90016d241ac979faa6fa1731f30b6f2a03Jesse Wilson                .addHeader("Location: https://anyhost/foo")
1353c0372d90016d241ac979faa6fa1731f30b6f2a03Jesse Wilson                .setBody("This page has moved!"));
1354c0372d90016d241ac979faa6fa1731f30b6f2a03Jesse Wilson        server.play();
1355c0372d90016d241ac979faa6fa1731f30b6f2a03Jesse Wilson
1356c0372d90016d241ac979faa6fa1731f30b6f2a03Jesse Wilson        HttpURLConnection connection = (HttpURLConnection) server.getUrl("/").openConnection();
1357c0372d90016d241ac979faa6fa1731f30b6f2a03Jesse Wilson        assertEquals("This page has moved!",
1358c0372d90016d241ac979faa6fa1731f30b6f2a03Jesse Wilson                readAscii(connection.getInputStream(), Integer.MAX_VALUE));
1359c0372d90016d241ac979faa6fa1731f30b6f2a03Jesse Wilson    }
1360c0372d90016d241ac979faa6fa1731f30b6f2a03Jesse Wilson
1361c0372d90016d241ac979faa6fa1731f30b6f2a03Jesse Wilson    public void testRedirectToAnotherOriginServer() throws Exception {
1362c0372d90016d241ac979faa6fa1731f30b6f2a03Jesse Wilson        MockWebServer server2 = new MockWebServer();
1363c0372d90016d241ac979faa6fa1731f30b6f2a03Jesse Wilson        server2.enqueue(new MockResponse().setBody("This is the 2nd server!"));
1364c0372d90016d241ac979faa6fa1731f30b6f2a03Jesse Wilson        server2.play();
1365c0372d90016d241ac979faa6fa1731f30b6f2a03Jesse Wilson
1366c0372d90016d241ac979faa6fa1731f30b6f2a03Jesse Wilson        server.enqueue(new MockResponse()
1367c0372d90016d241ac979faa6fa1731f30b6f2a03Jesse Wilson                .setResponseCode(HttpURLConnection.HTTP_MOVED_TEMP)
1368c0372d90016d241ac979faa6fa1731f30b6f2a03Jesse Wilson                .addHeader("Location: " + server2.getUrl("/").toString())
1369c0372d90016d241ac979faa6fa1731f30b6f2a03Jesse Wilson                .setBody("This page has moved!"));
1370c0372d90016d241ac979faa6fa1731f30b6f2a03Jesse Wilson        server.enqueue(new MockResponse().setBody("This is the first server again!"));
1371c0372d90016d241ac979faa6fa1731f30b6f2a03Jesse Wilson        server.play();
1372c0372d90016d241ac979faa6fa1731f30b6f2a03Jesse Wilson
1373c0372d90016d241ac979faa6fa1731f30b6f2a03Jesse Wilson        URLConnection connection = server.getUrl("/").openConnection();
1374c0372d90016d241ac979faa6fa1731f30b6f2a03Jesse Wilson        assertEquals("This is the 2nd server!",
1375c0372d90016d241ac979faa6fa1731f30b6f2a03Jesse Wilson                readAscii(connection.getInputStream(), Integer.MAX_VALUE));
1376c0372d90016d241ac979faa6fa1731f30b6f2a03Jesse Wilson        assertEquals(server2.getUrl("/"), connection.getURL());
1377c0372d90016d241ac979faa6fa1731f30b6f2a03Jesse Wilson
1378c0372d90016d241ac979faa6fa1731f30b6f2a03Jesse Wilson        // make sure the first server was careful to recycle the connection
1379c0372d90016d241ac979faa6fa1731f30b6f2a03Jesse Wilson        assertEquals("This is the first server again!",
1380c0372d90016d241ac979faa6fa1731f30b6f2a03Jesse Wilson                readAscii(server.getUrl("/").openStream(), Integer.MAX_VALUE));
1381c0372d90016d241ac979faa6fa1731f30b6f2a03Jesse Wilson
1382c0372d90016d241ac979faa6fa1731f30b6f2a03Jesse Wilson        RecordedRequest first = server.takeRequest();
13830c2fd828abec671333b8b88281825fd27a783723Jesse Wilson        assertContains(first.getHeaders(), "Host: " + hostName + ":" + server.getPort());
1384c0372d90016d241ac979faa6fa1731f30b6f2a03Jesse Wilson        RecordedRequest second = server2.takeRequest();
13850c2fd828abec671333b8b88281825fd27a783723Jesse Wilson        assertContains(second.getHeaders(), "Host: " + hostName + ":" + server2.getPort());
1386c0372d90016d241ac979faa6fa1731f30b6f2a03Jesse Wilson        RecordedRequest third = server.takeRequest();
1387c0372d90016d241ac979faa6fa1731f30b6f2a03Jesse Wilson        assertEquals("Expected connection reuse", 1, third.getSequenceNumber());
1388c0372d90016d241ac979faa6fa1731f30b6f2a03Jesse Wilson
1389c0372d90016d241ac979faa6fa1731f30b6f2a03Jesse Wilson        server2.shutdown();
1390c0372d90016d241ac979faa6fa1731f30b6f2a03Jesse Wilson    }
1391c0372d90016d241ac979faa6fa1731f30b6f2a03Jesse Wilson
1392d742d7fc7f0593eb8c6e4ac9dd4c0f6a80374e46Jesse Wilson    public void testResponse300MultipleChoiceWithPost() throws Exception {
1393d742d7fc7f0593eb8c6e4ac9dd4c0f6a80374e46Jesse Wilson        // Chrome doesn't follow the redirect, but Firefox and the RI both do
1394d742d7fc7f0593eb8c6e4ac9dd4c0f6a80374e46Jesse Wilson        testResponseRedirectedWithPost(HttpURLConnection.HTTP_MULT_CHOICE);
1395d742d7fc7f0593eb8c6e4ac9dd4c0f6a80374e46Jesse Wilson    }
1396d742d7fc7f0593eb8c6e4ac9dd4c0f6a80374e46Jesse Wilson
1397d742d7fc7f0593eb8c6e4ac9dd4c0f6a80374e46Jesse Wilson    public void testResponse301MovedPermanentlyWithPost() throws Exception {
1398d742d7fc7f0593eb8c6e4ac9dd4c0f6a80374e46Jesse Wilson        testResponseRedirectedWithPost(HttpURLConnection.HTTP_MOVED_PERM);
1399d742d7fc7f0593eb8c6e4ac9dd4c0f6a80374e46Jesse Wilson    }
1400d742d7fc7f0593eb8c6e4ac9dd4c0f6a80374e46Jesse Wilson
1401d742d7fc7f0593eb8c6e4ac9dd4c0f6a80374e46Jesse Wilson    public void testResponse302MovedTemporarilyWithPost() throws Exception {
1402d742d7fc7f0593eb8c6e4ac9dd4c0f6a80374e46Jesse Wilson        testResponseRedirectedWithPost(HttpURLConnection.HTTP_MOVED_TEMP);
1403d742d7fc7f0593eb8c6e4ac9dd4c0f6a80374e46Jesse Wilson    }
1404d742d7fc7f0593eb8c6e4ac9dd4c0f6a80374e46Jesse Wilson
1405d742d7fc7f0593eb8c6e4ac9dd4c0f6a80374e46Jesse Wilson    public void testResponse303SeeOtherWithPost() throws Exception {
1406d742d7fc7f0593eb8c6e4ac9dd4c0f6a80374e46Jesse Wilson        testResponseRedirectedWithPost(HttpURLConnection.HTTP_SEE_OTHER);
1407d742d7fc7f0593eb8c6e4ac9dd4c0f6a80374e46Jesse Wilson    }
1408d742d7fc7f0593eb8c6e4ac9dd4c0f6a80374e46Jesse Wilson
1409d742d7fc7f0593eb8c6e4ac9dd4c0f6a80374e46Jesse Wilson    private void testResponseRedirectedWithPost(int redirectCode) throws Exception {
1410d742d7fc7f0593eb8c6e4ac9dd4c0f6a80374e46Jesse Wilson        server.enqueue(new MockResponse()
1411d742d7fc7f0593eb8c6e4ac9dd4c0f6a80374e46Jesse Wilson                .setResponseCode(redirectCode)
1412d742d7fc7f0593eb8c6e4ac9dd4c0f6a80374e46Jesse Wilson                .addHeader("Location: /page2")
1413d742d7fc7f0593eb8c6e4ac9dd4c0f6a80374e46Jesse Wilson                .setBody("This page has moved!"));
1414d742d7fc7f0593eb8c6e4ac9dd4c0f6a80374e46Jesse Wilson        server.enqueue(new MockResponse().setBody("Page 2"));
1415d742d7fc7f0593eb8c6e4ac9dd4c0f6a80374e46Jesse Wilson        server.play();
1416d742d7fc7f0593eb8c6e4ac9dd4c0f6a80374e46Jesse Wilson
1417d742d7fc7f0593eb8c6e4ac9dd4c0f6a80374e46Jesse Wilson        HttpURLConnection connection = (HttpURLConnection) server.getUrl("/page1").openConnection();
1418d742d7fc7f0593eb8c6e4ac9dd4c0f6a80374e46Jesse Wilson        connection.setDoOutput(true);
1419d742d7fc7f0593eb8c6e4ac9dd4c0f6a80374e46Jesse Wilson        byte[] requestBody = { 'A', 'B', 'C', 'D' };
1420d742d7fc7f0593eb8c6e4ac9dd4c0f6a80374e46Jesse Wilson        OutputStream outputStream = connection.getOutputStream();
1421d742d7fc7f0593eb8c6e4ac9dd4c0f6a80374e46Jesse Wilson        outputStream.write(requestBody);
1422d742d7fc7f0593eb8c6e4ac9dd4c0f6a80374e46Jesse Wilson        outputStream.close();
1423d742d7fc7f0593eb8c6e4ac9dd4c0f6a80374e46Jesse Wilson        assertEquals("Page 2", readAscii(connection.getInputStream(), Integer.MAX_VALUE));
1424d742d7fc7f0593eb8c6e4ac9dd4c0f6a80374e46Jesse Wilson        assertTrue(connection.getDoOutput());
1425d742d7fc7f0593eb8c6e4ac9dd4c0f6a80374e46Jesse Wilson
1426d742d7fc7f0593eb8c6e4ac9dd4c0f6a80374e46Jesse Wilson        RecordedRequest page1 = server.takeRequest();
1427d742d7fc7f0593eb8c6e4ac9dd4c0f6a80374e46Jesse Wilson        assertEquals("POST /page1 HTTP/1.1", page1.getRequestLine());
1428d742d7fc7f0593eb8c6e4ac9dd4c0f6a80374e46Jesse Wilson        assertEquals(Arrays.toString(requestBody), Arrays.toString(page1.getBody()));
1429d742d7fc7f0593eb8c6e4ac9dd4c0f6a80374e46Jesse Wilson
1430d742d7fc7f0593eb8c6e4ac9dd4c0f6a80374e46Jesse Wilson        RecordedRequest page2 = server.takeRequest();
1431d742d7fc7f0593eb8c6e4ac9dd4c0f6a80374e46Jesse Wilson        assertEquals("GET /page2 HTTP/1.1", page2.getRequestLine());
1432d742d7fc7f0593eb8c6e4ac9dd4c0f6a80374e46Jesse Wilson    }
1433d742d7fc7f0593eb8c6e4ac9dd4c0f6a80374e46Jesse Wilson
1434d742d7fc7f0593eb8c6e4ac9dd4c0f6a80374e46Jesse Wilson    public void testResponse305UseProxy() throws Exception {
1435d742d7fc7f0593eb8c6e4ac9dd4c0f6a80374e46Jesse Wilson        server.play();
1436d742d7fc7f0593eb8c6e4ac9dd4c0f6a80374e46Jesse Wilson        server.enqueue(new MockResponse()
1437d742d7fc7f0593eb8c6e4ac9dd4c0f6a80374e46Jesse Wilson                .setResponseCode(HttpURLConnection.HTTP_USE_PROXY)
1438d742d7fc7f0593eb8c6e4ac9dd4c0f6a80374e46Jesse Wilson                .addHeader("Location: " + server.getUrl("/"))
1439d742d7fc7f0593eb8c6e4ac9dd4c0f6a80374e46Jesse Wilson                .setBody("This page has moved!"));
1440d742d7fc7f0593eb8c6e4ac9dd4c0f6a80374e46Jesse Wilson        server.enqueue(new MockResponse().setBody("Proxy Response"));
1441d742d7fc7f0593eb8c6e4ac9dd4c0f6a80374e46Jesse Wilson
1442d742d7fc7f0593eb8c6e4ac9dd4c0f6a80374e46Jesse Wilson        HttpURLConnection connection = (HttpURLConnection) server.getUrl("/foo").openConnection();
1443d742d7fc7f0593eb8c6e4ac9dd4c0f6a80374e46Jesse Wilson        // Fails on the RI, which gets "Proxy Response"
1444d742d7fc7f0593eb8c6e4ac9dd4c0f6a80374e46Jesse Wilson        assertEquals("This page has moved!",
1445d742d7fc7f0593eb8c6e4ac9dd4c0f6a80374e46Jesse Wilson                readAscii(connection.getInputStream(), Integer.MAX_VALUE));
1446d742d7fc7f0593eb8c6e4ac9dd4c0f6a80374e46Jesse Wilson
1447d742d7fc7f0593eb8c6e4ac9dd4c0f6a80374e46Jesse Wilson        RecordedRequest page1 = server.takeRequest();
1448d742d7fc7f0593eb8c6e4ac9dd4c0f6a80374e46Jesse Wilson        assertEquals("GET /foo HTTP/1.1", page1.getRequestLine());
1449d742d7fc7f0593eb8c6e4ac9dd4c0f6a80374e46Jesse Wilson        assertEquals(1, server.getRequestCount());
1450d742d7fc7f0593eb8c6e4ac9dd4c0f6a80374e46Jesse Wilson    }
1451d742d7fc7f0593eb8c6e4ac9dd4c0f6a80374e46Jesse Wilson
1452c0372d90016d241ac979faa6fa1731f30b6f2a03Jesse Wilson    public void testHttpsWithCustomTrustManager() throws Exception {
1453c0372d90016d241ac979faa6fa1731f30b6f2a03Jesse Wilson        RecordingHostnameVerifier hostnameVerifier = new RecordingHostnameVerifier();
1454c0372d90016d241ac979faa6fa1731f30b6f2a03Jesse Wilson        RecordingTrustManager trustManager = new RecordingTrustManager();
1455c0372d90016d241ac979faa6fa1731f30b6f2a03Jesse Wilson        SSLContext sc = SSLContext.getInstance("TLS");
1456c0372d90016d241ac979faa6fa1731f30b6f2a03Jesse Wilson        sc.init(null, new TrustManager[] { trustManager }, new java.security.SecureRandom());
1457c0372d90016d241ac979faa6fa1731f30b6f2a03Jesse Wilson
1458c0372d90016d241ac979faa6fa1731f30b6f2a03Jesse Wilson        HostnameVerifier defaultHostnameVerifier = HttpsURLConnection.getDefaultHostnameVerifier();
1459c0372d90016d241ac979faa6fa1731f30b6f2a03Jesse Wilson        HttpsURLConnection.setDefaultHostnameVerifier(hostnameVerifier);
1460c0372d90016d241ac979faa6fa1731f30b6f2a03Jesse Wilson        SSLSocketFactory defaultSSLSocketFactory = HttpsURLConnection.getDefaultSSLSocketFactory();
1461c0372d90016d241ac979faa6fa1731f30b6f2a03Jesse Wilson        HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
1462c0372d90016d241ac979faa6fa1731f30b6f2a03Jesse Wilson        try {
1463c0372d90016d241ac979faa6fa1731f30b6f2a03Jesse Wilson            TestSSLContext testSSLContext = TestSSLContext.create();
1464059dbc04218144f985b20a228bbe98139d400d0cBrian Carlstrom            server.useHttps(testSSLContext.serverContext.getSocketFactory(), false);
1465c0372d90016d241ac979faa6fa1731f30b6f2a03Jesse Wilson            server.enqueue(new MockResponse().setBody("ABC"));
1466c0372d90016d241ac979faa6fa1731f30b6f2a03Jesse Wilson            server.enqueue(new MockResponse().setBody("DEF"));
1467c0372d90016d241ac979faa6fa1731f30b6f2a03Jesse Wilson            server.enqueue(new MockResponse().setBody("GHI"));
1468c0372d90016d241ac979faa6fa1731f30b6f2a03Jesse Wilson            server.play();
1469c0372d90016d241ac979faa6fa1731f30b6f2a03Jesse Wilson
1470c0372d90016d241ac979faa6fa1731f30b6f2a03Jesse Wilson            URL url = server.getUrl("/");
1471c0372d90016d241ac979faa6fa1731f30b6f2a03Jesse Wilson            assertEquals("ABC", readAscii(url.openStream(), Integer.MAX_VALUE));
1472c0372d90016d241ac979faa6fa1731f30b6f2a03Jesse Wilson            assertEquals("DEF", readAscii(url.openStream(), Integer.MAX_VALUE));
1473c0372d90016d241ac979faa6fa1731f30b6f2a03Jesse Wilson            assertEquals("GHI", readAscii(url.openStream(), Integer.MAX_VALUE));
1474c0372d90016d241ac979faa6fa1731f30b6f2a03Jesse Wilson
14750c2fd828abec671333b8b88281825fd27a783723Jesse Wilson            assertEquals(Arrays.asList("verify " + hostName), hostnameVerifier.calls);
14764559b1d37edcb5d7f1da086cf2e3290388d74f46Brian Carlstrom            assertEquals(Arrays.asList("checkServerTrusted ["
14770c2fd828abec671333b8b88281825fd27a783723Jesse Wilson                    + "CN=" + hostName + " 1, "
1478b7f4d6c3968c372767b2510f38a3d506067aced6Jesse Wilson                    + "CN=Test Intermediate Certificate Authority 1, "
1479b7f4d6c3968c372767b2510f38a3d506067aced6Jesse Wilson                    + "CN=Test Root Certificate Authority 1"
1480b7f4d6c3968c372767b2510f38a3d506067aced6Jesse Wilson                    + "] RSA"),
1481c0372d90016d241ac979faa6fa1731f30b6f2a03Jesse Wilson                    trustManager.calls);
1482c0372d90016d241ac979faa6fa1731f30b6f2a03Jesse Wilson        } finally {
1483c0372d90016d241ac979faa6fa1731f30b6f2a03Jesse Wilson            HttpsURLConnection.setDefaultHostnameVerifier(defaultHostnameVerifier);
1484c0372d90016d241ac979faa6fa1731f30b6f2a03Jesse Wilson            HttpsURLConnection.setDefaultSSLSocketFactory(defaultSSLSocketFactory);
1485c0372d90016d241ac979faa6fa1731f30b6f2a03Jesse Wilson        }
1486c0372d90016d241ac979faa6fa1731f30b6f2a03Jesse Wilson    }
1487c0372d90016d241ac979faa6fa1731f30b6f2a03Jesse Wilson
14882d9fa917aae6a6da38e9d1eda05841ffdf8855bbJesse Wilson    /**
14892d9fa917aae6a6da38e9d1eda05841ffdf8855bbJesse Wilson     * Test that the timeout period is honored. The timeout may be doubled!
14902d9fa917aae6a6da38e9d1eda05841ffdf8855bbJesse Wilson     * HttpURLConnection will wait the full timeout for each of the server's IP
14912d9fa917aae6a6da38e9d1eda05841ffdf8855bbJesse Wilson     * addresses. This is typically one IPv4 address and one IPv6 address.
14922d9fa917aae6a6da38e9d1eda05841ffdf8855bbJesse Wilson     */
1493eafede536f2059bb6c869e7a5f07fd7ad9758e28Jesse Wilson    public void testConnectTimeouts() throws IOException {
14945fc5dde4c719c1dfdac46b67d5d2e4884d07721eElliott Hughes        StuckServer ss = new StuckServer();
14955fc5dde4c719c1dfdac46b67d5d2e4884d07721eElliott Hughes        int serverPort = ss.getLocalPort();
1496f02c695ed03e708623d9365dec26d533356ef2d0Brian Carlstrom        URLConnection urlConnection = new URL("http://localhost:" + serverPort).openConnection();
1497b7f4d6c3968c372767b2510f38a3d506067aced6Jesse Wilson        int timeout = 1000;
1498b7f4d6c3968c372767b2510f38a3d506067aced6Jesse Wilson        urlConnection.setConnectTimeout(timeout);
1499b7f4d6c3968c372767b2510f38a3d506067aced6Jesse Wilson        long start = System.currentTimeMillis();
1500eafede536f2059bb6c869e7a5f07fd7ad9758e28Jesse Wilson        try {
1501eafede536f2059bb6c869e7a5f07fd7ad9758e28Jesse Wilson            urlConnection.getInputStream();
1502eafede536f2059bb6c869e7a5f07fd7ad9758e28Jesse Wilson            fail();
1503eafede536f2059bb6c869e7a5f07fd7ad9758e28Jesse Wilson        } catch (SocketTimeoutException expected) {
15042d9fa917aae6a6da38e9d1eda05841ffdf8855bbJesse Wilson            long elapsed = System.currentTimeMillis() - start;
15052d9fa917aae6a6da38e9d1eda05841ffdf8855bbJesse Wilson            int attempts = InetAddress.getAllByName("localhost").length; // one per IP address
15062d9fa917aae6a6da38e9d1eda05841ffdf8855bbJesse Wilson            assertTrue("timeout=" +timeout + ", elapsed=" + elapsed + ", attempts=" + attempts,
15072d9fa917aae6a6da38e9d1eda05841ffdf8855bbJesse Wilson                    Math.abs((attempts * timeout) - elapsed) < 500);
15085fc5dde4c719c1dfdac46b67d5d2e4884d07721eElliott Hughes        } finally {
15095fc5dde4c719c1dfdac46b67d5d2e4884d07721eElliott Hughes            ss.close();
1510f02c695ed03e708623d9365dec26d533356ef2d0Brian Carlstrom        }
1511eafede536f2059bb6c869e7a5f07fd7ad9758e28Jesse Wilson    }
1512eafede536f2059bb6c869e7a5f07fd7ad9758e28Jesse Wilson
1513eafede536f2059bb6c869e7a5f07fd7ad9758e28Jesse Wilson    public void testReadTimeouts() throws IOException {
1514eafede536f2059bb6c869e7a5f07fd7ad9758e28Jesse Wilson        /*
1515eafede536f2059bb6c869e7a5f07fd7ad9758e28Jesse Wilson         * This relies on the fact that MockWebServer doesn't close the
1516eafede536f2059bb6c869e7a5f07fd7ad9758e28Jesse Wilson         * connection after a response has been sent. This causes the client to
1517eafede536f2059bb6c869e7a5f07fd7ad9758e28Jesse Wilson         * try to read more bytes than are sent, which results in a timeout.
1518eafede536f2059bb6c869e7a5f07fd7ad9758e28Jesse Wilson         */
1519eafede536f2059bb6c869e7a5f07fd7ad9758e28Jesse Wilson        MockResponse timeout = new MockResponse()
1520eafede536f2059bb6c869e7a5f07fd7ad9758e28Jesse Wilson                .setBody("ABC")
1521eafede536f2059bb6c869e7a5f07fd7ad9758e28Jesse Wilson                .clearHeaders()
1522eafede536f2059bb6c869e7a5f07fd7ad9758e28Jesse Wilson                .addHeader("Content-Length: 4");
1523eafede536f2059bb6c869e7a5f07fd7ad9758e28Jesse Wilson        server.enqueue(timeout);
1524b7f4d6c3968c372767b2510f38a3d506067aced6Jesse Wilson        server.enqueue(new MockResponse().setBody("unused")); // to keep the server alive
1525eafede536f2059bb6c869e7a5f07fd7ad9758e28Jesse Wilson        server.play();
1526eafede536f2059bb6c869e7a5f07fd7ad9758e28Jesse Wilson
1527eafede536f2059bb6c869e7a5f07fd7ad9758e28Jesse Wilson        URLConnection urlConnection = server.getUrl("/").openConnection();
1528eafede536f2059bb6c869e7a5f07fd7ad9758e28Jesse Wilson        urlConnection.setReadTimeout(1000);
1529eafede536f2059bb6c869e7a5f07fd7ad9758e28Jesse Wilson        InputStream in = urlConnection.getInputStream();
1530eafede536f2059bb6c869e7a5f07fd7ad9758e28Jesse Wilson        assertEquals('A', in.read());
1531eafede536f2059bb6c869e7a5f07fd7ad9758e28Jesse Wilson        assertEquals('B', in.read());
1532eafede536f2059bb6c869e7a5f07fd7ad9758e28Jesse Wilson        assertEquals('C', in.read());
1533eafede536f2059bb6c869e7a5f07fd7ad9758e28Jesse Wilson        try {
1534eafede536f2059bb6c869e7a5f07fd7ad9758e28Jesse Wilson            in.read(); // if Content-Length was accurate, this would return -1 immediately
1535eafede536f2059bb6c869e7a5f07fd7ad9758e28Jesse Wilson            fail();
1536eafede536f2059bb6c869e7a5f07fd7ad9758e28Jesse Wilson        } catch (SocketTimeoutException expected) {
1537eafede536f2059bb6c869e7a5f07fd7ad9758e28Jesse Wilson        }
1538eafede536f2059bb6c869e7a5f07fd7ad9758e28Jesse Wilson    }
1539eafede536f2059bb6c869e7a5f07fd7ad9758e28Jesse Wilson
1540125f068f0a6cd739beac97821c9421cf8317cc87Jesse Wilson    public void testSetChunkedEncodingAsRequestProperty() throws IOException, InterruptedException {
1541125f068f0a6cd739beac97821c9421cf8317cc87Jesse Wilson        server.enqueue(new MockResponse());
1542125f068f0a6cd739beac97821c9421cf8317cc87Jesse Wilson        server.play();
1543125f068f0a6cd739beac97821c9421cf8317cc87Jesse Wilson
1544125f068f0a6cd739beac97821c9421cf8317cc87Jesse Wilson        HttpURLConnection urlConnection = (HttpURLConnection) server.getUrl("/").openConnection();
1545125f068f0a6cd739beac97821c9421cf8317cc87Jesse Wilson        urlConnection.setRequestProperty("Transfer-encoding", "chunked");
1546125f068f0a6cd739beac97821c9421cf8317cc87Jesse Wilson        urlConnection.setDoOutput(true);
1547125f068f0a6cd739beac97821c9421cf8317cc87Jesse Wilson        urlConnection.getOutputStream().write("ABC".getBytes("UTF-8"));
1548125f068f0a6cd739beac97821c9421cf8317cc87Jesse Wilson        assertEquals(200, urlConnection.getResponseCode());
1549125f068f0a6cd739beac97821c9421cf8317cc87Jesse Wilson
1550125f068f0a6cd739beac97821c9421cf8317cc87Jesse Wilson        RecordedRequest request = server.takeRequest();
1551125f068f0a6cd739beac97821c9421cf8317cc87Jesse Wilson        assertEquals("ABC", new String(request.getBody(), "UTF-8"));
1552125f068f0a6cd739beac97821c9421cf8317cc87Jesse Wilson    }
1553125f068f0a6cd739beac97821c9421cf8317cc87Jesse Wilson
1554f418bf447fd007cd2ec2d45b4b0399a11904e9b4Jesse Wilson    public void testConnectionCloseInRequest() throws IOException, InterruptedException {
1555f418bf447fd007cd2ec2d45b4b0399a11904e9b4Jesse Wilson        server.enqueue(new MockResponse()); // server doesn't honor the connection: close header!
1556f418bf447fd007cd2ec2d45b4b0399a11904e9b4Jesse Wilson        server.enqueue(new MockResponse());
1557f418bf447fd007cd2ec2d45b4b0399a11904e9b4Jesse Wilson        server.play();
1558f418bf447fd007cd2ec2d45b4b0399a11904e9b4Jesse Wilson
1559f418bf447fd007cd2ec2d45b4b0399a11904e9b4Jesse Wilson        HttpURLConnection a = (HttpURLConnection) server.getUrl("/").openConnection();
1560f418bf447fd007cd2ec2d45b4b0399a11904e9b4Jesse Wilson        a.setRequestProperty("Connection", "close");
1561f418bf447fd007cd2ec2d45b4b0399a11904e9b4Jesse Wilson        assertEquals(200, a.getResponseCode());
1562f418bf447fd007cd2ec2d45b4b0399a11904e9b4Jesse Wilson
1563f418bf447fd007cd2ec2d45b4b0399a11904e9b4Jesse Wilson        HttpURLConnection b = (HttpURLConnection) server.getUrl("/").openConnection();
1564f418bf447fd007cd2ec2d45b4b0399a11904e9b4Jesse Wilson        assertEquals(200, b.getResponseCode());
1565f418bf447fd007cd2ec2d45b4b0399a11904e9b4Jesse Wilson
1566f418bf447fd007cd2ec2d45b4b0399a11904e9b4Jesse Wilson        assertEquals(0, server.takeRequest().getSequenceNumber());
1567f418bf447fd007cd2ec2d45b4b0399a11904e9b4Jesse Wilson        assertEquals("When connection: close is used, each request should get its own connection",
1568f418bf447fd007cd2ec2d45b4b0399a11904e9b4Jesse Wilson                0, server.takeRequest().getSequenceNumber());
1569f418bf447fd007cd2ec2d45b4b0399a11904e9b4Jesse Wilson    }
1570f418bf447fd007cd2ec2d45b4b0399a11904e9b4Jesse Wilson
1571f418bf447fd007cd2ec2d45b4b0399a11904e9b4Jesse Wilson    public void testConnectionCloseInResponse() throws IOException, InterruptedException {
1572f418bf447fd007cd2ec2d45b4b0399a11904e9b4Jesse Wilson        server.enqueue(new MockResponse().addHeader("Connection: close"));
1573f418bf447fd007cd2ec2d45b4b0399a11904e9b4Jesse Wilson        server.enqueue(new MockResponse());
1574f418bf447fd007cd2ec2d45b4b0399a11904e9b4Jesse Wilson        server.play();
1575f418bf447fd007cd2ec2d45b4b0399a11904e9b4Jesse Wilson
1576f418bf447fd007cd2ec2d45b4b0399a11904e9b4Jesse Wilson        HttpURLConnection a = (HttpURLConnection) server.getUrl("/").openConnection();
1577f418bf447fd007cd2ec2d45b4b0399a11904e9b4Jesse Wilson        assertEquals(200, a.getResponseCode());
1578f418bf447fd007cd2ec2d45b4b0399a11904e9b4Jesse Wilson
1579f418bf447fd007cd2ec2d45b4b0399a11904e9b4Jesse Wilson        HttpURLConnection b = (HttpURLConnection) server.getUrl("/").openConnection();
1580f418bf447fd007cd2ec2d45b4b0399a11904e9b4Jesse Wilson        assertEquals(200, b.getResponseCode());
1581f418bf447fd007cd2ec2d45b4b0399a11904e9b4Jesse Wilson
1582f418bf447fd007cd2ec2d45b4b0399a11904e9b4Jesse Wilson        assertEquals(0, server.takeRequest().getSequenceNumber());
1583f418bf447fd007cd2ec2d45b4b0399a11904e9b4Jesse Wilson        assertEquals("When connection: close is used, each request should get its own connection",
1584f418bf447fd007cd2ec2d45b4b0399a11904e9b4Jesse Wilson                0, server.takeRequest().getSequenceNumber());
1585f418bf447fd007cd2ec2d45b4b0399a11904e9b4Jesse Wilson    }
1586f418bf447fd007cd2ec2d45b4b0399a11904e9b4Jesse Wilson
1587f418bf447fd007cd2ec2d45b4b0399a11904e9b4Jesse Wilson    public void testConnectionCloseWithRedirect() throws IOException, InterruptedException {
1588f418bf447fd007cd2ec2d45b4b0399a11904e9b4Jesse Wilson        MockResponse response = new MockResponse()
1589f418bf447fd007cd2ec2d45b4b0399a11904e9b4Jesse Wilson                .setResponseCode(HttpURLConnection.HTTP_MOVED_TEMP)
1590f418bf447fd007cd2ec2d45b4b0399a11904e9b4Jesse Wilson                .addHeader("Location: /foo")
1591f418bf447fd007cd2ec2d45b4b0399a11904e9b4Jesse Wilson                .addHeader("Connection: close");
1592f418bf447fd007cd2ec2d45b4b0399a11904e9b4Jesse Wilson        server.enqueue(response);
1593f418bf447fd007cd2ec2d45b4b0399a11904e9b4Jesse Wilson        server.enqueue(new MockResponse().setBody("This is the new location!"));
1594f418bf447fd007cd2ec2d45b4b0399a11904e9b4Jesse Wilson        server.play();
1595f418bf447fd007cd2ec2d45b4b0399a11904e9b4Jesse Wilson
1596f418bf447fd007cd2ec2d45b4b0399a11904e9b4Jesse Wilson        URLConnection connection = server.getUrl("/").openConnection();
1597f418bf447fd007cd2ec2d45b4b0399a11904e9b4Jesse Wilson        assertEquals("This is the new location!",
1598f418bf447fd007cd2ec2d45b4b0399a11904e9b4Jesse Wilson                readAscii(connection.getInputStream(), Integer.MAX_VALUE));
1599f418bf447fd007cd2ec2d45b4b0399a11904e9b4Jesse Wilson
1600f418bf447fd007cd2ec2d45b4b0399a11904e9b4Jesse Wilson        assertEquals(0, server.takeRequest().getSequenceNumber());
1601f418bf447fd007cd2ec2d45b4b0399a11904e9b4Jesse Wilson        assertEquals("When connection: close is used, each request should get its own connection",
1602f418bf447fd007cd2ec2d45b4b0399a11904e9b4Jesse Wilson                0, server.takeRequest().getSequenceNumber());
1603f418bf447fd007cd2ec2d45b4b0399a11904e9b4Jesse Wilson    }
1604f418bf447fd007cd2ec2d45b4b0399a11904e9b4Jesse Wilson
160565d890eb22aeba9b009ee642ffd4fff48a6f98aeJesse Wilson    public void testResponseCodeDisagreesWithHeaders() throws IOException, InterruptedException {
160665d890eb22aeba9b009ee642ffd4fff48a6f98aeJesse Wilson        server.enqueue(new MockResponse()
160765d890eb22aeba9b009ee642ffd4fff48a6f98aeJesse Wilson                .setResponseCode(HttpURLConnection.HTTP_NO_CONTENT)
160865d890eb22aeba9b009ee642ffd4fff48a6f98aeJesse Wilson                .setBody("This body is not allowed!"));
160965d890eb22aeba9b009ee642ffd4fff48a6f98aeJesse Wilson        server.play();
161065d890eb22aeba9b009ee642ffd4fff48a6f98aeJesse Wilson
161165d890eb22aeba9b009ee642ffd4fff48a6f98aeJesse Wilson        URLConnection connection = server.getUrl("/").openConnection();
161265d890eb22aeba9b009ee642ffd4fff48a6f98aeJesse Wilson        assertEquals("This body is not allowed!",
161365d890eb22aeba9b009ee642ffd4fff48a6f98aeJesse Wilson                readAscii(connection.getInputStream(), Integer.MAX_VALUE));
161465d890eb22aeba9b009ee642ffd4fff48a6f98aeJesse Wilson    }
161565d890eb22aeba9b009ee642ffd4fff48a6f98aeJesse Wilson
1616ef66494dce45a0b7ec22ec3fb20c60096517a4e3Jesse Wilson    public void testSingleByteReadIsSigned() throws IOException {
1617ef66494dce45a0b7ec22ec3fb20c60096517a4e3Jesse Wilson        server.enqueue(new MockResponse().setBody(new byte[] { -2, -1 }));
1618ef66494dce45a0b7ec22ec3fb20c60096517a4e3Jesse Wilson        server.play();
1619ef66494dce45a0b7ec22ec3fb20c60096517a4e3Jesse Wilson
1620ef66494dce45a0b7ec22ec3fb20c60096517a4e3Jesse Wilson        URLConnection connection = server.getUrl("/").openConnection();
1621ef66494dce45a0b7ec22ec3fb20c60096517a4e3Jesse Wilson        InputStream in = connection.getInputStream();
1622ef66494dce45a0b7ec22ec3fb20c60096517a4e3Jesse Wilson        assertEquals(254, in.read());
1623ef66494dce45a0b7ec22ec3fb20c60096517a4e3Jesse Wilson        assertEquals(255, in.read());
1624ef66494dce45a0b7ec22ec3fb20c60096517a4e3Jesse Wilson        assertEquals(-1, in.read());
1625ef66494dce45a0b7ec22ec3fb20c60096517a4e3Jesse Wilson    }
1626ef66494dce45a0b7ec22ec3fb20c60096517a4e3Jesse Wilson
1627f29ad8a60254345d1943d1b3836482395a7c916fJesse Wilson    public void testFlushAfterStreamTransmittedWithChunkedEncoding() throws IOException {
1628f29ad8a60254345d1943d1b3836482395a7c916fJesse Wilson        testFlushAfterStreamTransmitted(TransferKind.CHUNKED);
1629f29ad8a60254345d1943d1b3836482395a7c916fJesse Wilson    }
1630f29ad8a60254345d1943d1b3836482395a7c916fJesse Wilson
1631f29ad8a60254345d1943d1b3836482395a7c916fJesse Wilson    public void testFlushAfterStreamTransmittedWithFixedLength() throws IOException {
1632f29ad8a60254345d1943d1b3836482395a7c916fJesse Wilson        testFlushAfterStreamTransmitted(TransferKind.FIXED_LENGTH);
1633f29ad8a60254345d1943d1b3836482395a7c916fJesse Wilson    }
1634f29ad8a60254345d1943d1b3836482395a7c916fJesse Wilson
1635f29ad8a60254345d1943d1b3836482395a7c916fJesse Wilson    public void testFlushAfterStreamTransmittedWithNoLengthHeaders() throws IOException {
1636f29ad8a60254345d1943d1b3836482395a7c916fJesse Wilson        testFlushAfterStreamTransmitted(TransferKind.END_OF_STREAM);
1637f29ad8a60254345d1943d1b3836482395a7c916fJesse Wilson    }
1638f29ad8a60254345d1943d1b3836482395a7c916fJesse Wilson
1639f29ad8a60254345d1943d1b3836482395a7c916fJesse Wilson    /**
1640f29ad8a60254345d1943d1b3836482395a7c916fJesse Wilson     * We explicitly permit apps to close the upload stream even after it has
1641f29ad8a60254345d1943d1b3836482395a7c916fJesse Wilson     * been transmitted.  We also permit flush so that buffered streams can
1642f29ad8a60254345d1943d1b3836482395a7c916fJesse Wilson     * do a no-op flush when they are closed. http://b/3038470
1643f29ad8a60254345d1943d1b3836482395a7c916fJesse Wilson     */
1644f29ad8a60254345d1943d1b3836482395a7c916fJesse Wilson    private void testFlushAfterStreamTransmitted(TransferKind transferKind) throws IOException {
1645f29ad8a60254345d1943d1b3836482395a7c916fJesse Wilson        server.enqueue(new MockResponse().setBody("abc"));
1646f29ad8a60254345d1943d1b3836482395a7c916fJesse Wilson        server.play();
1647f29ad8a60254345d1943d1b3836482395a7c916fJesse Wilson
1648f29ad8a60254345d1943d1b3836482395a7c916fJesse Wilson        HttpURLConnection connection = (HttpURLConnection) server.getUrl("/").openConnection();
1649f29ad8a60254345d1943d1b3836482395a7c916fJesse Wilson        connection.setDoOutput(true);
1650f29ad8a60254345d1943d1b3836482395a7c916fJesse Wilson        byte[] upload = "def".getBytes("UTF-8");
1651f29ad8a60254345d1943d1b3836482395a7c916fJesse Wilson
1652f29ad8a60254345d1943d1b3836482395a7c916fJesse Wilson        if (transferKind == TransferKind.CHUNKED) {
1653f29ad8a60254345d1943d1b3836482395a7c916fJesse Wilson            connection.setChunkedStreamingMode(0);
1654f29ad8a60254345d1943d1b3836482395a7c916fJesse Wilson        } else if (transferKind == TransferKind.FIXED_LENGTH) {
1655f29ad8a60254345d1943d1b3836482395a7c916fJesse Wilson            connection.setFixedLengthStreamingMode(upload.length);
1656f29ad8a60254345d1943d1b3836482395a7c916fJesse Wilson        }
1657f29ad8a60254345d1943d1b3836482395a7c916fJesse Wilson
1658f29ad8a60254345d1943d1b3836482395a7c916fJesse Wilson        OutputStream out = connection.getOutputStream();
1659f29ad8a60254345d1943d1b3836482395a7c916fJesse Wilson        out.write(upload);
1660f29ad8a60254345d1943d1b3836482395a7c916fJesse Wilson        assertEquals("abc", readAscii(connection.getInputStream(), Integer.MAX_VALUE));
1661f29ad8a60254345d1943d1b3836482395a7c916fJesse Wilson
1662f29ad8a60254345d1943d1b3836482395a7c916fJesse Wilson        out.flush(); // dubious but permitted
1663f29ad8a60254345d1943d1b3836482395a7c916fJesse Wilson        try {
1664f29ad8a60254345d1943d1b3836482395a7c916fJesse Wilson            out.write("ghi".getBytes("UTF-8"));
1665f29ad8a60254345d1943d1b3836482395a7c916fJesse Wilson            fail();
1666f29ad8a60254345d1943d1b3836482395a7c916fJesse Wilson        } catch (IOException expected) {
1667f29ad8a60254345d1943d1b3836482395a7c916fJesse Wilson        }
1668f29ad8a60254345d1943d1b3836482395a7c916fJesse Wilson    }
1669f29ad8a60254345d1943d1b3836482395a7c916fJesse Wilson
1670c6dae581716b9362a5c7f166c80a7f2b46ed1124Jesse Wilson    public void testGetHeadersThrows() throws IOException {
1671e942f46f10bb9384a1b186b3d7b74f9704c57090Jesse Wilson        server.enqueue(new MockResponse().setSocketPolicy(DISCONNECT_AT_START));
1672c6dae581716b9362a5c7f166c80a7f2b46ed1124Jesse Wilson        server.play();
1673c6dae581716b9362a5c7f166c80a7f2b46ed1124Jesse Wilson
1674c6dae581716b9362a5c7f166c80a7f2b46ed1124Jesse Wilson        HttpURLConnection connection = (HttpURLConnection) server.getUrl("/").openConnection();
1675c6dae581716b9362a5c7f166c80a7f2b46ed1124Jesse Wilson        try {
1676c6dae581716b9362a5c7f166c80a7f2b46ed1124Jesse Wilson            connection.getInputStream();
1677c6dae581716b9362a5c7f166c80a7f2b46ed1124Jesse Wilson            fail();
1678c6dae581716b9362a5c7f166c80a7f2b46ed1124Jesse Wilson        } catch (IOException expected) {
1679c6dae581716b9362a5c7f166c80a7f2b46ed1124Jesse Wilson        }
1680c6dae581716b9362a5c7f166c80a7f2b46ed1124Jesse Wilson
1681c6dae581716b9362a5c7f166c80a7f2b46ed1124Jesse Wilson        try {
1682c6dae581716b9362a5c7f166c80a7f2b46ed1124Jesse Wilson            connection.getInputStream();
1683c6dae581716b9362a5c7f166c80a7f2b46ed1124Jesse Wilson            fail();
1684f29ad8a60254345d1943d1b3836482395a7c916fJesse Wilson        } catch (IOException expected) {
1685f29ad8a60254345d1943d1b3836482395a7c916fJesse Wilson        }
1686f29ad8a60254345d1943d1b3836482395a7c916fJesse Wilson    }
1687f29ad8a60254345d1943d1b3836482395a7c916fJesse Wilson
1688b7f4d6c3968c372767b2510f38a3d506067aced6Jesse Wilson    public void testGetKeepAlive() throws Exception {
1689b7f4d6c3968c372767b2510f38a3d506067aced6Jesse Wilson        MockWebServer server = new MockWebServer();
1690b7f4d6c3968c372767b2510f38a3d506067aced6Jesse Wilson        server.enqueue(new MockResponse().setBody("ABC"));
1691b7f4d6c3968c372767b2510f38a3d506067aced6Jesse Wilson        server.play();
1692b7f4d6c3968c372767b2510f38a3d506067aced6Jesse Wilson
1693b7f4d6c3968c372767b2510f38a3d506067aced6Jesse Wilson        // The request should work once and then fail
1694b7f4d6c3968c372767b2510f38a3d506067aced6Jesse Wilson        URLConnection connection = server.getUrl("").openConnection();
1695b7f4d6c3968c372767b2510f38a3d506067aced6Jesse Wilson        InputStream input = connection.getInputStream();
1696b7f4d6c3968c372767b2510f38a3d506067aced6Jesse Wilson        assertEquals("ABC", readAscii(input, Integer.MAX_VALUE));
1697b7f4d6c3968c372767b2510f38a3d506067aced6Jesse Wilson        input.close();
1698b7f4d6c3968c372767b2510f38a3d506067aced6Jesse Wilson        try {
1699b7f4d6c3968c372767b2510f38a3d506067aced6Jesse Wilson            server.getUrl("").openConnection().getInputStream();
1700b7f4d6c3968c372767b2510f38a3d506067aced6Jesse Wilson            fail();
1701b7f4d6c3968c372767b2510f38a3d506067aced6Jesse Wilson        } catch (ConnectException expected) {
1702b7f4d6c3968c372767b2510f38a3d506067aced6Jesse Wilson        }
1703b7f4d6c3968c372767b2510f38a3d506067aced6Jesse Wilson    }
1704b7f4d6c3968c372767b2510f38a3d506067aced6Jesse Wilson
1705b7f4d6c3968c372767b2510f38a3d506067aced6Jesse Wilson    /**
1706d1b5e5da828434388e486a388710d21e4306dae0Jesse Wilson     * This test goes through the exhaustive set of interesting ASCII characters
1707d1b5e5da828434388e486a388710d21e4306dae0Jesse Wilson     * because most of those characters are interesting in some way according to
1708d1b5e5da828434388e486a388710d21e4306dae0Jesse Wilson     * RFC 2396 and RFC 2732. http://b/1158780
1709b7f4d6c3968c372767b2510f38a3d506067aced6Jesse Wilson     */
1710d1b5e5da828434388e486a388710d21e4306dae0Jesse Wilson    public void testLenientUrlToUri() throws Exception {
1711d1b5e5da828434388e486a388710d21e4306dae0Jesse Wilson        // alphanum
1712d1b5e5da828434388e486a388710d21e4306dae0Jesse Wilson        testUrlToUriMapping("abzABZ09", "abzABZ09", "abzABZ09", "abzABZ09", "abzABZ09");
1713d1b5e5da828434388e486a388710d21e4306dae0Jesse Wilson
1714d1b5e5da828434388e486a388710d21e4306dae0Jesse Wilson        // control characters
1715d1b5e5da828434388e486a388710d21e4306dae0Jesse Wilson        testUrlToUriMapping("\u0001", "%01", "%01", "%01", "%01");
1716d1b5e5da828434388e486a388710d21e4306dae0Jesse Wilson        testUrlToUriMapping("\u001f", "%1F", "%1F", "%1F", "%1F");
1717d1b5e5da828434388e486a388710d21e4306dae0Jesse Wilson
1718d1b5e5da828434388e486a388710d21e4306dae0Jesse Wilson        // ascii characters
1719d1b5e5da828434388e486a388710d21e4306dae0Jesse Wilson        testUrlToUriMapping("%20", "%20", "%20", "%20", "%20");
1720d1b5e5da828434388e486a388710d21e4306dae0Jesse Wilson        testUrlToUriMapping("%20", "%20", "%20", "%20", "%20");
1721d1b5e5da828434388e486a388710d21e4306dae0Jesse Wilson        testUrlToUriMapping(" ", "%20", "%20", "%20", "%20");
1722d1b5e5da828434388e486a388710d21e4306dae0Jesse Wilson        testUrlToUriMapping("!", "!", "!", "!", "!");
1723d1b5e5da828434388e486a388710d21e4306dae0Jesse Wilson        testUrlToUriMapping("\"", "%22", "%22", "%22", "%22");
1724d1b5e5da828434388e486a388710d21e4306dae0Jesse Wilson        testUrlToUriMapping("#", null, null, null, "%23");
1725d1b5e5da828434388e486a388710d21e4306dae0Jesse Wilson        testUrlToUriMapping("$", "$", "$", "$", "$");
1726d1b5e5da828434388e486a388710d21e4306dae0Jesse Wilson        testUrlToUriMapping("&", "&", "&", "&", "&");
1727d1b5e5da828434388e486a388710d21e4306dae0Jesse Wilson        testUrlToUriMapping("'", "'", "'", "'", "'");
1728d1b5e5da828434388e486a388710d21e4306dae0Jesse Wilson        testUrlToUriMapping("(", "(", "(", "(", "(");
1729d1b5e5da828434388e486a388710d21e4306dae0Jesse Wilson        testUrlToUriMapping(")", ")", ")", ")", ")");
1730d1b5e5da828434388e486a388710d21e4306dae0Jesse Wilson        testUrlToUriMapping("*", "*", "*", "*", "*");
1731d1b5e5da828434388e486a388710d21e4306dae0Jesse Wilson        testUrlToUriMapping("+", "+", "+", "+", "+");
1732d1b5e5da828434388e486a388710d21e4306dae0Jesse Wilson        testUrlToUriMapping(",", ",", ",", ",", ",");
1733d1b5e5da828434388e486a388710d21e4306dae0Jesse Wilson        testUrlToUriMapping("-", "-", "-", "-", "-");
1734d1b5e5da828434388e486a388710d21e4306dae0Jesse Wilson        testUrlToUriMapping(".", ".", ".", ".", ".");
1735d1b5e5da828434388e486a388710d21e4306dae0Jesse Wilson        testUrlToUriMapping("/", null, "/", "/", "/");
1736d1b5e5da828434388e486a388710d21e4306dae0Jesse Wilson        testUrlToUriMapping(":", null, ":", ":", ":");
1737d1b5e5da828434388e486a388710d21e4306dae0Jesse Wilson        testUrlToUriMapping(";", ";", ";", ";", ";");
1738d1b5e5da828434388e486a388710d21e4306dae0Jesse Wilson        testUrlToUriMapping("<", "%3C", "%3C", "%3C", "%3C");
1739d1b5e5da828434388e486a388710d21e4306dae0Jesse Wilson        testUrlToUriMapping("=", "=", "=", "=", "=");
1740d1b5e5da828434388e486a388710d21e4306dae0Jesse Wilson        testUrlToUriMapping(">", "%3E", "%3E", "%3E", "%3E");
1741d1b5e5da828434388e486a388710d21e4306dae0Jesse Wilson        testUrlToUriMapping("?", null, null, "?", "?");
1742d1b5e5da828434388e486a388710d21e4306dae0Jesse Wilson        testUrlToUriMapping("@", "@", "@", "@", "@");
1743d1b5e5da828434388e486a388710d21e4306dae0Jesse Wilson        testUrlToUriMapping("[", null, "%5B", null, "%5B");
1744d1b5e5da828434388e486a388710d21e4306dae0Jesse Wilson        testUrlToUriMapping("\\", "%5C", "%5C", "%5C", "%5C");
1745d1b5e5da828434388e486a388710d21e4306dae0Jesse Wilson        testUrlToUriMapping("]", null, "%5D", null, "%5D");
1746d1b5e5da828434388e486a388710d21e4306dae0Jesse Wilson        testUrlToUriMapping("^", "%5E", "%5E", "%5E", "%5E");
1747d1b5e5da828434388e486a388710d21e4306dae0Jesse Wilson        testUrlToUriMapping("_", "_", "_", "_", "_");
1748d1b5e5da828434388e486a388710d21e4306dae0Jesse Wilson        testUrlToUriMapping("`", "%60", "%60", "%60", "%60");
1749d1b5e5da828434388e486a388710d21e4306dae0Jesse Wilson        testUrlToUriMapping("{", "%7B", "%7B", "%7B", "%7B");
1750d1b5e5da828434388e486a388710d21e4306dae0Jesse Wilson        testUrlToUriMapping("|", "%7C", "%7C", "%7C", "%7C");
1751d1b5e5da828434388e486a388710d21e4306dae0Jesse Wilson        testUrlToUriMapping("}", "%7D", "%7D", "%7D", "%7D");
1752d1b5e5da828434388e486a388710d21e4306dae0Jesse Wilson        testUrlToUriMapping("~", "~", "~", "~", "~");
1753d1b5e5da828434388e486a388710d21e4306dae0Jesse Wilson        testUrlToUriMapping("~", "~", "~", "~", "~");
1754d1b5e5da828434388e486a388710d21e4306dae0Jesse Wilson        testUrlToUriMapping("\u007f", "%7F", "%7F", "%7F", "%7F");
1755d1b5e5da828434388e486a388710d21e4306dae0Jesse Wilson
1756d1b5e5da828434388e486a388710d21e4306dae0Jesse Wilson        // beyond ascii
1757d1b5e5da828434388e486a388710d21e4306dae0Jesse Wilson        testUrlToUriMapping("\u0080", "%C2%80", "%C2%80", "%C2%80", "%C2%80");
1758d1b5e5da828434388e486a388710d21e4306dae0Jesse Wilson        testUrlToUriMapping("\u20ac", "\u20ac", "\u20ac", "\u20ac", "\u20ac");
175932559028b14b9b321b10eede050afd554a376569Jesse Wilson        testUrlToUriMapping("\ud842\udf9f",
176032559028b14b9b321b10eede050afd554a376569Jesse Wilson                "\ud842\udf9f", "\ud842\udf9f", "\ud842\udf9f", "\ud842\udf9f");
1761d1b5e5da828434388e486a388710d21e4306dae0Jesse Wilson    }
1762d1b5e5da828434388e486a388710d21e4306dae0Jesse Wilson
1763d1b5e5da828434388e486a388710d21e4306dae0Jesse Wilson    public void testLenientUrlToUriNul() throws Exception {
1764d1b5e5da828434388e486a388710d21e4306dae0Jesse Wilson        testUrlToUriMapping("\u0000", "%00", "%00", "%00", "%00"); // RI fails this
1765d1b5e5da828434388e486a388710d21e4306dae0Jesse Wilson    }
1766d1b5e5da828434388e486a388710d21e4306dae0Jesse Wilson
1767d1b5e5da828434388e486a388710d21e4306dae0Jesse Wilson    private void testUrlToUriMapping(String string, String asAuthority, String asFile,
1768d1b5e5da828434388e486a388710d21e4306dae0Jesse Wilson            String asQuery, String asFragment) throws Exception {
1769d1b5e5da828434388e486a388710d21e4306dae0Jesse Wilson        if (asAuthority != null) {
1770d1b5e5da828434388e486a388710d21e4306dae0Jesse Wilson            assertEquals("http://host" + asAuthority + ".tld/",
1771d1b5e5da828434388e486a388710d21e4306dae0Jesse Wilson                    backdoorUrlToUri(new URL("http://host" + string + ".tld/")).toString());
1772d1b5e5da828434388e486a388710d21e4306dae0Jesse Wilson        }
1773d1b5e5da828434388e486a388710d21e4306dae0Jesse Wilson        if (asFile != null) {
1774d1b5e5da828434388e486a388710d21e4306dae0Jesse Wilson            assertEquals("http://host.tld/file" + asFile + "/",
1775d1b5e5da828434388e486a388710d21e4306dae0Jesse Wilson                    backdoorUrlToUri(new URL("http://host.tld/file" + string + "/")).toString());
1776d1b5e5da828434388e486a388710d21e4306dae0Jesse Wilson        }
1777d1b5e5da828434388e486a388710d21e4306dae0Jesse Wilson        if (asQuery != null) {
1778d1b5e5da828434388e486a388710d21e4306dae0Jesse Wilson            assertEquals("http://host.tld/file?q" + asQuery + "=x",
1779d1b5e5da828434388e486a388710d21e4306dae0Jesse Wilson                    backdoorUrlToUri(new URL("http://host.tld/file?q" + string + "=x")).toString());
1780d1b5e5da828434388e486a388710d21e4306dae0Jesse Wilson        }
1781d1b5e5da828434388e486a388710d21e4306dae0Jesse Wilson        assertEquals("http://host.tld/file#" + asFragment + "-x",
1782d1b5e5da828434388e486a388710d21e4306dae0Jesse Wilson                backdoorUrlToUri(new URL("http://host.tld/file#" + asFragment + "-x")).toString());
1783d1b5e5da828434388e486a388710d21e4306dae0Jesse Wilson    }
1784b7f4d6c3968c372767b2510f38a3d506067aced6Jesse Wilson
1785d1b5e5da828434388e486a388710d21e4306dae0Jesse Wilson    /**
1786d1b5e5da828434388e486a388710d21e4306dae0Jesse Wilson     * Exercises HttpURLConnection to convert URL to a URI. Unlike URL#toURI,
1787d1b5e5da828434388e486a388710d21e4306dae0Jesse Wilson     * HttpURLConnection recovers from URLs with unescaped but unsupported URI
1788d1b5e5da828434388e486a388710d21e4306dae0Jesse Wilson     * characters like '{' and '|' by escaping these characters.
1789d1b5e5da828434388e486a388710d21e4306dae0Jesse Wilson     */
1790d1b5e5da828434388e486a388710d21e4306dae0Jesse Wilson    private URI backdoorUrlToUri(URL url) throws Exception {
1791d1b5e5da828434388e486a388710d21e4306dae0Jesse Wilson        final AtomicReference<URI> uriReference = new AtomicReference<URI>();
1792d1b5e5da828434388e486a388710d21e4306dae0Jesse Wilson
1793d1b5e5da828434388e486a388710d21e4306dae0Jesse Wilson        ResponseCache.setDefault(new ResponseCache() {
1794d1b5e5da828434388e486a388710d21e4306dae0Jesse Wilson            @Override public CacheRequest put(URI uri, URLConnection connection) throws IOException {
1795d1b5e5da828434388e486a388710d21e4306dae0Jesse Wilson                return null;
1796d1b5e5da828434388e486a388710d21e4306dae0Jesse Wilson            }
1797d1b5e5da828434388e486a388710d21e4306dae0Jesse Wilson            @Override public CacheResponse get(URI uri, String requestMethod,
1798d1b5e5da828434388e486a388710d21e4306dae0Jesse Wilson                    Map<String, List<String>> requestHeaders) throws IOException {
1799d1b5e5da828434388e486a388710d21e4306dae0Jesse Wilson                uriReference.set(uri);
1800d1b5e5da828434388e486a388710d21e4306dae0Jesse Wilson                throw new UnsupportedOperationException();
1801d1b5e5da828434388e486a388710d21e4306dae0Jesse Wilson            }
1802d1b5e5da828434388e486a388710d21e4306dae0Jesse Wilson        });
1803d1b5e5da828434388e486a388710d21e4306dae0Jesse Wilson
1804d1b5e5da828434388e486a388710d21e4306dae0Jesse Wilson        try {
1805d1b5e5da828434388e486a388710d21e4306dae0Jesse Wilson            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
1806d1b5e5da828434388e486a388710d21e4306dae0Jesse Wilson            connection.getResponseCode();
1807d1b5e5da828434388e486a388710d21e4306dae0Jesse Wilson        } catch (Exception expected) {
1808d1b5e5da828434388e486a388710d21e4306dae0Jesse Wilson        }
1809d1b5e5da828434388e486a388710d21e4306dae0Jesse Wilson
1810d1b5e5da828434388e486a388710d21e4306dae0Jesse Wilson        return uriReference.get();
1811b7f4d6c3968c372767b2510f38a3d506067aced6Jesse Wilson    }
1812b7f4d6c3968c372767b2510f38a3d506067aced6Jesse Wilson
1813afd9b157f467b7c4f2f0b5592dca72f18d844602Jesse Wilson    /**
1814afd9b157f467b7c4f2f0b5592dca72f18d844602Jesse Wilson     * Don't explode if the cache returns a null body. http://b/3373699
1815afd9b157f467b7c4f2f0b5592dca72f18d844602Jesse Wilson     */
1816afd9b157f467b7c4f2f0b5592dca72f18d844602Jesse Wilson    public void testResponseCacheReturnsNullOutputStream() throws Exception {
1817afd9b157f467b7c4f2f0b5592dca72f18d844602Jesse Wilson        final AtomicBoolean aborted = new AtomicBoolean();
1818afd9b157f467b7c4f2f0b5592dca72f18d844602Jesse Wilson        ResponseCache.setDefault(new ResponseCache() {
1819afd9b157f467b7c4f2f0b5592dca72f18d844602Jesse Wilson            @Override public CacheResponse get(URI uri, String requestMethod,
1820afd9b157f467b7c4f2f0b5592dca72f18d844602Jesse Wilson                    Map<String, List<String>> requestHeaders) throws IOException {
1821afd9b157f467b7c4f2f0b5592dca72f18d844602Jesse Wilson                return null;
1822afd9b157f467b7c4f2f0b5592dca72f18d844602Jesse Wilson            }
1823afd9b157f467b7c4f2f0b5592dca72f18d844602Jesse Wilson            @Override public CacheRequest put(URI uri, URLConnection connection) throws IOException {
1824afd9b157f467b7c4f2f0b5592dca72f18d844602Jesse Wilson                return new CacheRequest() {
1825afd9b157f467b7c4f2f0b5592dca72f18d844602Jesse Wilson                    @Override public void abort() {
1826afd9b157f467b7c4f2f0b5592dca72f18d844602Jesse Wilson                        aborted.set(true);
1827afd9b157f467b7c4f2f0b5592dca72f18d844602Jesse Wilson                    }
1828afd9b157f467b7c4f2f0b5592dca72f18d844602Jesse Wilson                    @Override public OutputStream getBody() throws IOException {
1829afd9b157f467b7c4f2f0b5592dca72f18d844602Jesse Wilson                        return null;
1830afd9b157f467b7c4f2f0b5592dca72f18d844602Jesse Wilson                    }
1831afd9b157f467b7c4f2f0b5592dca72f18d844602Jesse Wilson                };
1832afd9b157f467b7c4f2f0b5592dca72f18d844602Jesse Wilson            }
1833afd9b157f467b7c4f2f0b5592dca72f18d844602Jesse Wilson        });
1834afd9b157f467b7c4f2f0b5592dca72f18d844602Jesse Wilson
1835afd9b157f467b7c4f2f0b5592dca72f18d844602Jesse Wilson        server.enqueue(new MockResponse().setBody("abcdef"));
1836afd9b157f467b7c4f2f0b5592dca72f18d844602Jesse Wilson        server.play();
1837afd9b157f467b7c4f2f0b5592dca72f18d844602Jesse Wilson
1838afd9b157f467b7c4f2f0b5592dca72f18d844602Jesse Wilson        HttpURLConnection connection = (HttpURLConnection) server.getUrl("/").openConnection();
1839afd9b157f467b7c4f2f0b5592dca72f18d844602Jesse Wilson        InputStream in = connection.getInputStream();
1840afd9b157f467b7c4f2f0b5592dca72f18d844602Jesse Wilson        assertEquals("abc", readAscii(in, 3));
1841afd9b157f467b7c4f2f0b5592dca72f18d844602Jesse Wilson        in.close();
1842afd9b157f467b7c4f2f0b5592dca72f18d844602Jesse Wilson        assertFalse(aborted.get()); // The best behavior is ambiguous, but RI 6 doesn't abort here
1843afd9b157f467b7c4f2f0b5592dca72f18d844602Jesse Wilson    }
1844d1b5e5da828434388e486a388710d21e4306dae0Jesse Wilson
18455e8b5a55eda914b67c62b4e77152922d5c77eb68Jesse Wilson
18465e8b5a55eda914b67c62b4e77152922d5c77eb68Jesse Wilson    /**
18475e8b5a55eda914b67c62b4e77152922d5c77eb68Jesse Wilson     * http://code.google.com/p/android/issues/detail?id=14562
18485e8b5a55eda914b67c62b4e77152922d5c77eb68Jesse Wilson     */
18495e8b5a55eda914b67c62b4e77152922d5c77eb68Jesse Wilson    public void testReadAfterLastByte() throws Exception {
18505e8b5a55eda914b67c62b4e77152922d5c77eb68Jesse Wilson        server.enqueue(new MockResponse()
18515e8b5a55eda914b67c62b4e77152922d5c77eb68Jesse Wilson                .setBody("ABC")
18525e8b5a55eda914b67c62b4e77152922d5c77eb68Jesse Wilson                .clearHeaders()
18535e8b5a55eda914b67c62b4e77152922d5c77eb68Jesse Wilson                .addHeader("Connection: close")
18545e8b5a55eda914b67c62b4e77152922d5c77eb68Jesse Wilson                .setSocketPolicy(SocketPolicy.DISCONNECT_AT_END));
18555e8b5a55eda914b67c62b4e77152922d5c77eb68Jesse Wilson        server.play();
18565e8b5a55eda914b67c62b4e77152922d5c77eb68Jesse Wilson
18575e8b5a55eda914b67c62b4e77152922d5c77eb68Jesse Wilson        HttpURLConnection connection = (HttpURLConnection) server.getUrl("/").openConnection();
18585e8b5a55eda914b67c62b4e77152922d5c77eb68Jesse Wilson        InputStream in = connection.getInputStream();
18595e8b5a55eda914b67c62b4e77152922d5c77eb68Jesse Wilson        assertEquals("ABC", readAscii(in, 3));
18605e8b5a55eda914b67c62b4e77152922d5c77eb68Jesse Wilson        assertEquals(-1, in.read());
1861bc4c79c6a2059003f695f7ad204de36700e8d701Jesse Wilson        assertEquals(-1, in.read()); // throws IOException in Gingerbread
1862bc4c79c6a2059003f695f7ad204de36700e8d701Jesse Wilson    }
1863bc4c79c6a2059003f695f7ad204de36700e8d701Jesse Wilson
1864ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson    public void testGetContent() throws Exception {
1865ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson        server.enqueue(new MockResponse().setBody("A"));
1866ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson        server.play();
1867ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson        HttpURLConnection connection = (HttpURLConnection) server.getUrl("/").openConnection();
1868ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson        InputStream in = (InputStream) connection.getContent();
1869ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson        assertEquals("A", readAscii(in, Integer.MAX_VALUE));
1870ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson    }
1871ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson
1872ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson    public void testGetContentOfType() throws Exception {
1873ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson        server.enqueue(new MockResponse().setBody("A"));
1874ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson        server.play();
1875ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson        HttpURLConnection connection = (HttpURLConnection) server.getUrl("/").openConnection();
1876ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson        try {
1877ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson            connection.getContent(null);
1878ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson            fail();
1879ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson        } catch (NullPointerException expected) {
1880ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson        }
1881ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson        try {
1882ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson            connection.getContent(new Class[] { null });
1883ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson            fail();
1884ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson        } catch (NullPointerException expected) {
1885ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson        }
1886ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson        assertNull(connection.getContent(new Class[] { getClass() }));
1887ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson        connection.disconnect();
1888ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson    }
1889ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson
1890ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson    public void testGetOutputStreamOnGetFails() throws Exception {
1891ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson        server.enqueue(new MockResponse());
1892ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson        server.play();
1893ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson        HttpURLConnection connection = (HttpURLConnection) server.getUrl("/").openConnection();
1894ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson        try {
1895ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson            connection.getOutputStream();
1896ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson            fail();
1897ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson        } catch (ProtocolException expected) {
1898ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson        }
1899ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson    }
1900ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson
1901ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson    public void testGetOutputAfterGetInputStreamFails() throws Exception {
1902ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson        server.enqueue(new MockResponse());
1903ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson        server.play();
1904ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson        HttpURLConnection connection = (HttpURLConnection) server.getUrl("/").openConnection();
1905ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson        connection.setDoOutput(true);
1906ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson        try {
1907ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson            connection.getInputStream();
1908ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson            connection.getOutputStream();
1909ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson            fail();
1910ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson        } catch (ProtocolException expected) {
1911ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson        }
1912ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson    }
1913ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson
1914ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson    public void testSetDoOutputOrDoInputAfterConnectFails() throws Exception {
1915ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson        server.enqueue(new MockResponse());
1916ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson        server.play();
1917ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson        HttpURLConnection connection = (HttpURLConnection) server.getUrl("/").openConnection();
1918ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson        connection.connect();
1919ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson        try {
1920ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson            connection.setDoOutput(true);
1921ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson            fail();
1922ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson        } catch (IllegalStateException expected) {
1923ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson        }
1924ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson        try {
1925ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson            connection.setDoInput(true);
1926ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson            fail();
1927ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson        } catch (IllegalStateException expected) {
1928ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson        }
1929ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson        connection.disconnect();
1930ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson    }
1931ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson
1932ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson    public void testClientSendsContentLength() throws Exception {
1933ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson        server.enqueue(new MockResponse().setBody("A"));
1934ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson        server.play();
1935ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson        HttpURLConnection connection = (HttpURLConnection) server.getUrl("/").openConnection();
1936ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson        connection.setDoOutput(true);
1937ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson        OutputStream out = connection.getOutputStream();
1938ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson        out.write(new byte[] { 'A', 'B', 'C' });
1939ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson        out.close();
1940ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson        assertEquals("A", readAscii(connection.getInputStream(), Integer.MAX_VALUE));
1941ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson        RecordedRequest request = server.takeRequest();
1942ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson        assertContains(request.getHeaders(), "Content-Length: 3");
1943ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson    }
1944ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson
1945ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson    public void testGetContentLengthConnects() throws Exception {
1946ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson        server.enqueue(new MockResponse().setBody("ABC"));
1947ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson        server.play();
1948ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson        HttpURLConnection connection = (HttpURLConnection) server.getUrl("/").openConnection();
1949ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson        assertEquals(3, connection.getContentLength());
1950ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson        connection.disconnect();
1951ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson    }
1952ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson
1953ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson    public void testGetContentTypeConnects() throws Exception {
1954ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson        server.enqueue(new MockResponse()
1955ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson                .addHeader("Content-Type: text/plain")
1956ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson                .setBody("ABC"));
1957ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson        server.play();
1958ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson        HttpURLConnection connection = (HttpURLConnection) server.getUrl("/").openConnection();
1959ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson        assertEquals("text/plain", connection.getContentType());
1960ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson        connection.disconnect();
1961ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson    }
1962ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson
1963ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson    public void testGetContentEncodingConnects() throws Exception {
1964ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson        server.enqueue(new MockResponse()
1965ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson                .addHeader("Content-Encoding: identity")
1966ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson                .setBody("ABC"));
1967ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson        server.play();
1968ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson        HttpURLConnection connection = (HttpURLConnection) server.getUrl("/").openConnection();
1969ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson        assertEquals("identity", connection.getContentEncoding());
1970ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson        connection.disconnect();
1971ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson    }
1972ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson
19735292410e4ebf7fb5149eefd2f52fcb94c46690a6Jesse Wilson    // http://b/4361656
19745292410e4ebf7fb5149eefd2f52fcb94c46690a6Jesse Wilson    public void testUrlContainsQueryButNoPath() throws Exception {
19755292410e4ebf7fb5149eefd2f52fcb94c46690a6Jesse Wilson        server.enqueue(new MockResponse().setBody("A"));
19765292410e4ebf7fb5149eefd2f52fcb94c46690a6Jesse Wilson        server.play();
19775292410e4ebf7fb5149eefd2f52fcb94c46690a6Jesse Wilson        URL url = new URL("http", server.getHostName(), server.getPort(), "?query");
19785292410e4ebf7fb5149eefd2f52fcb94c46690a6Jesse Wilson        assertEquals("A", readAscii(url.openConnection().getInputStream(), Integer.MAX_VALUE));
19795292410e4ebf7fb5149eefd2f52fcb94c46690a6Jesse Wilson        RecordedRequest request = server.takeRequest();
19805292410e4ebf7fb5149eefd2f52fcb94c46690a6Jesse Wilson        assertEquals("GET /?query HTTP/1.1", request.getRequestLine());
19815292410e4ebf7fb5149eefd2f52fcb94c46690a6Jesse Wilson    }
19825292410e4ebf7fb5149eefd2f52fcb94c46690a6Jesse Wilson
198325a753691a80186cd4d7086b12c0e52225d95897Jesse Wilson    // http://code.google.com/p/android/issues/detail?id=20442
198425a753691a80186cd4d7086b12c0e52225d95897Jesse Wilson    public void testInputStreamAvailableWithChunkedEncoding() throws Exception {
198525a753691a80186cd4d7086b12c0e52225d95897Jesse Wilson        testInputStreamAvailable(TransferKind.CHUNKED);
198625a753691a80186cd4d7086b12c0e52225d95897Jesse Wilson    }
198725a753691a80186cd4d7086b12c0e52225d95897Jesse Wilson
198825a753691a80186cd4d7086b12c0e52225d95897Jesse Wilson    public void testInputStreamAvailableWithContentLengthHeader() throws Exception {
198925a753691a80186cd4d7086b12c0e52225d95897Jesse Wilson        testInputStreamAvailable(TransferKind.FIXED_LENGTH);
199025a753691a80186cd4d7086b12c0e52225d95897Jesse Wilson    }
199125a753691a80186cd4d7086b12c0e52225d95897Jesse Wilson
199225a753691a80186cd4d7086b12c0e52225d95897Jesse Wilson    public void testInputStreamAvailableWithNoLengthHeaders() throws Exception {
199325a753691a80186cd4d7086b12c0e52225d95897Jesse Wilson        testInputStreamAvailable(TransferKind.END_OF_STREAM);
199425a753691a80186cd4d7086b12c0e52225d95897Jesse Wilson    }
199525a753691a80186cd4d7086b12c0e52225d95897Jesse Wilson
199625a753691a80186cd4d7086b12c0e52225d95897Jesse Wilson    private void testInputStreamAvailable(TransferKind transferKind) throws IOException {
199725a753691a80186cd4d7086b12c0e52225d95897Jesse Wilson        String body = "ABCDEFGH";
199825a753691a80186cd4d7086b12c0e52225d95897Jesse Wilson        MockResponse response = new MockResponse();
199925a753691a80186cd4d7086b12c0e52225d95897Jesse Wilson        transferKind.setBody(response, body, 4);
200025a753691a80186cd4d7086b12c0e52225d95897Jesse Wilson        server.enqueue(response);
200125a753691a80186cd4d7086b12c0e52225d95897Jesse Wilson        server.play();
200225a753691a80186cd4d7086b12c0e52225d95897Jesse Wilson        URLConnection connection = server.getUrl("/").openConnection();
200325a753691a80186cd4d7086b12c0e52225d95897Jesse Wilson        InputStream in = connection.getInputStream();
200425a753691a80186cd4d7086b12c0e52225d95897Jesse Wilson        for (int i = 0; i < body.length(); i++) {
200525a753691a80186cd4d7086b12c0e52225d95897Jesse Wilson            assertTrue(in.available() >= 0);
200625a753691a80186cd4d7086b12c0e52225d95897Jesse Wilson            assertEquals(body.charAt(i), in.read());
200725a753691a80186cd4d7086b12c0e52225d95897Jesse Wilson        }
200825a753691a80186cd4d7086b12c0e52225d95897Jesse Wilson        assertEquals(0, in.available());
200925a753691a80186cd4d7086b12c0e52225d95897Jesse Wilson        assertEquals(-1, in.read());
201025a753691a80186cd4d7086b12c0e52225d95897Jesse Wilson    }
201125a753691a80186cd4d7086b12c0e52225d95897Jesse Wilson
2012d0d626655f1d452070d3116678037e8759f807f4Jesse Wilson    // http://code.google.com/p/android/issues/detail?id=16895
2013d0d626655f1d452070d3116678037e8759f807f4Jesse Wilson    public void testUrlWithSpaceInHost() throws Exception {
2014d0d626655f1d452070d3116678037e8759f807f4Jesse Wilson        URLConnection urlConnection = new URL("http://and roid.com/").openConnection();
2015d0d626655f1d452070d3116678037e8759f807f4Jesse Wilson        try {
2016d0d626655f1d452070d3116678037e8759f807f4Jesse Wilson            urlConnection.getInputStream();
2017d0d626655f1d452070d3116678037e8759f807f4Jesse Wilson            fail();
2018d0d626655f1d452070d3116678037e8759f807f4Jesse Wilson        } catch (UnknownHostException expected) {
2019d0d626655f1d452070d3116678037e8759f807f4Jesse Wilson        }
2020d0d626655f1d452070d3116678037e8759f807f4Jesse Wilson    }
2021d0d626655f1d452070d3116678037e8759f807f4Jesse Wilson
2022d0d626655f1d452070d3116678037e8759f807f4Jesse Wilson    public void testUrlWithSpaceInHostViaHttpProxy() throws Exception {
2023d0d626655f1d452070d3116678037e8759f807f4Jesse Wilson        server.enqueue(new MockResponse());
2024d0d626655f1d452070d3116678037e8759f807f4Jesse Wilson        server.play();
2025d0d626655f1d452070d3116678037e8759f807f4Jesse Wilson        URLConnection urlConnection = new URL("http://and roid.com/")
2026d0d626655f1d452070d3116678037e8759f807f4Jesse Wilson                .openConnection(server.toProxyAddress());
2027d0d626655f1d452070d3116678037e8759f807f4Jesse Wilson        try {
2028d0d626655f1d452070d3116678037e8759f807f4Jesse Wilson            urlConnection.getInputStream();
2029d0d626655f1d452070d3116678037e8759f807f4Jesse Wilson            fail(); // the RI makes a bogus proxy request for "GET http://and roid.com/ HTTP/1.1"
2030d0d626655f1d452070d3116678037e8759f807f4Jesse Wilson        } catch (UnknownHostException expected) {
2031d0d626655f1d452070d3116678037e8759f807f4Jesse Wilson        }
2032d0d626655f1d452070d3116678037e8759f807f4Jesse Wilson    }
2033d0d626655f1d452070d3116678037e8759f807f4Jesse Wilson
2034bc4c79c6a2059003f695f7ad204de36700e8d701Jesse Wilson    /**
20350c59055dd24e1659f85d9ff7e2148883f663bd62Jesse Wilson     * Returns a gzipped copy of {@code bytes}.
2036deb236fb06f2a14861e7d40dea959f181cd5cf28Jesse Wilson     */
2037deb236fb06f2a14861e7d40dea959f181cd5cf28Jesse Wilson    public byte[] gzip(byte[] bytes) throws IOException {
2038deb236fb06f2a14861e7d40dea959f181cd5cf28Jesse Wilson        ByteArrayOutputStream bytesOut = new ByteArrayOutputStream();
2039deb236fb06f2a14861e7d40dea959f181cd5cf28Jesse Wilson        OutputStream gzippedOut = new GZIPOutputStream(bytesOut);
2040deb236fb06f2a14861e7d40dea959f181cd5cf28Jesse Wilson        gzippedOut.write(bytes);
2041deb236fb06f2a14861e7d40dea959f181cd5cf28Jesse Wilson        gzippedOut.close();
2042deb236fb06f2a14861e7d40dea959f181cd5cf28Jesse Wilson        return bytesOut.toByteArray();
2043deb236fb06f2a14861e7d40dea959f181cd5cf28Jesse Wilson    }
2044deb236fb06f2a14861e7d40dea959f181cd5cf28Jesse Wilson
2045c8977f474b30c5f3807398859a6b16687af6fc7bJesse Wilson    /**
2046c8977f474b30c5f3807398859a6b16687af6fc7bJesse Wilson     * Reads at most {@code limit} characters from {@code in} and asserts that
2047c8977f474b30c5f3807398859a6b16687af6fc7bJesse Wilson     * content equals {@code expected}.
2048c8977f474b30c5f3807398859a6b16687af6fc7bJesse Wilson     */
2049c8977f474b30c5f3807398859a6b16687af6fc7bJesse Wilson    private void assertContent(String expected, URLConnection connection, int limit)
2050c8977f474b30c5f3807398859a6b16687af6fc7bJesse Wilson            throws IOException {
2051f02c695ed03e708623d9365dec26d533356ef2d0Brian Carlstrom        connection.connect();
205251e468abf2628ce964d3657042f3ac8f2c947504Jesse Wilson        assertEquals(expected, readAscii(connection.getInputStream(), limit));
2053c8977f474b30c5f3807398859a6b16687af6fc7bJesse Wilson        ((HttpURLConnection) connection).disconnect();
2054c8977f474b30c5f3807398859a6b16687af6fc7bJesse Wilson    }
2055c8977f474b30c5f3807398859a6b16687af6fc7bJesse Wilson
2056c8977f474b30c5f3807398859a6b16687af6fc7bJesse Wilson    private void assertContent(String expected, URLConnection connection) throws IOException {
2057c8977f474b30c5f3807398859a6b16687af6fc7bJesse Wilson        assertContent(expected, connection, Integer.MAX_VALUE);
2058c8977f474b30c5f3807398859a6b16687af6fc7bJesse Wilson    }
2059c8977f474b30c5f3807398859a6b16687af6fc7bJesse Wilson
206060476787f0e0f052366d8031c74e507ffd3d16a3Jesse Wilson    private void assertContains(List<String> headers, String header) {
206160476787f0e0f052366d8031c74e507ffd3d16a3Jesse Wilson        assertTrue(headers.toString(), headers.contains(header));
206260476787f0e0f052366d8031c74e507ffd3d16a3Jesse Wilson    }
206351e468abf2628ce964d3657042f3ac8f2c947504Jesse Wilson
2064ffd579b668428272b78f5c6c64f9c89766f37c1aJesse Wilson    private void assertContainsNoneMatching(List<String> headers, String pattern) {
2065ffd579b668428272b78f5c6c64f9c89766f37c1aJesse Wilson        for (String header : headers) {
2066ffd579b668428272b78f5c6c64f9c89766f37c1aJesse Wilson            if (header.matches(pattern)) {
2067ffd579b668428272b78f5c6c64f9c89766f37c1aJesse Wilson                fail("Header " + header + " matches " + pattern);
2068ffd579b668428272b78f5c6c64f9c89766f37c1aJesse Wilson            }
2069ffd579b668428272b78f5c6c64f9c89766f37c1aJesse Wilson        }
2070ffd579b668428272b78f5c6c64f9c89766f37c1aJesse Wilson    }
2071ffd579b668428272b78f5c6c64f9c89766f37c1aJesse Wilson
2072eafede536f2059bb6c869e7a5f07fd7ad9758e28Jesse Wilson    private Set<String> newSet(String... elements) {
207383a47d4d0c536e06fc53eda9d5a1a5d93f9accc6Jesse Wilson        return new HashSet<String>(Arrays.asList(elements));
207483a47d4d0c536e06fc53eda9d5a1a5d93f9accc6Jesse Wilson    }
207583a47d4d0c536e06fc53eda9d5a1a5d93f9accc6Jesse Wilson
207651e468abf2628ce964d3657042f3ac8f2c947504Jesse Wilson    enum TransferKind {
207751e468abf2628ce964d3657042f3ac8f2c947504Jesse Wilson        CHUNKED() {
2078deb236fb06f2a14861e7d40dea959f181cd5cf28Jesse Wilson            @Override void setBody(MockResponse response, byte[] content, int chunkSize)
207951e468abf2628ce964d3657042f3ac8f2c947504Jesse Wilson                    throws IOException {
208051e468abf2628ce964d3657042f3ac8f2c947504Jesse Wilson                response.setChunkedBody(content, chunkSize);
208151e468abf2628ce964d3657042f3ac8f2c947504Jesse Wilson            }
208251e468abf2628ce964d3657042f3ac8f2c947504Jesse Wilson        },
208351e468abf2628ce964d3657042f3ac8f2c947504Jesse Wilson        FIXED_LENGTH() {
2084deb236fb06f2a14861e7d40dea959f181cd5cf28Jesse Wilson            @Override void setBody(MockResponse response, byte[] content, int chunkSize) {
208551e468abf2628ce964d3657042f3ac8f2c947504Jesse Wilson                response.setBody(content);
208651e468abf2628ce964d3657042f3ac8f2c947504Jesse Wilson            }
208751e468abf2628ce964d3657042f3ac8f2c947504Jesse Wilson        },
208851e468abf2628ce964d3657042f3ac8f2c947504Jesse Wilson        END_OF_STREAM() {
2089deb236fb06f2a14861e7d40dea959f181cd5cf28Jesse Wilson            @Override void setBody(MockResponse response, byte[] content, int chunkSize) {
209051e468abf2628ce964d3657042f3ac8f2c947504Jesse Wilson                response.setBody(content);
2091e942f46f10bb9384a1b186b3d7b74f9704c57090Jesse Wilson                response.setSocketPolicy(DISCONNECT_AT_END);
209251e468abf2628ce964d3657042f3ac8f2c947504Jesse Wilson                for (Iterator<String> h = response.getHeaders().iterator(); h.hasNext(); ) {
209351e468abf2628ce964d3657042f3ac8f2c947504Jesse Wilson                    if (h.next().startsWith("Content-Length:")) {
209451e468abf2628ce964d3657042f3ac8f2c947504Jesse Wilson                        h.remove();
209551e468abf2628ce964d3657042f3ac8f2c947504Jesse Wilson                        break;
209651e468abf2628ce964d3657042f3ac8f2c947504Jesse Wilson                    }
209751e468abf2628ce964d3657042f3ac8f2c947504Jesse Wilson                }
209851e468abf2628ce964d3657042f3ac8f2c947504Jesse Wilson            }
209951e468abf2628ce964d3657042f3ac8f2c947504Jesse Wilson        };
210051e468abf2628ce964d3657042f3ac8f2c947504Jesse Wilson
2101deb236fb06f2a14861e7d40dea959f181cd5cf28Jesse Wilson        abstract void setBody(MockResponse response, byte[] content, int chunkSize)
210251e468abf2628ce964d3657042f3ac8f2c947504Jesse Wilson                throws IOException;
2103deb236fb06f2a14861e7d40dea959f181cd5cf28Jesse Wilson
2104deb236fb06f2a14861e7d40dea959f181cd5cf28Jesse Wilson        void setBody(MockResponse response, String content, int chunkSize) throws IOException {
2105deb236fb06f2a14861e7d40dea959f181cd5cf28Jesse Wilson            setBody(response, content.getBytes("UTF-8"), chunkSize);
2106deb236fb06f2a14861e7d40dea959f181cd5cf28Jesse Wilson        }
210751e468abf2628ce964d3657042f3ac8f2c947504Jesse Wilson    }
2108c0372d90016d241ac979faa6fa1731f30b6f2a03Jesse Wilson
2109984fcff696380abd6ea14e80030f9fd2d09dbad0Jesse Wilson    enum ProxyConfig {
2110f02c695ed03e708623d9365dec26d533356ef2d0Brian Carlstrom        NO_PROXY() {
2111f02c695ed03e708623d9365dec26d533356ef2d0Brian Carlstrom            @Override public HttpURLConnection connect(MockWebServer server, URL url)
2112f02c695ed03e708623d9365dec26d533356ef2d0Brian Carlstrom                    throws IOException {
2113f02c695ed03e708623d9365dec26d533356ef2d0Brian Carlstrom                return (HttpURLConnection) url.openConnection(Proxy.NO_PROXY);
2114f02c695ed03e708623d9365dec26d533356ef2d0Brian Carlstrom            }
2115f02c695ed03e708623d9365dec26d533356ef2d0Brian Carlstrom        },
2116f02c695ed03e708623d9365dec26d533356ef2d0Brian Carlstrom
2117984fcff696380abd6ea14e80030f9fd2d09dbad0Jesse Wilson        CREATE_ARG() {
2118984fcff696380abd6ea14e80030f9fd2d09dbad0Jesse Wilson            @Override public HttpURLConnection connect(MockWebServer server, URL url)
2119984fcff696380abd6ea14e80030f9fd2d09dbad0Jesse Wilson                    throws IOException {
2120984fcff696380abd6ea14e80030f9fd2d09dbad0Jesse Wilson                return (HttpURLConnection) url.openConnection(server.toProxyAddress());
2121984fcff696380abd6ea14e80030f9fd2d09dbad0Jesse Wilson            }
2122984fcff696380abd6ea14e80030f9fd2d09dbad0Jesse Wilson        },
2123984fcff696380abd6ea14e80030f9fd2d09dbad0Jesse Wilson
2124984fcff696380abd6ea14e80030f9fd2d09dbad0Jesse Wilson        PROXY_SYSTEM_PROPERTY() {
2125984fcff696380abd6ea14e80030f9fd2d09dbad0Jesse Wilson            @Override public HttpURLConnection connect(MockWebServer server, URL url)
2126984fcff696380abd6ea14e80030f9fd2d09dbad0Jesse Wilson                    throws IOException {
2127984fcff696380abd6ea14e80030f9fd2d09dbad0Jesse Wilson                System.setProperty("proxyHost", "localhost");
2128984fcff696380abd6ea14e80030f9fd2d09dbad0Jesse Wilson                System.setProperty("proxyPort", Integer.toString(server.getPort()));
2129984fcff696380abd6ea14e80030f9fd2d09dbad0Jesse Wilson                return (HttpURLConnection) url.openConnection();
2130984fcff696380abd6ea14e80030f9fd2d09dbad0Jesse Wilson            }
2131984fcff696380abd6ea14e80030f9fd2d09dbad0Jesse Wilson        },
2132984fcff696380abd6ea14e80030f9fd2d09dbad0Jesse Wilson
2133984fcff696380abd6ea14e80030f9fd2d09dbad0Jesse Wilson        HTTP_PROXY_SYSTEM_PROPERTY() {
2134984fcff696380abd6ea14e80030f9fd2d09dbad0Jesse Wilson            @Override public HttpURLConnection connect(MockWebServer server, URL url)
2135984fcff696380abd6ea14e80030f9fd2d09dbad0Jesse Wilson                    throws IOException {
2136984fcff696380abd6ea14e80030f9fd2d09dbad0Jesse Wilson                System.setProperty("http.proxyHost", "localhost");
2137984fcff696380abd6ea14e80030f9fd2d09dbad0Jesse Wilson                System.setProperty("http.proxyPort", Integer.toString(server.getPort()));
2138984fcff696380abd6ea14e80030f9fd2d09dbad0Jesse Wilson                return (HttpURLConnection) url.openConnection();
2139984fcff696380abd6ea14e80030f9fd2d09dbad0Jesse Wilson            }
2140984fcff696380abd6ea14e80030f9fd2d09dbad0Jesse Wilson        },
2141984fcff696380abd6ea14e80030f9fd2d09dbad0Jesse Wilson
2142984fcff696380abd6ea14e80030f9fd2d09dbad0Jesse Wilson        HTTPS_PROXY_SYSTEM_PROPERTY() {
2143984fcff696380abd6ea14e80030f9fd2d09dbad0Jesse Wilson            @Override public HttpURLConnection connect(MockWebServer server, URL url)
2144984fcff696380abd6ea14e80030f9fd2d09dbad0Jesse Wilson                    throws IOException {
2145984fcff696380abd6ea14e80030f9fd2d09dbad0Jesse Wilson                System.setProperty("https.proxyHost", "localhost");
2146984fcff696380abd6ea14e80030f9fd2d09dbad0Jesse Wilson                System.setProperty("https.proxyPort", Integer.toString(server.getPort()));
2147984fcff696380abd6ea14e80030f9fd2d09dbad0Jesse Wilson                return (HttpURLConnection) url.openConnection();
2148984fcff696380abd6ea14e80030f9fd2d09dbad0Jesse Wilson            }
2149984fcff696380abd6ea14e80030f9fd2d09dbad0Jesse Wilson        };
2150984fcff696380abd6ea14e80030f9fd2d09dbad0Jesse Wilson
2151984fcff696380abd6ea14e80030f9fd2d09dbad0Jesse Wilson        public abstract HttpURLConnection connect(MockWebServer server, URL url) throws IOException;
2152984fcff696380abd6ea14e80030f9fd2d09dbad0Jesse Wilson    }
2153984fcff696380abd6ea14e80030f9fd2d09dbad0Jesse Wilson
2154c0372d90016d241ac979faa6fa1731f30b6f2a03Jesse Wilson    private static class RecordingTrustManager implements X509TrustManager {
2155c0372d90016d241ac979faa6fa1731f30b6f2a03Jesse Wilson        private final List<String> calls = new ArrayList<String>();
2156c0372d90016d241ac979faa6fa1731f30b6f2a03Jesse Wilson
2157c0372d90016d241ac979faa6fa1731f30b6f2a03Jesse Wilson        public X509Certificate[] getAcceptedIssuers() {
2158c0372d90016d241ac979faa6fa1731f30b6f2a03Jesse Wilson            calls.add("getAcceptedIssuers");
2159c0372d90016d241ac979faa6fa1731f30b6f2a03Jesse Wilson            return new X509Certificate[] {};
2160c0372d90016d241ac979faa6fa1731f30b6f2a03Jesse Wilson        }
2161c0372d90016d241ac979faa6fa1731f30b6f2a03Jesse Wilson
2162c0372d90016d241ac979faa6fa1731f30b6f2a03Jesse Wilson        public void checkClientTrusted(X509Certificate[] chain, String authType)
2163c0372d90016d241ac979faa6fa1731f30b6f2a03Jesse Wilson                throws CertificateException {
2164c0372d90016d241ac979faa6fa1731f30b6f2a03Jesse Wilson            calls.add("checkClientTrusted " + certificatesToString(chain) + " " + authType);
2165c0372d90016d241ac979faa6fa1731f30b6f2a03Jesse Wilson        }
2166c0372d90016d241ac979faa6fa1731f30b6f2a03Jesse Wilson
2167c0372d90016d241ac979faa6fa1731f30b6f2a03Jesse Wilson        public void checkServerTrusted(X509Certificate[] chain, String authType)
2168c0372d90016d241ac979faa6fa1731f30b6f2a03Jesse Wilson                throws CertificateException {
2169c0372d90016d241ac979faa6fa1731f30b6f2a03Jesse Wilson            calls.add("checkServerTrusted " + certificatesToString(chain) + " " + authType);
2170c0372d90016d241ac979faa6fa1731f30b6f2a03Jesse Wilson        }
2171c0372d90016d241ac979faa6fa1731f30b6f2a03Jesse Wilson
2172c0372d90016d241ac979faa6fa1731f30b6f2a03Jesse Wilson        private String certificatesToString(X509Certificate[] certificates) {
2173c0372d90016d241ac979faa6fa1731f30b6f2a03Jesse Wilson            List<String> result = new ArrayList<String>();
2174c0372d90016d241ac979faa6fa1731f30b6f2a03Jesse Wilson            for (X509Certificate certificate : certificates) {
2175c0372d90016d241ac979faa6fa1731f30b6f2a03Jesse Wilson                result.add(certificate.getSubjectDN() + " " + certificate.getSerialNumber());
2176c0372d90016d241ac979faa6fa1731f30b6f2a03Jesse Wilson            }
2177c0372d90016d241ac979faa6fa1731f30b6f2a03Jesse Wilson            return result.toString();
2178c0372d90016d241ac979faa6fa1731f30b6f2a03Jesse Wilson        }
2179c0372d90016d241ac979faa6fa1731f30b6f2a03Jesse Wilson    }
2180c0372d90016d241ac979faa6fa1731f30b6f2a03Jesse Wilson
2181c0372d90016d241ac979faa6fa1731f30b6f2a03Jesse Wilson    private static class RecordingHostnameVerifier implements HostnameVerifier {
2182c0372d90016d241ac979faa6fa1731f30b6f2a03Jesse Wilson        private final List<String> calls = new ArrayList<String>();
2183c0372d90016d241ac979faa6fa1731f30b6f2a03Jesse Wilson
2184c0372d90016d241ac979faa6fa1731f30b6f2a03Jesse Wilson        public boolean verify(String hostname, SSLSession session) {
2185c0372d90016d241ac979faa6fa1731f30b6f2a03Jesse Wilson            calls.add("verify " + hostname);
2186c0372d90016d241ac979faa6fa1731f30b6f2a03Jesse Wilson            return true;
2187c0372d90016d241ac979faa6fa1731f30b6f2a03Jesse Wilson        }
2188c0372d90016d241ac979faa6fa1731f30b6f2a03Jesse Wilson    }
21895757cb35ad2e58d7accb7f5d3db6f2d5e72f097dJesse Wilson
21905757cb35ad2e58d7accb7f5d3db6f2d5e72f097dJesse Wilson    private static class SimpleAuthenticator extends Authenticator {
21915757cb35ad2e58d7accb7f5d3db6f2d5e72f097dJesse Wilson        /** base64("username:password") */
21925757cb35ad2e58d7accb7f5d3db6f2d5e72f097dJesse Wilson        private static final String BASE_64_CREDENTIALS = "dXNlcm5hbWU6cGFzc3dvcmQ=";
21935757cb35ad2e58d7accb7f5d3db6f2d5e72f097dJesse Wilson
21945757cb35ad2e58d7accb7f5d3db6f2d5e72f097dJesse Wilson        private String expectedPrompt;
21955757cb35ad2e58d7accb7f5d3db6f2d5e72f097dJesse Wilson        private RequestorType requestorType;
21965757cb35ad2e58d7accb7f5d3db6f2d5e72f097dJesse Wilson        private int requestingPort;
21975757cb35ad2e58d7accb7f5d3db6f2d5e72f097dJesse Wilson        private InetAddress requestingSite;
21985757cb35ad2e58d7accb7f5d3db6f2d5e72f097dJesse Wilson        private String requestingPrompt;
21995757cb35ad2e58d7accb7f5d3db6f2d5e72f097dJesse Wilson        private String requestingProtocol;
22005757cb35ad2e58d7accb7f5d3db6f2d5e72f097dJesse Wilson        private String requestingScheme;
22015757cb35ad2e58d7accb7f5d3db6f2d5e72f097dJesse Wilson
22025757cb35ad2e58d7accb7f5d3db6f2d5e72f097dJesse Wilson        protected PasswordAuthentication getPasswordAuthentication() {
22035757cb35ad2e58d7accb7f5d3db6f2d5e72f097dJesse Wilson            requestorType = getRequestorType();
22045757cb35ad2e58d7accb7f5d3db6f2d5e72f097dJesse Wilson            requestingPort = getRequestingPort();
22055757cb35ad2e58d7accb7f5d3db6f2d5e72f097dJesse Wilson            requestingSite = getRequestingSite();
22065757cb35ad2e58d7accb7f5d3db6f2d5e72f097dJesse Wilson            requestingPrompt = getRequestingPrompt();
22075757cb35ad2e58d7accb7f5d3db6f2d5e72f097dJesse Wilson            requestingProtocol = getRequestingProtocol();
22085757cb35ad2e58d7accb7f5d3db6f2d5e72f097dJesse Wilson            requestingScheme = getRequestingScheme();
22095757cb35ad2e58d7accb7f5d3db6f2d5e72f097dJesse Wilson            return (expectedPrompt == null || expectedPrompt.equals(requestingPrompt))
22105757cb35ad2e58d7accb7f5d3db6f2d5e72f097dJesse Wilson                    ? new PasswordAuthentication("username", "password".toCharArray())
22115757cb35ad2e58d7accb7f5d3db6f2d5e72f097dJesse Wilson                    : null;
22125757cb35ad2e58d7accb7f5d3db6f2d5e72f097dJesse Wilson        }
22135757cb35ad2e58d7accb7f5d3db6f2d5e72f097dJesse Wilson    }
2214e40c9e3935a5024c0f3ebfb3f1441fcd5c48ed86Elliott Hughes}
2215