URLConnectionTest.java revision a468471e8ccc2f642d5b2ae3c75873a74267ece2
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;
374557728efb66c455a52b7669a8eefef7a9e54854Jesse Wilsonimport java.net.PasswordAuthentication;
38f14bee4dbf9f724a177a85a7b73f7b0bc6df1ec0Jesse Wilsonimport java.net.ProtocolException;
39f02c695ed03e708623d9365dec26d533356ef2d0Brian Carlstromimport java.net.Proxy;
404557728efb66c455a52b7669a8eefef7a9e54854Jesse Wilsonimport java.net.ResponseCache;
414557728efb66c455a52b7669a8eefef7a9e54854Jesse Wilsonimport java.net.SocketTimeoutException;
424557728efb66c455a52b7669a8eefef7a9e54854Jesse Wilsonimport java.net.URI;
434557728efb66c455a52b7669a8eefef7a9e54854Jesse Wilsonimport java.net.URL;
444557728efb66c455a52b7669a8eefef7a9e54854Jesse Wilsonimport java.net.URLConnection;
45c0372d90016d241ac979faa6fa1731f30b6f2a03Jesse Wilsonimport java.security.cert.CertificateException;
46c0372d90016d241ac979faa6fa1731f30b6f2a03Jesse Wilsonimport java.security.cert.X509Certificate;
4751e468abf2628ce964d3657042f3ac8f2c947504Jesse Wilsonimport java.util.ArrayList;
4802f0cb2eb84a112fcf644d7d1fd0b5f94ea2f03bElliott Hughesimport java.util.Arrays;
4951e468abf2628ce964d3657042f3ac8f2c947504Jesse Wilsonimport java.util.Collections;
5083a47d4d0c536e06fc53eda9d5a1a5d93f9accc6Jesse Wilsonimport java.util.HashSet;
5151e468abf2628ce964d3657042f3ac8f2c947504Jesse Wilsonimport java.util.Iterator;
526247987eb505a482a67f5f19678260d9e7240a5fElliott Hughesimport java.util.List;
5383a47d4d0c536e06fc53eda9d5a1a5d93f9accc6Jesse Wilsonimport java.util.Map;
5451e468abf2628ce964d3657042f3ac8f2c947504Jesse Wilsonimport java.util.Set;
55afd9b157f467b7c4f2f0b5592dca72f18d844602Jesse Wilsonimport java.util.concurrent.atomic.AtomicBoolean;
5683a47d4d0c536e06fc53eda9d5a1a5d93f9accc6Jesse Wilsonimport java.util.concurrent.atomic.AtomicReference;
57deb236fb06f2a14861e7d40dea959f181cd5cf28Jesse Wilsonimport java.util.zip.GZIPInputStream;
58deb236fb06f2a14861e7d40dea959f181cd5cf28Jesse Wilsonimport java.util.zip.GZIPOutputStream;
5960476787f0e0f052366d8031c74e507ffd3d16a3Jesse Wilsonimport javax.net.ssl.HostnameVerifier;
6060476787f0e0f052366d8031c74e507ffd3d16a3Jesse Wilsonimport javax.net.ssl.HttpsURLConnection;
61c0372d90016d241ac979faa6fa1731f30b6f2a03Jesse Wilsonimport javax.net.ssl.SSLContext;
62096aac7b8a607d3da237900f52cab1c5066bf992Jesse Wilsonimport javax.net.ssl.SSLException;
632915378e253f08e47fe5a9bfd026cd1ca7c6c351Brian Carlstromimport javax.net.ssl.SSLHandshakeException;
6460476787f0e0f052366d8031c74e507ffd3d16a3Jesse Wilsonimport javax.net.ssl.SSLSession;
65c0372d90016d241ac979faa6fa1731f30b6f2a03Jesse Wilsonimport javax.net.ssl.SSLSocketFactory;
66c0372d90016d241ac979faa6fa1731f30b6f2a03Jesse Wilsonimport javax.net.ssl.TrustManager;
67c0372d90016d241ac979faa6fa1731f30b6f2a03Jesse Wilsonimport javax.net.ssl.X509TrustManager;
68ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilsonimport junit.framework.TestCase;
692915378e253f08e47fe5a9bfd026cd1ca7c6c351Brian Carlstromimport libcore.java.security.TestKeyStore;
7050ae32218918eae80298bd1ab8e4f588bbbabdb2Jesse Wilsonimport libcore.javax.net.ssl.TestSSLContext;
715fc5dde4c719c1dfdac46b67d5d2e4884d07721eElliott Hughesimport tests.net.StuckServer;
72e40c9e3935a5024c0f3ebfb3f1441fcd5c48ed86Elliott Hughes
73ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilsonpublic final class URLConnectionTest extends TestCase {
74b1b5baac449d2725002338735f4db34bec8fd001Jesse Wilson
75ffd579b668428272b78f5c6c64f9c89766f37c1aJesse Wilson    private static final Authenticator SIMPLE_AUTHENTICATOR = new Authenticator() {
76ffd579b668428272b78f5c6c64f9c89766f37c1aJesse Wilson        protected PasswordAuthentication getPasswordAuthentication() {
77ffd579b668428272b78f5c6c64f9c89766f37c1aJesse Wilson            return new PasswordAuthentication("username", "password".toCharArray());
78ffd579b668428272b78f5c6c64f9c89766f37c1aJesse Wilson        }
79ffd579b668428272b78f5c6c64f9c89766f37c1aJesse Wilson    };
80ffd579b668428272b78f5c6c64f9c89766f37c1aJesse Wilson
81c996149b500fc4825156106554457fe2394ae087Jesse Wilson    /** base64("username:password") */
82c996149b500fc4825156106554457fe2394ae087Jesse Wilson    private static final String BASE_64_CREDENTIALS = "dXNlcm5hbWU6cGFzc3dvcmQ=";
83c996149b500fc4825156106554457fe2394ae087Jesse Wilson
8451e468abf2628ce964d3657042f3ac8f2c947504Jesse Wilson    private MockWebServer server = new MockWebServer();
850c2fd828abec671333b8b88281825fd27a783723Jesse Wilson    private String hostName;
8600feece22909b7dc79fc96d666d157390b93858eJesse Wilson
8700feece22909b7dc79fc96d666d157390b93858eJesse Wilson    @Override protected void setUp() throws Exception {
8800feece22909b7dc79fc96d666d157390b93858eJesse Wilson        super.setUp();
890c2fd828abec671333b8b88281825fd27a783723Jesse Wilson        hostName = server.getHostName();
9000feece22909b7dc79fc96d666d157390b93858eJesse Wilson    }
9151e468abf2628ce964d3657042f3ac8f2c947504Jesse Wilson
9251e468abf2628ce964d3657042f3ac8f2c947504Jesse Wilson    @Override protected void tearDown() throws Exception {
9351e468abf2628ce964d3657042f3ac8f2c947504Jesse Wilson        ResponseCache.setDefault(null);
94ffd579b668428272b78f5c6c64f9c89766f37c1aJesse Wilson        Authenticator.setDefault(null);
95984fcff696380abd6ea14e80030f9fd2d09dbad0Jesse Wilson        System.clearProperty("proxyHost");
96984fcff696380abd6ea14e80030f9fd2d09dbad0Jesse Wilson        System.clearProperty("proxyPort");
97984fcff696380abd6ea14e80030f9fd2d09dbad0Jesse Wilson        System.clearProperty("http.proxyHost");
98984fcff696380abd6ea14e80030f9fd2d09dbad0Jesse Wilson        System.clearProperty("http.proxyPort");
99984fcff696380abd6ea14e80030f9fd2d09dbad0Jesse Wilson        System.clearProperty("https.proxyHost");
100984fcff696380abd6ea14e80030f9fd2d09dbad0Jesse Wilson        System.clearProperty("https.proxyPort");
10151e468abf2628ce964d3657042f3ac8f2c947504Jesse Wilson        server.shutdown();
10200feece22909b7dc79fc96d666d157390b93858eJesse Wilson        super.tearDown();
10351e468abf2628ce964d3657042f3ac8f2c947504Jesse Wilson    }
10451e468abf2628ce964d3657042f3ac8f2c947504Jesse Wilson
10583a47d4d0c536e06fc53eda9d5a1a5d93f9accc6Jesse Wilson    public void testRequestHeaders() throws IOException, InterruptedException {
10683a47d4d0c536e06fc53eda9d5a1a5d93f9accc6Jesse Wilson        server.enqueue(new MockResponse());
10783a47d4d0c536e06fc53eda9d5a1a5d93f9accc6Jesse Wilson        server.play();
10883a47d4d0c536e06fc53eda9d5a1a5d93f9accc6Jesse Wilson
10983a47d4d0c536e06fc53eda9d5a1a5d93f9accc6Jesse Wilson        HttpURLConnection urlConnection = (HttpURLConnection) server.getUrl("/").openConnection();
11083a47d4d0c536e06fc53eda9d5a1a5d93f9accc6Jesse Wilson        urlConnection.addRequestProperty("D", "e");
11183a47d4d0c536e06fc53eda9d5a1a5d93f9accc6Jesse Wilson        urlConnection.addRequestProperty("D", "f");
112ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson        assertEquals("f", urlConnection.getRequestProperty("D"));
113ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson        assertEquals("f", urlConnection.getRequestProperty("d"));
11483a47d4d0c536e06fc53eda9d5a1a5d93f9accc6Jesse Wilson        Map<String, List<String>> requestHeaders = urlConnection.getRequestProperties();
11583a47d4d0c536e06fc53eda9d5a1a5d93f9accc6Jesse Wilson        assertEquals(newSet("e", "f"), new HashSet<String>(requestHeaders.get("D")));
116ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson        assertEquals(newSet("e", "f"), new HashSet<String>(requestHeaders.get("d")));
11783a47d4d0c536e06fc53eda9d5a1a5d93f9accc6Jesse Wilson        try {
11883a47d4d0c536e06fc53eda9d5a1a5d93f9accc6Jesse Wilson            requestHeaders.put("G", Arrays.asList("h"));
11983a47d4d0c536e06fc53eda9d5a1a5d93f9accc6Jesse Wilson            fail("Modified an unmodifiable view.");
12083a47d4d0c536e06fc53eda9d5a1a5d93f9accc6Jesse Wilson        } catch (UnsupportedOperationException expected) {
12183a47d4d0c536e06fc53eda9d5a1a5d93f9accc6Jesse Wilson        }
12283a47d4d0c536e06fc53eda9d5a1a5d93f9accc6Jesse Wilson        try {
12383a47d4d0c536e06fc53eda9d5a1a5d93f9accc6Jesse Wilson            requestHeaders.get("D").add("i");
12483a47d4d0c536e06fc53eda9d5a1a5d93f9accc6Jesse Wilson            fail("Modified an unmodifiable view.");
12583a47d4d0c536e06fc53eda9d5a1a5d93f9accc6Jesse Wilson        } catch (UnsupportedOperationException expected) {
12683a47d4d0c536e06fc53eda9d5a1a5d93f9accc6Jesse Wilson        }
12783a47d4d0c536e06fc53eda9d5a1a5d93f9accc6Jesse Wilson        try {
12883a47d4d0c536e06fc53eda9d5a1a5d93f9accc6Jesse Wilson            urlConnection.setRequestProperty(null, "j");
12983a47d4d0c536e06fc53eda9d5a1a5d93f9accc6Jesse Wilson            fail();
13083a47d4d0c536e06fc53eda9d5a1a5d93f9accc6Jesse Wilson        } catch (NullPointerException expected) {
13183a47d4d0c536e06fc53eda9d5a1a5d93f9accc6Jesse Wilson        }
13283a47d4d0c536e06fc53eda9d5a1a5d93f9accc6Jesse Wilson        try {
13383a47d4d0c536e06fc53eda9d5a1a5d93f9accc6Jesse Wilson            urlConnection.addRequestProperty(null, "k");
13483a47d4d0c536e06fc53eda9d5a1a5d93f9accc6Jesse Wilson            fail();
13583a47d4d0c536e06fc53eda9d5a1a5d93f9accc6Jesse Wilson        } catch (NullPointerException expected) {
13683a47d4d0c536e06fc53eda9d5a1a5d93f9accc6Jesse Wilson        }
13783a47d4d0c536e06fc53eda9d5a1a5d93f9accc6Jesse Wilson        urlConnection.setRequestProperty("NullValue", null); // should fail silently!
138ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson        assertNull(urlConnection.getRequestProperty("NullValue"));
13983a47d4d0c536e06fc53eda9d5a1a5d93f9accc6Jesse Wilson        urlConnection.addRequestProperty("AnotherNullValue", null);  // should fail silently!
140ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson        assertNull(urlConnection.getRequestProperty("AnotherNullValue"));
14183a47d4d0c536e06fc53eda9d5a1a5d93f9accc6Jesse Wilson
14283a47d4d0c536e06fc53eda9d5a1a5d93f9accc6Jesse Wilson        urlConnection.getResponseCode();
14383a47d4d0c536e06fc53eda9d5a1a5d93f9accc6Jesse Wilson        RecordedRequest request = server.takeRequest();
14483a47d4d0c536e06fc53eda9d5a1a5d93f9accc6Jesse Wilson        assertContains(request.getHeaders(), "D: e");
14583a47d4d0c536e06fc53eda9d5a1a5d93f9accc6Jesse Wilson        assertContains(request.getHeaders(), "D: f");
14683a47d4d0c536e06fc53eda9d5a1a5d93f9accc6Jesse Wilson        assertContainsNoneMatching(request.getHeaders(), "NullValue.*");
14783a47d4d0c536e06fc53eda9d5a1a5d93f9accc6Jesse Wilson        assertContainsNoneMatching(request.getHeaders(), "AnotherNullValue.*");
14883a47d4d0c536e06fc53eda9d5a1a5d93f9accc6Jesse Wilson        assertContainsNoneMatching(request.getHeaders(), "G:.*");
14983a47d4d0c536e06fc53eda9d5a1a5d93f9accc6Jesse Wilson        assertContainsNoneMatching(request.getHeaders(), "null:.*");
15083a47d4d0c536e06fc53eda9d5a1a5d93f9accc6Jesse Wilson
15183a47d4d0c536e06fc53eda9d5a1a5d93f9accc6Jesse Wilson        try {
15283a47d4d0c536e06fc53eda9d5a1a5d93f9accc6Jesse Wilson            urlConnection.addRequestProperty("N", "o");
15383a47d4d0c536e06fc53eda9d5a1a5d93f9accc6Jesse Wilson            fail("Set header after connect");
15483a47d4d0c536e06fc53eda9d5a1a5d93f9accc6Jesse Wilson        } catch (IllegalStateException expected) {
15583a47d4d0c536e06fc53eda9d5a1a5d93f9accc6Jesse Wilson        }
15683a47d4d0c536e06fc53eda9d5a1a5d93f9accc6Jesse Wilson        try {
15783a47d4d0c536e06fc53eda9d5a1a5d93f9accc6Jesse Wilson            urlConnection.setRequestProperty("P", "q");
15883a47d4d0c536e06fc53eda9d5a1a5d93f9accc6Jesse Wilson            fail("Set header after connect");
15983a47d4d0c536e06fc53eda9d5a1a5d93f9accc6Jesse Wilson        } catch (IllegalStateException expected) {
16083a47d4d0c536e06fc53eda9d5a1a5d93f9accc6Jesse Wilson        }
161ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson        try {
162ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson            urlConnection.getRequestProperties();
163ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson            fail();
164ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson        } catch (IllegalStateException expected) {
165ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson        }
166ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson    }
167ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson
168ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson    public void testGetRequestPropertyReturnsLastValue() throws Exception {
169ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson        server.play();
170ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson        HttpURLConnection urlConnection = (HttpURLConnection) server.getUrl("/").openConnection();
171ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson        urlConnection.addRequestProperty("A", "value1");
172ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson        urlConnection.addRequestProperty("A", "value2");
173ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson        assertEquals("value2", urlConnection.getRequestProperty("A"));
17483a47d4d0c536e06fc53eda9d5a1a5d93f9accc6Jesse Wilson    }
17583a47d4d0c536e06fc53eda9d5a1a5d93f9accc6Jesse Wilson
17683a47d4d0c536e06fc53eda9d5a1a5d93f9accc6Jesse Wilson    public void testResponseHeaders() throws IOException, InterruptedException {
17783a47d4d0c536e06fc53eda9d5a1a5d93f9accc6Jesse Wilson        server.enqueue(new MockResponse()
17883a47d4d0c536e06fc53eda9d5a1a5d93f9accc6Jesse Wilson                .setStatus("HTTP/1.0 200 Fantastic")
17983a47d4d0c536e06fc53eda9d5a1a5d93f9accc6Jesse Wilson                .addHeader("A: c")
180ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson                .addHeader("B: d")
181ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson                .addHeader("A: e")
18283a47d4d0c536e06fc53eda9d5a1a5d93f9accc6Jesse Wilson                .setChunkedBody("ABCDE\nFGHIJ\nKLMNO\nPQR", 8));
18383a47d4d0c536e06fc53eda9d5a1a5d93f9accc6Jesse Wilson        server.play();
18483a47d4d0c536e06fc53eda9d5a1a5d93f9accc6Jesse Wilson
18583a47d4d0c536e06fc53eda9d5a1a5d93f9accc6Jesse Wilson        HttpURLConnection urlConnection = (HttpURLConnection) server.getUrl("/").openConnection();
18683a47d4d0c536e06fc53eda9d5a1a5d93f9accc6Jesse Wilson        assertEquals(200, urlConnection.getResponseCode());
18783a47d4d0c536e06fc53eda9d5a1a5d93f9accc6Jesse Wilson        assertEquals("Fantastic", urlConnection.getResponseMessage());
188c1a675c80c69decadb736b245f0366f93a94a462Jesse Wilson        assertEquals("HTTP/1.0 200 Fantastic", urlConnection.getHeaderField(null));
18983a47d4d0c536e06fc53eda9d5a1a5d93f9accc6Jesse Wilson        Map<String, List<String>> responseHeaders = urlConnection.getHeaderFields();
1908ac847a52e72f0cefbb20a6850ae04468d433a9eJesse Wilson        assertEquals(Arrays.asList("HTTP/1.0 200 Fantastic"), responseHeaders.get(null));
191ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson        assertEquals(newSet("c", "e"), new HashSet<String>(responseHeaders.get("A")));
192ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson        assertEquals(newSet("c", "e"), new HashSet<String>(responseHeaders.get("a")));
19383a47d4d0c536e06fc53eda9d5a1a5d93f9accc6Jesse Wilson        try {
19483a47d4d0c536e06fc53eda9d5a1a5d93f9accc6Jesse Wilson            responseHeaders.put("N", Arrays.asList("o"));
19583a47d4d0c536e06fc53eda9d5a1a5d93f9accc6Jesse Wilson            fail("Modified an unmodifiable view.");
19683a47d4d0c536e06fc53eda9d5a1a5d93f9accc6Jesse Wilson        } catch (UnsupportedOperationException expected) {
19783a47d4d0c536e06fc53eda9d5a1a5d93f9accc6Jesse Wilson        }
19883a47d4d0c536e06fc53eda9d5a1a5d93f9accc6Jesse Wilson        try {
199ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson            responseHeaders.get("A").add("f");
20083a47d4d0c536e06fc53eda9d5a1a5d93f9accc6Jesse Wilson            fail("Modified an unmodifiable view.");
20183a47d4d0c536e06fc53eda9d5a1a5d93f9accc6Jesse Wilson        } catch (UnsupportedOperationException expected) {
20283a47d4d0c536e06fc53eda9d5a1a5d93f9accc6Jesse Wilson        }
203ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson        assertEquals("A", urlConnection.getHeaderFieldKey(0));
204ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson        assertEquals("c", urlConnection.getHeaderField(0));
205ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson        assertEquals("B", urlConnection.getHeaderFieldKey(1));
206ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson        assertEquals("d", urlConnection.getHeaderField(1));
207ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson        assertEquals("A", urlConnection.getHeaderFieldKey(2));
208ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson        assertEquals("e", urlConnection.getHeaderField(2));
209ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson    }
210ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson
211ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson    public void testGetErrorStreamOnSuccessfulRequest() throws Exception {
212ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson        server.enqueue(new MockResponse().setBody("A"));
213ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson        server.play();
214ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson        HttpURLConnection connection = (HttpURLConnection) server.getUrl("/").openConnection();
215ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson        assertNull(connection.getErrorStream());
216ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson    }
217ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson
218ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson    public void testGetErrorStreamOnUnsuccessfulRequest() throws Exception {
219ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson        server.enqueue(new MockResponse().setResponseCode(404).setBody("A"));
220ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson        server.play();
221ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson        HttpURLConnection connection = (HttpURLConnection) server.getUrl("/").openConnection();
222ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson        assertEquals("A", readAscii(connection.getErrorStream(), Integer.MAX_VALUE));
22383a47d4d0c536e06fc53eda9d5a1a5d93f9accc6Jesse Wilson    }
22483a47d4d0c536e06fc53eda9d5a1a5d93f9accc6Jesse Wilson
225e40c9e3935a5024c0f3ebfb3f1441fcd5c48ed86Elliott Hughes    // Check that if we don't read to the end of a response, the next request on the
226e40c9e3935a5024c0f3ebfb3f1441fcd5c48ed86Elliott Hughes    // recycled connection doesn't get the unread tail of the first request's response.
227e40c9e3935a5024c0f3ebfb3f1441fcd5c48ed86Elliott Hughes    // http://code.google.com/p/android/issues/detail?id=2939
228e40c9e3935a5024c0f3ebfb3f1441fcd5c48ed86Elliott Hughes    public void test_2939() throws Exception {
229b1b5baac449d2725002338735f4db34bec8fd001Jesse Wilson        MockResponse response = new MockResponse().setChunkedBody("ABCDE\nFGHIJ\nKLMNO\nPQR", 8);
230b1b5baac449d2725002338735f4db34bec8fd001Jesse Wilson
231b1b5baac449d2725002338735f4db34bec8fd001Jesse Wilson        server.enqueue(response);
232b1b5baac449d2725002338735f4db34bec8fd001Jesse Wilson        server.enqueue(response);
233b1b5baac449d2725002338735f4db34bec8fd001Jesse Wilson        server.play();
234b1b5baac449d2725002338735f4db34bec8fd001Jesse Wilson
235c8977f474b30c5f3807398859a6b16687af6fc7bJesse Wilson        assertContent("ABCDE", server.getUrl("/").openConnection(), 5);
236c8977f474b30c5f3807398859a6b16687af6fc7bJesse Wilson        assertContent("ABCDE", server.getUrl("/").openConnection(), 5);
2378baf143a7c8921d07b54adbc66ac1e5b42de5fe6Jesse Wilson    }
2388baf143a7c8921d07b54adbc66ac1e5b42de5fe6Jesse Wilson
239977a9954414ec41256b218e6278a8544ea135d45Elliott Hughes    // Check that we recognize a few basic mime types by extension.
240977a9954414ec41256b218e6278a8544ea135d45Elliott Hughes    // http://code.google.com/p/android/issues/detail?id=10100
241977a9954414ec41256b218e6278a8544ea135d45Elliott Hughes    public void test_10100() throws Exception {
242977a9954414ec41256b218e6278a8544ea135d45Elliott Hughes        assertEquals("image/jpeg", URLConnection.guessContentTypeFromName("someFile.jpg"));
243977a9954414ec41256b218e6278a8544ea135d45Elliott Hughes        assertEquals("application/pdf", URLConnection.guessContentTypeFromName("stuff.pdf"));
244977a9954414ec41256b218e6278a8544ea135d45Elliott Hughes    }
245977a9954414ec41256b218e6278a8544ea135d45Elliott Hughes
2468baf143a7c8921d07b54adbc66ac1e5b42de5fe6Jesse Wilson    public void testConnectionsArePooled() throws Exception {
247b1b5baac449d2725002338735f4db34bec8fd001Jesse Wilson        MockResponse response = new MockResponse().setBody("ABCDEFGHIJKLMNOPQR");
248b1b5baac449d2725002338735f4db34bec8fd001Jesse Wilson
249b1b5baac449d2725002338735f4db34bec8fd001Jesse Wilson        server.enqueue(response);
250b1b5baac449d2725002338735f4db34bec8fd001Jesse Wilson        server.enqueue(response);
251b1b5baac449d2725002338735f4db34bec8fd001Jesse Wilson        server.enqueue(response);
252b1b5baac449d2725002338735f4db34bec8fd001Jesse Wilson        server.play();
253b1b5baac449d2725002338735f4db34bec8fd001Jesse Wilson
25406e15e6c528fcb773bedb43e34b0577312570927Jesse Wilson        assertContent("ABCDEFGHIJKLMNOPQR", server.getUrl("/foo").openConnection());
255c8977f474b30c5f3807398859a6b16687af6fc7bJesse Wilson        assertEquals(0, server.takeRequest().getSequenceNumber());
25606e15e6c528fcb773bedb43e34b0577312570927Jesse Wilson        assertContent("ABCDEFGHIJKLMNOPQR", server.getUrl("/bar?baz=quux").openConnection());
257c8977f474b30c5f3807398859a6b16687af6fc7bJesse Wilson        assertEquals(1, server.takeRequest().getSequenceNumber());
25806e15e6c528fcb773bedb43e34b0577312570927Jesse Wilson        assertContent("ABCDEFGHIJKLMNOPQR", server.getUrl("/z").openConnection());
259c8977f474b30c5f3807398859a6b16687af6fc7bJesse Wilson        assertEquals(2, server.takeRequest().getSequenceNumber());
260c8977f474b30c5f3807398859a6b16687af6fc7bJesse Wilson    }
261c8977f474b30c5f3807398859a6b16687af6fc7bJesse Wilson
262c8977f474b30c5f3807398859a6b16687af6fc7bJesse Wilson    public void testChunkedConnectionsArePooled() throws Exception {
263c8977f474b30c5f3807398859a6b16687af6fc7bJesse Wilson        MockResponse response = new MockResponse().setChunkedBody("ABCDEFGHIJKLMNOPQR", 5);
264c8977f474b30c5f3807398859a6b16687af6fc7bJesse Wilson
265c8977f474b30c5f3807398859a6b16687af6fc7bJesse Wilson        server.enqueue(response);
266c8977f474b30c5f3807398859a6b16687af6fc7bJesse Wilson        server.enqueue(response);
267c8977f474b30c5f3807398859a6b16687af6fc7bJesse Wilson        server.enqueue(response);
268c8977f474b30c5f3807398859a6b16687af6fc7bJesse Wilson        server.play();
269c8977f474b30c5f3807398859a6b16687af6fc7bJesse Wilson
27006e15e6c528fcb773bedb43e34b0577312570927Jesse Wilson        assertContent("ABCDEFGHIJKLMNOPQR", server.getUrl("/foo").openConnection());
271b1b5baac449d2725002338735f4db34bec8fd001Jesse Wilson        assertEquals(0, server.takeRequest().getSequenceNumber());
27206e15e6c528fcb773bedb43e34b0577312570927Jesse Wilson        assertContent("ABCDEFGHIJKLMNOPQR", server.getUrl("/bar?baz=quux").openConnection());
273b1b5baac449d2725002338735f4db34bec8fd001Jesse Wilson        assertEquals(1, server.takeRequest().getSequenceNumber());
27406e15e6c528fcb773bedb43e34b0577312570927Jesse Wilson        assertContent("ABCDEFGHIJKLMNOPQR", server.getUrl("/z").openConnection());
275b1b5baac449d2725002338735f4db34bec8fd001Jesse Wilson        assertEquals(2, server.takeRequest().getSequenceNumber());
276e40c9e3935a5024c0f3ebfb3f1441fcd5c48ed86Elliott Hughes    }
27702f0cb2eb84a112fcf644d7d1fd0b5f94ea2f03bElliott Hughes
278e942f46f10bb9384a1b186b3d7b74f9704c57090Jesse Wilson    public void testServerClosesSocket() throws Exception {
279e942f46f10bb9384a1b186b3d7b74f9704c57090Jesse Wilson        testServerClosesOutput(DISCONNECT_AT_END);
280e942f46f10bb9384a1b186b3d7b74f9704c57090Jesse Wilson    }
281e942f46f10bb9384a1b186b3d7b74f9704c57090Jesse Wilson
282e942f46f10bb9384a1b186b3d7b74f9704c57090Jesse Wilson    public void testServerShutdownInput() throws Exception {
283e942f46f10bb9384a1b186b3d7b74f9704c57090Jesse Wilson        testServerClosesOutput(SHUTDOWN_INPUT_AT_END);
284e942f46f10bb9384a1b186b3d7b74f9704c57090Jesse Wilson    }
285e942f46f10bb9384a1b186b3d7b74f9704c57090Jesse Wilson
286e942f46f10bb9384a1b186b3d7b74f9704c57090Jesse Wilson    public void testServerShutdownOutput() throws Exception {
287e942f46f10bb9384a1b186b3d7b74f9704c57090Jesse Wilson        testServerClosesOutput(SHUTDOWN_OUTPUT_AT_END);
288e942f46f10bb9384a1b186b3d7b74f9704c57090Jesse Wilson    }
289e942f46f10bb9384a1b186b3d7b74f9704c57090Jesse Wilson
290e942f46f10bb9384a1b186b3d7b74f9704c57090Jesse Wilson    private void testServerClosesOutput(SocketPolicy socketPolicy) throws Exception {
291e942f46f10bb9384a1b186b3d7b74f9704c57090Jesse Wilson        server.enqueue(new MockResponse()
292e942f46f10bb9384a1b186b3d7b74f9704c57090Jesse Wilson                .setBody("This connection won't pool properly")
293e942f46f10bb9384a1b186b3d7b74f9704c57090Jesse Wilson                .setSocketPolicy(socketPolicy));
294e942f46f10bb9384a1b186b3d7b74f9704c57090Jesse Wilson        server.enqueue(new MockResponse()
295e942f46f10bb9384a1b186b3d7b74f9704c57090Jesse Wilson                .setBody("This comes after a busted connection"));
296e942f46f10bb9384a1b186b3d7b74f9704c57090Jesse Wilson        server.play();
297e942f46f10bb9384a1b186b3d7b74f9704c57090Jesse Wilson
298e942f46f10bb9384a1b186b3d7b74f9704c57090Jesse Wilson        assertContent("This connection won't pool properly", server.getUrl("/a").openConnection());
299e942f46f10bb9384a1b186b3d7b74f9704c57090Jesse Wilson        assertEquals(0, server.takeRequest().getSequenceNumber());
300e942f46f10bb9384a1b186b3d7b74f9704c57090Jesse Wilson        assertContent("This comes after a busted connection", server.getUrl("/b").openConnection());
301e942f46f10bb9384a1b186b3d7b74f9704c57090Jesse Wilson        // sequence number 0 means the HTTP socket connection was not reused
302e942f46f10bb9384a1b186b3d7b74f9704c57090Jesse Wilson        assertEquals(0, server.takeRequest().getSequenceNumber());
303e942f46f10bb9384a1b186b3d7b74f9704c57090Jesse Wilson    }
304e942f46f10bb9384a1b186b3d7b74f9704c57090Jesse Wilson
305b1b5baac449d2725002338735f4db34bec8fd001Jesse Wilson    enum WriteKind { BYTE_BY_BYTE, SMALL_BUFFERS, LARGE_BUFFERS }
30602f0cb2eb84a112fcf644d7d1fd0b5f94ea2f03bElliott Hughes
30702f0cb2eb84a112fcf644d7d1fd0b5f94ea2f03bElliott Hughes    public void test_chunkedUpload_byteByByte() throws Exception {
30851e468abf2628ce964d3657042f3ac8f2c947504Jesse Wilson        doUpload(TransferKind.CHUNKED, WriteKind.BYTE_BY_BYTE);
30902f0cb2eb84a112fcf644d7d1fd0b5f94ea2f03bElliott Hughes    }
31002f0cb2eb84a112fcf644d7d1fd0b5f94ea2f03bElliott Hughes
31102f0cb2eb84a112fcf644d7d1fd0b5f94ea2f03bElliott Hughes    public void test_chunkedUpload_smallBuffers() throws Exception {
31251e468abf2628ce964d3657042f3ac8f2c947504Jesse Wilson        doUpload(TransferKind.CHUNKED, WriteKind.SMALL_BUFFERS);
31302f0cb2eb84a112fcf644d7d1fd0b5f94ea2f03bElliott Hughes    }
31402f0cb2eb84a112fcf644d7d1fd0b5f94ea2f03bElliott Hughes
31502f0cb2eb84a112fcf644d7d1fd0b5f94ea2f03bElliott Hughes    public void test_chunkedUpload_largeBuffers() throws Exception {
31651e468abf2628ce964d3657042f3ac8f2c947504Jesse Wilson        doUpload(TransferKind.CHUNKED, WriteKind.LARGE_BUFFERS);
31702f0cb2eb84a112fcf644d7d1fd0b5f94ea2f03bElliott Hughes    }
31802f0cb2eb84a112fcf644d7d1fd0b5f94ea2f03bElliott Hughes
31902f0cb2eb84a112fcf644d7d1fd0b5f94ea2f03bElliott Hughes    public void test_fixedLengthUpload_byteByByte() throws Exception {
32051e468abf2628ce964d3657042f3ac8f2c947504Jesse Wilson        doUpload(TransferKind.FIXED_LENGTH, WriteKind.BYTE_BY_BYTE);
32102f0cb2eb84a112fcf644d7d1fd0b5f94ea2f03bElliott Hughes    }
32202f0cb2eb84a112fcf644d7d1fd0b5f94ea2f03bElliott Hughes
32302f0cb2eb84a112fcf644d7d1fd0b5f94ea2f03bElliott Hughes    public void test_fixedLengthUpload_smallBuffers() throws Exception {
32451e468abf2628ce964d3657042f3ac8f2c947504Jesse Wilson        doUpload(TransferKind.FIXED_LENGTH, WriteKind.SMALL_BUFFERS);
32502f0cb2eb84a112fcf644d7d1fd0b5f94ea2f03bElliott Hughes    }
32602f0cb2eb84a112fcf644d7d1fd0b5f94ea2f03bElliott Hughes
32702f0cb2eb84a112fcf644d7d1fd0b5f94ea2f03bElliott Hughes    public void test_fixedLengthUpload_largeBuffers() throws Exception {
32851e468abf2628ce964d3657042f3ac8f2c947504Jesse Wilson        doUpload(TransferKind.FIXED_LENGTH, WriteKind.LARGE_BUFFERS);
32902f0cb2eb84a112fcf644d7d1fd0b5f94ea2f03bElliott Hughes    }
33002f0cb2eb84a112fcf644d7d1fd0b5f94ea2f03bElliott Hughes
33151e468abf2628ce964d3657042f3ac8f2c947504Jesse Wilson    private void doUpload(TransferKind uploadKind, WriteKind writeKind) throws Exception {
33202f0cb2eb84a112fcf644d7d1fd0b5f94ea2f03bElliott Hughes        int n = 512*1024;
333b1b5baac449d2725002338735f4db34bec8fd001Jesse Wilson        server.setBodyLimit(0);
334b1b5baac449d2725002338735f4db34bec8fd001Jesse Wilson        server.enqueue(new MockResponse());
335b1b5baac449d2725002338735f4db34bec8fd001Jesse Wilson        server.play();
336b1b5baac449d2725002338735f4db34bec8fd001Jesse Wilson
337b1b5baac449d2725002338735f4db34bec8fd001Jesse Wilson        HttpURLConnection conn = (HttpURLConnection) server.getUrl("/").openConnection();
33802f0cb2eb84a112fcf644d7d1fd0b5f94ea2f03bElliott Hughes        conn.setDoOutput(true);
33902f0cb2eb84a112fcf644d7d1fd0b5f94ea2f03bElliott Hughes        conn.setRequestMethod("POST");
34051e468abf2628ce964d3657042f3ac8f2c947504Jesse Wilson        if (uploadKind == TransferKind.CHUNKED) {
34102f0cb2eb84a112fcf644d7d1fd0b5f94ea2f03bElliott Hughes            conn.setChunkedStreamingMode(-1);
34202f0cb2eb84a112fcf644d7d1fd0b5f94ea2f03bElliott Hughes        } else {
34302f0cb2eb84a112fcf644d7d1fd0b5f94ea2f03bElliott Hughes            conn.setFixedLengthStreamingMode(n);
34402f0cb2eb84a112fcf644d7d1fd0b5f94ea2f03bElliott Hughes        }
34502f0cb2eb84a112fcf644d7d1fd0b5f94ea2f03bElliott Hughes        OutputStream out = conn.getOutputStream();
34602f0cb2eb84a112fcf644d7d1fd0b5f94ea2f03bElliott Hughes        if (writeKind == WriteKind.BYTE_BY_BYTE) {
34702f0cb2eb84a112fcf644d7d1fd0b5f94ea2f03bElliott Hughes            for (int i = 0; i < n; ++i) {
34802f0cb2eb84a112fcf644d7d1fd0b5f94ea2f03bElliott Hughes                out.write('x');
34902f0cb2eb84a112fcf644d7d1fd0b5f94ea2f03bElliott Hughes            }
35002f0cb2eb84a112fcf644d7d1fd0b5f94ea2f03bElliott Hughes        } else {
35102f0cb2eb84a112fcf644d7d1fd0b5f94ea2f03bElliott Hughes            byte[] buf = new byte[writeKind == WriteKind.SMALL_BUFFERS ? 256 : 64*1024];
35202f0cb2eb84a112fcf644d7d1fd0b5f94ea2f03bElliott Hughes            Arrays.fill(buf, (byte) 'x');
35302f0cb2eb84a112fcf644d7d1fd0b5f94ea2f03bElliott Hughes            for (int i = 0; i < n; i += buf.length) {
35402f0cb2eb84a112fcf644d7d1fd0b5f94ea2f03bElliott Hughes                out.write(buf, 0, Math.min(buf.length, n - i));
35502f0cb2eb84a112fcf644d7d1fd0b5f94ea2f03bElliott Hughes            }
35602f0cb2eb84a112fcf644d7d1fd0b5f94ea2f03bElliott Hughes        }
35702f0cb2eb84a112fcf644d7d1fd0b5f94ea2f03bElliott Hughes        out.close();
3584cb7f05dc68abb23ae54a5891c369062185f2210Elliott Hughes        assertEquals(200, conn.getResponseCode());
359b1b5baac449d2725002338735f4db34bec8fd001Jesse Wilson        RecordedRequest request = server.takeRequest();
360b1b5baac449d2725002338735f4db34bec8fd001Jesse Wilson        assertEquals(n, request.getBodySize());
36151e468abf2628ce964d3657042f3ac8f2c947504Jesse Wilson        if (uploadKind == TransferKind.CHUNKED) {
362b1b5baac449d2725002338735f4db34bec8fd001Jesse Wilson            assertTrue(request.getChunkSizes().size() > 0);
363b1b5baac449d2725002338735f4db34bec8fd001Jesse Wilson        } else {
364b1b5baac449d2725002338735f4db34bec8fd001Jesse Wilson            assertTrue(request.getChunkSizes().isEmpty());
365b1b5baac449d2725002338735f4db34bec8fd001Jesse Wilson        }
36602f0cb2eb84a112fcf644d7d1fd0b5f94ea2f03bElliott Hughes    }
3676247987eb505a482a67f5f19678260d9e7240a5fElliott Hughes
368f14bee4dbf9f724a177a85a7b73f7b0bc6df1ec0Jesse Wilson    public void testGetResponseCodeNoResponseBody() throws Exception {
369f14bee4dbf9f724a177a85a7b73f7b0bc6df1ec0Jesse Wilson        server.enqueue(new MockResponse()
370f14bee4dbf9f724a177a85a7b73f7b0bc6df1ec0Jesse Wilson                .addHeader("abc: def"));
371f14bee4dbf9f724a177a85a7b73f7b0bc6df1ec0Jesse Wilson        server.play();
372f14bee4dbf9f724a177a85a7b73f7b0bc6df1ec0Jesse Wilson
373f14bee4dbf9f724a177a85a7b73f7b0bc6df1ec0Jesse Wilson        URL url = server.getUrl("/");
374f14bee4dbf9f724a177a85a7b73f7b0bc6df1ec0Jesse Wilson        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
375f14bee4dbf9f724a177a85a7b73f7b0bc6df1ec0Jesse Wilson        conn.setDoInput(false);
376f14bee4dbf9f724a177a85a7b73f7b0bc6df1ec0Jesse Wilson        assertEquals("def", conn.getHeaderField("abc"));
377f14bee4dbf9f724a177a85a7b73f7b0bc6df1ec0Jesse Wilson        assertEquals(200, conn.getResponseCode());
378f14bee4dbf9f724a177a85a7b73f7b0bc6df1ec0Jesse Wilson        try {
379f14bee4dbf9f724a177a85a7b73f7b0bc6df1ec0Jesse Wilson            conn.getInputStream();
380f14bee4dbf9f724a177a85a7b73f7b0bc6df1ec0Jesse Wilson            fail();
381f14bee4dbf9f724a177a85a7b73f7b0bc6df1ec0Jesse Wilson        } catch (ProtocolException expected) {
382f14bee4dbf9f724a177a85a7b73f7b0bc6df1ec0Jesse Wilson        }
383f14bee4dbf9f724a177a85a7b73f7b0bc6df1ec0Jesse Wilson    }
384f14bee4dbf9f724a177a85a7b73f7b0bc6df1ec0Jesse Wilson
38560476787f0e0f052366d8031c74e507ffd3d16a3Jesse Wilson    public void testConnectViaHttps() throws IOException, InterruptedException {
38660476787f0e0f052366d8031c74e507ffd3d16a3Jesse Wilson        TestSSLContext testSSLContext = TestSSLContext.create();
38760476787f0e0f052366d8031c74e507ffd3d16a3Jesse Wilson
388059dbc04218144f985b20a228bbe98139d400d0cBrian Carlstrom        server.useHttps(testSSLContext.serverContext.getSocketFactory(), false);
389c0372d90016d241ac979faa6fa1731f30b6f2a03Jesse Wilson        server.enqueue(new MockResponse().setBody("this response comes via HTTPS"));
39060476787f0e0f052366d8031c74e507ffd3d16a3Jesse Wilson        server.play();
39160476787f0e0f052366d8031c74e507ffd3d16a3Jesse Wilson
392096aac7b8a607d3da237900f52cab1c5066bf992Jesse Wilson        HttpsURLConnection connection = (HttpsURLConnection) server.getUrl("/foo").openConnection();
3934559b1d37edcb5d7f1da086cf2e3290388d74f46Brian Carlstrom        connection.setSSLSocketFactory(testSSLContext.clientContext.getSocketFactory());
39460476787f0e0f052366d8031c74e507ffd3d16a3Jesse Wilson
395c8977f474b30c5f3807398859a6b16687af6fc7bJesse Wilson        assertContent("this response comes via HTTPS", connection);
39660476787f0e0f052366d8031c74e507ffd3d16a3Jesse Wilson
39760476787f0e0f052366d8031c74e507ffd3d16a3Jesse Wilson        RecordedRequest request = server.takeRequest();
39860476787f0e0f052366d8031c74e507ffd3d16a3Jesse Wilson        assertEquals("GET /foo HTTP/1.1", request.getRequestLine());
39960476787f0e0f052366d8031c74e507ffd3d16a3Jesse Wilson    }
40060476787f0e0f052366d8031c74e507ffd3d16a3Jesse Wilson
401096aac7b8a607d3da237900f52cab1c5066bf992Jesse Wilson    public void testConnectViaHttpsReusingConnections() throws IOException, InterruptedException {
402096aac7b8a607d3da237900f52cab1c5066bf992Jesse Wilson        TestSSLContext testSSLContext = TestSSLContext.create();
403096aac7b8a607d3da237900f52cab1c5066bf992Jesse Wilson
404059dbc04218144f985b20a228bbe98139d400d0cBrian Carlstrom        server.useHttps(testSSLContext.serverContext.getSocketFactory(), false);
405096aac7b8a607d3da237900f52cab1c5066bf992Jesse Wilson        server.enqueue(new MockResponse().setBody("this response comes via HTTPS"));
406096aac7b8a607d3da237900f52cab1c5066bf992Jesse Wilson        server.enqueue(new MockResponse().setBody("another response via HTTPS"));
407096aac7b8a607d3da237900f52cab1c5066bf992Jesse Wilson        server.play();
408096aac7b8a607d3da237900f52cab1c5066bf992Jesse Wilson
409b7155fd57239e986bbaba254a91aeb9600d60305Jesse Wilson        HttpsURLConnection connection = (HttpsURLConnection) server.getUrl("/").openConnection();
410b7155fd57239e986bbaba254a91aeb9600d60305Jesse Wilson        connection.setSSLSocketFactory(testSSLContext.clientContext.getSocketFactory());
411b7155fd57239e986bbaba254a91aeb9600d60305Jesse Wilson        assertContent("this response comes via HTTPS", connection);
412b7155fd57239e986bbaba254a91aeb9600d60305Jesse Wilson
413b7155fd57239e986bbaba254a91aeb9600d60305Jesse Wilson        connection = (HttpsURLConnection) server.getUrl("/").openConnection();
414b7155fd57239e986bbaba254a91aeb9600d60305Jesse Wilson        connection.setSSLSocketFactory(testSSLContext.clientContext.getSocketFactory());
415b7155fd57239e986bbaba254a91aeb9600d60305Jesse Wilson        assertContent("another response via HTTPS", connection);
416b7155fd57239e986bbaba254a91aeb9600d60305Jesse Wilson
417b7155fd57239e986bbaba254a91aeb9600d60305Jesse Wilson        assertEquals(0, server.takeRequest().getSequenceNumber());
418b7155fd57239e986bbaba254a91aeb9600d60305Jesse Wilson        assertEquals(1, server.takeRequest().getSequenceNumber());
419b7155fd57239e986bbaba254a91aeb9600d60305Jesse Wilson    }
420b7155fd57239e986bbaba254a91aeb9600d60305Jesse Wilson
4218116f7e97e00d223e7fbe5c950c9a5e3277de124Jesse Wilson    public void testConnectViaHttpsReusingConnectionsDifferentFactories()
422b7155fd57239e986bbaba254a91aeb9600d60305Jesse Wilson            throws IOException, InterruptedException {
423b7155fd57239e986bbaba254a91aeb9600d60305Jesse Wilson        TestSSLContext testSSLContext = TestSSLContext.create();
424b7155fd57239e986bbaba254a91aeb9600d60305Jesse Wilson
425b7155fd57239e986bbaba254a91aeb9600d60305Jesse Wilson        server.useHttps(testSSLContext.serverContext.getSocketFactory(), false);
426b7155fd57239e986bbaba254a91aeb9600d60305Jesse Wilson        server.enqueue(new MockResponse().setBody("this response comes via HTTPS"));
427b7155fd57239e986bbaba254a91aeb9600d60305Jesse Wilson        server.enqueue(new MockResponse().setBody("another response via HTTPS"));
428b7155fd57239e986bbaba254a91aeb9600d60305Jesse Wilson        server.play();
429b7155fd57239e986bbaba254a91aeb9600d60305Jesse Wilson
430096aac7b8a607d3da237900f52cab1c5066bf992Jesse Wilson        // install a custom SSL socket factory so the server can be authorized
431096aac7b8a607d3da237900f52cab1c5066bf992Jesse Wilson        HttpsURLConnection connection = (HttpsURLConnection) server.getUrl("/").openConnection();
432059dbc04218144f985b20a228bbe98139d400d0cBrian Carlstrom        connection.setSSLSocketFactory(testSSLContext.clientContext.getSocketFactory());
433096aac7b8a607d3da237900f52cab1c5066bf992Jesse Wilson        assertContent("this response comes via HTTPS", connection);
434096aac7b8a607d3da237900f52cab1c5066bf992Jesse Wilson
435096aac7b8a607d3da237900f52cab1c5066bf992Jesse Wilson        connection = (HttpsURLConnection) server.getUrl("/").openConnection();
436096aac7b8a607d3da237900f52cab1c5066bf992Jesse Wilson        try {
437096aac7b8a607d3da237900f52cab1c5066bf992Jesse Wilson            readAscii(connection.getInputStream(), Integer.MAX_VALUE);
438b7155fd57239e986bbaba254a91aeb9600d60305Jesse Wilson            fail("without an SSL socket factory, the connection should fail");
439096aac7b8a607d3da237900f52cab1c5066bf992Jesse Wilson        } catch (SSLException expected) {
440096aac7b8a607d3da237900f52cab1c5066bf992Jesse Wilson        }
441096aac7b8a607d3da237900f52cab1c5066bf992Jesse Wilson    }
442096aac7b8a607d3da237900f52cab1c5066bf992Jesse Wilson
4434559b1d37edcb5d7f1da086cf2e3290388d74f46Brian Carlstrom    public void testConnectViaHttpsWithSSLFallback() throws IOException, InterruptedException {
4444559b1d37edcb5d7f1da086cf2e3290388d74f46Brian Carlstrom        TestSSLContext testSSLContext = TestSSLContext.create();
4454559b1d37edcb5d7f1da086cf2e3290388d74f46Brian Carlstrom
4464559b1d37edcb5d7f1da086cf2e3290388d74f46Brian Carlstrom        server.useHttps(testSSLContext.serverContext.getSocketFactory(), false);
447e942f46f10bb9384a1b186b3d7b74f9704c57090Jesse Wilson        server.enqueue(new MockResponse().setSocketPolicy(DISCONNECT_AT_START));
4484559b1d37edcb5d7f1da086cf2e3290388d74f46Brian Carlstrom        server.enqueue(new MockResponse().setBody("this response comes via SSL"));
4494559b1d37edcb5d7f1da086cf2e3290388d74f46Brian Carlstrom        server.play();
4504559b1d37edcb5d7f1da086cf2e3290388d74f46Brian Carlstrom
4514559b1d37edcb5d7f1da086cf2e3290388d74f46Brian Carlstrom        HttpsURLConnection connection = (HttpsURLConnection) server.getUrl("/foo").openConnection();
4524559b1d37edcb5d7f1da086cf2e3290388d74f46Brian Carlstrom        connection.setSSLSocketFactory(testSSLContext.clientContext.getSocketFactory());
4534559b1d37edcb5d7f1da086cf2e3290388d74f46Brian Carlstrom
4544559b1d37edcb5d7f1da086cf2e3290388d74f46Brian Carlstrom        assertContent("this response comes via SSL", connection);
4554559b1d37edcb5d7f1da086cf2e3290388d74f46Brian Carlstrom
4564559b1d37edcb5d7f1da086cf2e3290388d74f46Brian Carlstrom        RecordedRequest request = server.takeRequest();
4574559b1d37edcb5d7f1da086cf2e3290388d74f46Brian Carlstrom        assertEquals("GET /foo HTTP/1.1", request.getRequestLine());
4584559b1d37edcb5d7f1da086cf2e3290388d74f46Brian Carlstrom    }
4594559b1d37edcb5d7f1da086cf2e3290388d74f46Brian Carlstrom
4602915378e253f08e47fe5a9bfd026cd1ca7c6c351Brian Carlstrom    /**
4612915378e253f08e47fe5a9bfd026cd1ca7c6c351Brian Carlstrom     * Verify that we don't retry connections on certificate verification errors.
4622915378e253f08e47fe5a9bfd026cd1ca7c6c351Brian Carlstrom     *
4632915378e253f08e47fe5a9bfd026cd1ca7c6c351Brian Carlstrom     * http://code.google.com/p/android/issues/detail?id=13178
4642915378e253f08e47fe5a9bfd026cd1ca7c6c351Brian Carlstrom     */
4652915378e253f08e47fe5a9bfd026cd1ca7c6c351Brian Carlstrom    public void testConnectViaHttpsToUntrustedServer() throws IOException, InterruptedException {
4662915378e253f08e47fe5a9bfd026cd1ca7c6c351Brian Carlstrom        TestSSLContext testSSLContext = TestSSLContext.create(TestKeyStore.getClientCA2(),
4672915378e253f08e47fe5a9bfd026cd1ca7c6c351Brian Carlstrom                                                              TestKeyStore.getServer());
4682915378e253f08e47fe5a9bfd026cd1ca7c6c351Brian Carlstrom
4692915378e253f08e47fe5a9bfd026cd1ca7c6c351Brian Carlstrom        server.useHttps(testSSLContext.serverContext.getSocketFactory(), false);
4702915378e253f08e47fe5a9bfd026cd1ca7c6c351Brian Carlstrom        server.enqueue(new MockResponse()); // unused
4712915378e253f08e47fe5a9bfd026cd1ca7c6c351Brian Carlstrom        server.play();
4722915378e253f08e47fe5a9bfd026cd1ca7c6c351Brian Carlstrom
4732915378e253f08e47fe5a9bfd026cd1ca7c6c351Brian Carlstrom        HttpsURLConnection connection = (HttpsURLConnection) server.getUrl("/foo").openConnection();
4742915378e253f08e47fe5a9bfd026cd1ca7c6c351Brian Carlstrom        connection.setSSLSocketFactory(testSSLContext.clientContext.getSocketFactory());
4752915378e253f08e47fe5a9bfd026cd1ca7c6c351Brian Carlstrom        try {
4762915378e253f08e47fe5a9bfd026cd1ca7c6c351Brian Carlstrom            connection.getInputStream();
4772915378e253f08e47fe5a9bfd026cd1ca7c6c351Brian Carlstrom            fail();
4782915378e253f08e47fe5a9bfd026cd1ca7c6c351Brian Carlstrom        } catch (SSLHandshakeException expected) {
4792915378e253f08e47fe5a9bfd026cd1ca7c6c351Brian Carlstrom            assertTrue(expected.getCause() instanceof CertificateException);
4802915378e253f08e47fe5a9bfd026cd1ca7c6c351Brian Carlstrom        }
4812915378e253f08e47fe5a9bfd026cd1ca7c6c351Brian Carlstrom        assertEquals(0, server.getRequestCount());
4822915378e253f08e47fe5a9bfd026cd1ca7c6c351Brian Carlstrom    }
4832915378e253f08e47fe5a9bfd026cd1ca7c6c351Brian Carlstrom
484984fcff696380abd6ea14e80030f9fd2d09dbad0Jesse Wilson    public void testConnectViaProxyUsingProxyArg() throws Exception {
485984fcff696380abd6ea14e80030f9fd2d09dbad0Jesse Wilson        testConnectViaProxy(ProxyConfig.CREATE_ARG);
486984fcff696380abd6ea14e80030f9fd2d09dbad0Jesse Wilson    }
487984fcff696380abd6ea14e80030f9fd2d09dbad0Jesse Wilson
488984fcff696380abd6ea14e80030f9fd2d09dbad0Jesse Wilson    public void testConnectViaProxyUsingProxySystemProperty() throws Exception {
489984fcff696380abd6ea14e80030f9fd2d09dbad0Jesse Wilson        testConnectViaProxy(ProxyConfig.PROXY_SYSTEM_PROPERTY);
490984fcff696380abd6ea14e80030f9fd2d09dbad0Jesse Wilson    }
491984fcff696380abd6ea14e80030f9fd2d09dbad0Jesse Wilson
492984fcff696380abd6ea14e80030f9fd2d09dbad0Jesse Wilson    public void testConnectViaProxyUsingHttpProxySystemProperty() throws Exception {
493984fcff696380abd6ea14e80030f9fd2d09dbad0Jesse Wilson        testConnectViaProxy(ProxyConfig.HTTP_PROXY_SYSTEM_PROPERTY);
494984fcff696380abd6ea14e80030f9fd2d09dbad0Jesse Wilson    }
495984fcff696380abd6ea14e80030f9fd2d09dbad0Jesse Wilson
496984fcff696380abd6ea14e80030f9fd2d09dbad0Jesse Wilson    private void testConnectViaProxy(ProxyConfig proxyConfig) throws Exception {
497c0372d90016d241ac979faa6fa1731f30b6f2a03Jesse Wilson        MockResponse mockResponse = new MockResponse().setBody("this response comes via a proxy");
49851e468abf2628ce964d3657042f3ac8f2c947504Jesse Wilson        server.enqueue(mockResponse);
49951e468abf2628ce964d3657042f3ac8f2c947504Jesse Wilson        server.play();
50060476787f0e0f052366d8031c74e507ffd3d16a3Jesse Wilson
501984fcff696380abd6ea14e80030f9fd2d09dbad0Jesse Wilson        URL url = new URL("http://android.com/foo");
502984fcff696380abd6ea14e80030f9fd2d09dbad0Jesse Wilson        HttpURLConnection connection = proxyConfig.connect(server, url);
503c8977f474b30c5f3807398859a6b16687af6fc7bJesse Wilson        assertContent("this response comes via a proxy", connection);
50460476787f0e0f052366d8031c74e507ffd3d16a3Jesse Wilson
50551e468abf2628ce964d3657042f3ac8f2c947504Jesse Wilson        RecordedRequest request = server.takeRequest();
50660476787f0e0f052366d8031c74e507ffd3d16a3Jesse Wilson        assertEquals("GET http://android.com/foo HTTP/1.1", request.getRequestLine());
50760476787f0e0f052366d8031c74e507ffd3d16a3Jesse Wilson        assertContains(request.getHeaders(), "Host: android.com");
50860476787f0e0f052366d8031c74e507ffd3d16a3Jesse Wilson    }
50960476787f0e0f052366d8031c74e507ffd3d16a3Jesse Wilson
510c8977f474b30c5f3807398859a6b16687af6fc7bJesse Wilson    public void testContentDisagreesWithContentLengthHeader() throws IOException {
511c8977f474b30c5f3807398859a6b16687af6fc7bJesse Wilson        server.enqueue(new MockResponse()
512c8977f474b30c5f3807398859a6b16687af6fc7bJesse Wilson                .setBody("abc\r\nYOU SHOULD NOT SEE THIS")
513c8977f474b30c5f3807398859a6b16687af6fc7bJesse Wilson                .clearHeaders()
514c8977f474b30c5f3807398859a6b16687af6fc7bJesse Wilson                .addHeader("Content-Length: 3"));
515c8977f474b30c5f3807398859a6b16687af6fc7bJesse Wilson        server.play();
516c8977f474b30c5f3807398859a6b16687af6fc7bJesse Wilson
517c8977f474b30c5f3807398859a6b16687af6fc7bJesse Wilson        assertContent("abc", server.getUrl("/").openConnection());
518c8977f474b30c5f3807398859a6b16687af6fc7bJesse Wilson    }
519c8977f474b30c5f3807398859a6b16687af6fc7bJesse Wilson
520c8977f474b30c5f3807398859a6b16687af6fc7bJesse Wilson    public void testContentDisagreesWithChunkedHeader() throws IOException {
521c8977f474b30c5f3807398859a6b16687af6fc7bJesse Wilson        MockResponse mockResponse = new MockResponse();
522c8977f474b30c5f3807398859a6b16687af6fc7bJesse Wilson        mockResponse.setChunkedBody("abc", 3);
523c8977f474b30c5f3807398859a6b16687af6fc7bJesse Wilson        ByteArrayOutputStream bytesOut = new ByteArrayOutputStream();
524c8977f474b30c5f3807398859a6b16687af6fc7bJesse Wilson        bytesOut.write(mockResponse.getBody());
525c8977f474b30c5f3807398859a6b16687af6fc7bJesse Wilson        bytesOut.write("\r\nYOU SHOULD NOT SEE THIS".getBytes());
526c8977f474b30c5f3807398859a6b16687af6fc7bJesse Wilson        mockResponse.setBody(bytesOut.toByteArray());
527c8977f474b30c5f3807398859a6b16687af6fc7bJesse Wilson        mockResponse.clearHeaders();
528c8977f474b30c5f3807398859a6b16687af6fc7bJesse Wilson        mockResponse.addHeader("Transfer-encoding: chunked");
529c8977f474b30c5f3807398859a6b16687af6fc7bJesse Wilson
530c8977f474b30c5f3807398859a6b16687af6fc7bJesse Wilson        server.enqueue(mockResponse);
531c8977f474b30c5f3807398859a6b16687af6fc7bJesse Wilson        server.play();
532c8977f474b30c5f3807398859a6b16687af6fc7bJesse Wilson
533c8977f474b30c5f3807398859a6b16687af6fc7bJesse Wilson        assertContent("abc", server.getUrl("/").openConnection());
534c8977f474b30c5f3807398859a6b16687af6fc7bJesse Wilson    }
535c8977f474b30c5f3807398859a6b16687af6fc7bJesse Wilson
536f02c695ed03e708623d9365dec26d533356ef2d0Brian Carlstrom    public void testConnectViaHttpProxyToHttpsUsingProxyArgWithNoProxy() throws Exception {
537f02c695ed03e708623d9365dec26d533356ef2d0Brian Carlstrom        testConnectViaDirectProxyToHttps(ProxyConfig.NO_PROXY);
538f02c695ed03e708623d9365dec26d533356ef2d0Brian Carlstrom    }
539f02c695ed03e708623d9365dec26d533356ef2d0Brian Carlstrom
540f02c695ed03e708623d9365dec26d533356ef2d0Brian Carlstrom    public void testConnectViaHttpProxyToHttpsUsingHttpProxySystemProperty() throws Exception {
541f02c695ed03e708623d9365dec26d533356ef2d0Brian Carlstrom        // https should not use http proxy
542f02c695ed03e708623d9365dec26d533356ef2d0Brian Carlstrom        testConnectViaDirectProxyToHttps(ProxyConfig.HTTP_PROXY_SYSTEM_PROPERTY);
543f02c695ed03e708623d9365dec26d533356ef2d0Brian Carlstrom    }
544f02c695ed03e708623d9365dec26d533356ef2d0Brian Carlstrom
545f02c695ed03e708623d9365dec26d533356ef2d0Brian Carlstrom    private void testConnectViaDirectProxyToHttps(ProxyConfig proxyConfig) throws Exception {
546f02c695ed03e708623d9365dec26d533356ef2d0Brian Carlstrom        TestSSLContext testSSLContext = TestSSLContext.create();
547f02c695ed03e708623d9365dec26d533356ef2d0Brian Carlstrom
548f02c695ed03e708623d9365dec26d533356ef2d0Brian Carlstrom        server.useHttps(testSSLContext.serverContext.getSocketFactory(), false);
549f02c695ed03e708623d9365dec26d533356ef2d0Brian Carlstrom        server.enqueue(new MockResponse().setBody("this response comes via HTTPS"));
550f02c695ed03e708623d9365dec26d533356ef2d0Brian Carlstrom        server.play();
551f02c695ed03e708623d9365dec26d533356ef2d0Brian Carlstrom
552f02c695ed03e708623d9365dec26d533356ef2d0Brian Carlstrom        URL url = server.getUrl("/foo");
553f02c695ed03e708623d9365dec26d533356ef2d0Brian Carlstrom        HttpsURLConnection connection = (HttpsURLConnection) proxyConfig.connect(server, url);
554f02c695ed03e708623d9365dec26d533356ef2d0Brian Carlstrom        connection.setSSLSocketFactory(testSSLContext.clientContext.getSocketFactory());
555f02c695ed03e708623d9365dec26d533356ef2d0Brian Carlstrom
556f02c695ed03e708623d9365dec26d533356ef2d0Brian Carlstrom        assertContent("this response comes via HTTPS", connection);
557f02c695ed03e708623d9365dec26d533356ef2d0Brian Carlstrom
558f02c695ed03e708623d9365dec26d533356ef2d0Brian Carlstrom        RecordedRequest request = server.takeRequest();
559f02c695ed03e708623d9365dec26d533356ef2d0Brian Carlstrom        assertEquals("GET /foo HTTP/1.1", request.getRequestLine());
560f02c695ed03e708623d9365dec26d533356ef2d0Brian Carlstrom    }
561f02c695ed03e708623d9365dec26d533356ef2d0Brian Carlstrom
562f02c695ed03e708623d9365dec26d533356ef2d0Brian Carlstrom
563984fcff696380abd6ea14e80030f9fd2d09dbad0Jesse Wilson    public void testConnectViaHttpProxyToHttpsUsingProxyArg() throws Exception {
564984fcff696380abd6ea14e80030f9fd2d09dbad0Jesse Wilson        testConnectViaHttpProxyToHttps(ProxyConfig.CREATE_ARG);
565984fcff696380abd6ea14e80030f9fd2d09dbad0Jesse Wilson    }
566984fcff696380abd6ea14e80030f9fd2d09dbad0Jesse Wilson
567984fcff696380abd6ea14e80030f9fd2d09dbad0Jesse Wilson    /**
568984fcff696380abd6ea14e80030f9fd2d09dbad0Jesse Wilson     * We weren't honoring all of the appropriate proxy system properties when
569984fcff696380abd6ea14e80030f9fd2d09dbad0Jesse Wilson     * connecting via HTTPS. http://b/3097518
570984fcff696380abd6ea14e80030f9fd2d09dbad0Jesse Wilson     */
571984fcff696380abd6ea14e80030f9fd2d09dbad0Jesse Wilson    public void testConnectViaHttpProxyToHttpsUsingProxySystemProperty() throws Exception {
572984fcff696380abd6ea14e80030f9fd2d09dbad0Jesse Wilson        testConnectViaHttpProxyToHttps(ProxyConfig.PROXY_SYSTEM_PROPERTY);
573984fcff696380abd6ea14e80030f9fd2d09dbad0Jesse Wilson    }
574984fcff696380abd6ea14e80030f9fd2d09dbad0Jesse Wilson
575984fcff696380abd6ea14e80030f9fd2d09dbad0Jesse Wilson    public void testConnectViaHttpProxyToHttpsUsingHttpsProxySystemProperty() throws Exception {
576984fcff696380abd6ea14e80030f9fd2d09dbad0Jesse Wilson        testConnectViaHttpProxyToHttps(ProxyConfig.HTTPS_PROXY_SYSTEM_PROPERTY);
577984fcff696380abd6ea14e80030f9fd2d09dbad0Jesse Wilson    }
578984fcff696380abd6ea14e80030f9fd2d09dbad0Jesse Wilson
579984fcff696380abd6ea14e80030f9fd2d09dbad0Jesse Wilson    /**
580984fcff696380abd6ea14e80030f9fd2d09dbad0Jesse Wilson     * We were verifying the wrong hostname when connecting to an HTTPS site
581984fcff696380abd6ea14e80030f9fd2d09dbad0Jesse Wilson     * through a proxy. http://b/3097277
582984fcff696380abd6ea14e80030f9fd2d09dbad0Jesse Wilson     */
583984fcff696380abd6ea14e80030f9fd2d09dbad0Jesse Wilson    private void testConnectViaHttpProxyToHttps(ProxyConfig proxyConfig) throws Exception {
58460476787f0e0f052366d8031c74e507ffd3d16a3Jesse Wilson        TestSSLContext testSSLContext = TestSSLContext.create();
585984fcff696380abd6ea14e80030f9fd2d09dbad0Jesse Wilson        RecordingHostnameVerifier hostnameVerifier = new RecordingHostnameVerifier();
58660476787f0e0f052366d8031c74e507ffd3d16a3Jesse Wilson
587059dbc04218144f985b20a228bbe98139d400d0cBrian Carlstrom        server.useHttps(testSSLContext.serverContext.getSocketFactory(), true);
588c996149b500fc4825156106554457fe2394ae087Jesse Wilson        server.enqueue(new MockResponse()
589c996149b500fc4825156106554457fe2394ae087Jesse Wilson                .setSocketPolicy(SocketPolicy.UPGRADE_TO_SSL_AT_END)
590c996149b500fc4825156106554457fe2394ae087Jesse Wilson                .clearHeaders());
591c0372d90016d241ac979faa6fa1731f30b6f2a03Jesse Wilson        server.enqueue(new MockResponse().setBody("this response comes via a secure proxy"));
59251e468abf2628ce964d3657042f3ac8f2c947504Jesse Wilson        server.play();
59360476787f0e0f052366d8031c74e507ffd3d16a3Jesse Wilson
59460476787f0e0f052366d8031c74e507ffd3d16a3Jesse Wilson        URL url = new URL("https://android.com/foo");
595984fcff696380abd6ea14e80030f9fd2d09dbad0Jesse Wilson        HttpsURLConnection connection = (HttpsURLConnection) proxyConfig.connect(server, url);
596059dbc04218144f985b20a228bbe98139d400d0cBrian Carlstrom        connection.setSSLSocketFactory(testSSLContext.clientContext.getSocketFactory());
597984fcff696380abd6ea14e80030f9fd2d09dbad0Jesse Wilson        connection.setHostnameVerifier(hostnameVerifier);
59860476787f0e0f052366d8031c74e507ffd3d16a3Jesse Wilson
599c8977f474b30c5f3807398859a6b16687af6fc7bJesse Wilson        assertContent("this response comes via a secure proxy", connection);
60060476787f0e0f052366d8031c74e507ffd3d16a3Jesse Wilson
60151e468abf2628ce964d3657042f3ac8f2c947504Jesse Wilson        RecordedRequest connect = server.takeRequest();
60260476787f0e0f052366d8031c74e507ffd3d16a3Jesse Wilson        assertEquals("Connect line failure on proxy",
60360476787f0e0f052366d8031c74e507ffd3d16a3Jesse Wilson                "CONNECT android.com:443 HTTP/1.1", connect.getRequestLine());
60460476787f0e0f052366d8031c74e507ffd3d16a3Jesse Wilson        assertContains(connect.getHeaders(), "Host: android.com");
60560476787f0e0f052366d8031c74e507ffd3d16a3Jesse Wilson
60651e468abf2628ce964d3657042f3ac8f2c947504Jesse Wilson        RecordedRequest get = server.takeRequest();
60760476787f0e0f052366d8031c74e507ffd3d16a3Jesse Wilson        assertEquals("GET /foo HTTP/1.1", get.getRequestLine());
60860476787f0e0f052366d8031c74e507ffd3d16a3Jesse Wilson        assertContains(get.getHeaders(), "Host: android.com");
609984fcff696380abd6ea14e80030f9fd2d09dbad0Jesse Wilson        assertEquals(Arrays.asList("verify android.com"), hostnameVerifier.calls);
61060476787f0e0f052366d8031c74e507ffd3d16a3Jesse Wilson    }
61160476787f0e0f052366d8031c74e507ffd3d16a3Jesse Wilson
612d4bddd7d1fb7b1b7f0836648228235c6e4b56a18Jesse Wilson    /**
613d4bddd7d1fb7b1b7f0836648228235c6e4b56a18Jesse Wilson     * Test which headers are sent unencrypted to the HTTP proxy.
614d4bddd7d1fb7b1b7f0836648228235c6e4b56a18Jesse Wilson     */
615d4bddd7d1fb7b1b7f0836648228235c6e4b56a18Jesse Wilson    public void testProxyConnectIncludesProxyHeadersOnly()
616d4bddd7d1fb7b1b7f0836648228235c6e4b56a18Jesse Wilson            throws IOException, InterruptedException {
617984fcff696380abd6ea14e80030f9fd2d09dbad0Jesse Wilson        RecordingHostnameVerifier hostnameVerifier = new RecordingHostnameVerifier();
618d4bddd7d1fb7b1b7f0836648228235c6e4b56a18Jesse Wilson        TestSSLContext testSSLContext = TestSSLContext.create();
619d4bddd7d1fb7b1b7f0836648228235c6e4b56a18Jesse Wilson
620d4bddd7d1fb7b1b7f0836648228235c6e4b56a18Jesse Wilson        server.useHttps(testSSLContext.serverContext.getSocketFactory(), true);
621c996149b500fc4825156106554457fe2394ae087Jesse Wilson        server.enqueue(new MockResponse()
622c996149b500fc4825156106554457fe2394ae087Jesse Wilson                .setSocketPolicy(SocketPolicy.UPGRADE_TO_SSL_AT_END)
623c996149b500fc4825156106554457fe2394ae087Jesse Wilson                .clearHeaders());
624d4bddd7d1fb7b1b7f0836648228235c6e4b56a18Jesse Wilson        server.enqueue(new MockResponse().setBody("encrypted response from the origin server"));
625d4bddd7d1fb7b1b7f0836648228235c6e4b56a18Jesse Wilson        server.play();
626d4bddd7d1fb7b1b7f0836648228235c6e4b56a18Jesse Wilson
627d4bddd7d1fb7b1b7f0836648228235c6e4b56a18Jesse Wilson        URL url = new URL("https://android.com/foo");
628d4bddd7d1fb7b1b7f0836648228235c6e4b56a18Jesse Wilson        HttpsURLConnection connection = (HttpsURLConnection) url.openConnection(
629d4bddd7d1fb7b1b7f0836648228235c6e4b56a18Jesse Wilson                server.toProxyAddress());
630d4bddd7d1fb7b1b7f0836648228235c6e4b56a18Jesse Wilson        connection.addRequestProperty("Private", "Secret");
631d4bddd7d1fb7b1b7f0836648228235c6e4b56a18Jesse Wilson        connection.addRequestProperty("Proxy-Authorization", "bar");
632d4bddd7d1fb7b1b7f0836648228235c6e4b56a18Jesse Wilson        connection.addRequestProperty("User-Agent", "baz");
633d4bddd7d1fb7b1b7f0836648228235c6e4b56a18Jesse Wilson        connection.setSSLSocketFactory(testSSLContext.clientContext.getSocketFactory());
634984fcff696380abd6ea14e80030f9fd2d09dbad0Jesse Wilson        connection.setHostnameVerifier(hostnameVerifier);
635d4bddd7d1fb7b1b7f0836648228235c6e4b56a18Jesse Wilson        assertContent("encrypted response from the origin server", connection);
636d4bddd7d1fb7b1b7f0836648228235c6e4b56a18Jesse Wilson
637d4bddd7d1fb7b1b7f0836648228235c6e4b56a18Jesse Wilson        RecordedRequest connect = server.takeRequest();
638d4bddd7d1fb7b1b7f0836648228235c6e4b56a18Jesse Wilson        assertContainsNoneMatching(connect.getHeaders(), "Private.*");
639d4bddd7d1fb7b1b7f0836648228235c6e4b56a18Jesse Wilson        assertContains(connect.getHeaders(), "Proxy-Authorization: bar");
640d4bddd7d1fb7b1b7f0836648228235c6e4b56a18Jesse Wilson        assertContains(connect.getHeaders(), "User-Agent: baz");
641d4bddd7d1fb7b1b7f0836648228235c6e4b56a18Jesse Wilson        assertContains(connect.getHeaders(), "Host: android.com");
642d4bddd7d1fb7b1b7f0836648228235c6e4b56a18Jesse Wilson        assertContains(connect.getHeaders(), "Proxy-Connection: Keep-Alive");
643d4bddd7d1fb7b1b7f0836648228235c6e4b56a18Jesse Wilson
644d4bddd7d1fb7b1b7f0836648228235c6e4b56a18Jesse Wilson        RecordedRequest get = server.takeRequest();
645d4bddd7d1fb7b1b7f0836648228235c6e4b56a18Jesse Wilson        assertContains(get.getHeaders(), "Private: Secret");
646984fcff696380abd6ea14e80030f9fd2d09dbad0Jesse Wilson        assertEquals(Arrays.asList("verify android.com"), hostnameVerifier.calls);
647d4bddd7d1fb7b1b7f0836648228235c6e4b56a18Jesse Wilson    }
648d4bddd7d1fb7b1b7f0836648228235c6e4b56a18Jesse Wilson
649c996149b500fc4825156106554457fe2394ae087Jesse Wilson    public void testProxyAuthenticateOnConnect() throws Exception {
650c996149b500fc4825156106554457fe2394ae087Jesse Wilson        Authenticator.setDefault(SIMPLE_AUTHENTICATOR);
651c996149b500fc4825156106554457fe2394ae087Jesse Wilson        TestSSLContext testSSLContext = TestSSLContext.create();
652c996149b500fc4825156106554457fe2394ae087Jesse Wilson        server.useHttps(testSSLContext.serverContext.getSocketFactory(), true);
653c996149b500fc4825156106554457fe2394ae087Jesse Wilson        server.enqueue(new MockResponse()
654c996149b500fc4825156106554457fe2394ae087Jesse Wilson                .setResponseCode(407)
655c996149b500fc4825156106554457fe2394ae087Jesse Wilson                .addHeader("Proxy-Authenticate: Basic realm=\"localhost\""));
656c996149b500fc4825156106554457fe2394ae087Jesse Wilson        server.enqueue(new MockResponse()
657c996149b500fc4825156106554457fe2394ae087Jesse Wilson                .setSocketPolicy(SocketPolicy.UPGRADE_TO_SSL_AT_END)
658c996149b500fc4825156106554457fe2394ae087Jesse Wilson                .clearHeaders());
659c996149b500fc4825156106554457fe2394ae087Jesse Wilson        server.enqueue(new MockResponse().setBody("A"));
660c996149b500fc4825156106554457fe2394ae087Jesse Wilson        server.play();
661c996149b500fc4825156106554457fe2394ae087Jesse Wilson
662c996149b500fc4825156106554457fe2394ae087Jesse Wilson        URL url = new URL("https://android.com/foo");
663c996149b500fc4825156106554457fe2394ae087Jesse Wilson        HttpsURLConnection connection = (HttpsURLConnection) url.openConnection(
664c996149b500fc4825156106554457fe2394ae087Jesse Wilson                server.toProxyAddress());
665c996149b500fc4825156106554457fe2394ae087Jesse Wilson        connection.setSSLSocketFactory(testSSLContext.clientContext.getSocketFactory());
666c996149b500fc4825156106554457fe2394ae087Jesse Wilson        connection.setHostnameVerifier(new RecordingHostnameVerifier());
667c996149b500fc4825156106554457fe2394ae087Jesse Wilson        assertContent("A", connection);
668c996149b500fc4825156106554457fe2394ae087Jesse Wilson
669c996149b500fc4825156106554457fe2394ae087Jesse Wilson        RecordedRequest connect1 = server.takeRequest();
670c996149b500fc4825156106554457fe2394ae087Jesse Wilson        assertEquals("CONNECT android.com:443 HTTP/1.1", connect1.getRequestLine());
671c996149b500fc4825156106554457fe2394ae087Jesse Wilson        assertContainsNoneMatching(connect1.getHeaders(), "Proxy\\-Authorization.*");
672c996149b500fc4825156106554457fe2394ae087Jesse Wilson
673c996149b500fc4825156106554457fe2394ae087Jesse Wilson        RecordedRequest connect2 = server.takeRequest();
674c996149b500fc4825156106554457fe2394ae087Jesse Wilson        assertEquals("CONNECT android.com:443 HTTP/1.1", connect2.getRequestLine());
675c996149b500fc4825156106554457fe2394ae087Jesse Wilson        assertContains(connect2.getHeaders(), "Proxy-Authorization: Basic " + BASE_64_CREDENTIALS);
676c996149b500fc4825156106554457fe2394ae087Jesse Wilson
677c996149b500fc4825156106554457fe2394ae087Jesse Wilson        RecordedRequest get = server.takeRequest();
678c996149b500fc4825156106554457fe2394ae087Jesse Wilson        assertEquals("GET /foo HTTP/1.1", get.getRequestLine());
679c996149b500fc4825156106554457fe2394ae087Jesse Wilson        assertContainsNoneMatching(get.getHeaders(), "Proxy\\-Authorization.*");
680c996149b500fc4825156106554457fe2394ae087Jesse Wilson    }
681c996149b500fc4825156106554457fe2394ae087Jesse Wilson
682d4bddd7d1fb7b1b7f0836648228235c6e4b56a18Jesse Wilson    public void testDisconnectedConnection() throws IOException {
683d4bddd7d1fb7b1b7f0836648228235c6e4b56a18Jesse Wilson        server.enqueue(new MockResponse().setBody("ABCDEFGHIJKLMNOPQR"));
684d4bddd7d1fb7b1b7f0836648228235c6e4b56a18Jesse Wilson        server.play();
685d4bddd7d1fb7b1b7f0836648228235c6e4b56a18Jesse Wilson
686d4bddd7d1fb7b1b7f0836648228235c6e4b56a18Jesse Wilson        HttpURLConnection connection = (HttpURLConnection) server.getUrl("/").openConnection();
687d4bddd7d1fb7b1b7f0836648228235c6e4b56a18Jesse Wilson        InputStream in = connection.getInputStream();
688d4bddd7d1fb7b1b7f0836648228235c6e4b56a18Jesse Wilson        assertEquals('A', (char) in.read());
689d4bddd7d1fb7b1b7f0836648228235c6e4b56a18Jesse Wilson        connection.disconnect();
690d4bddd7d1fb7b1b7f0836648228235c6e4b56a18Jesse Wilson        try {
691d4bddd7d1fb7b1b7f0836648228235c6e4b56a18Jesse Wilson            in.read();
692d4bddd7d1fb7b1b7f0836648228235c6e4b56a18Jesse Wilson            fail("Expected a connection closed exception");
693d4bddd7d1fb7b1b7f0836648228235c6e4b56a18Jesse Wilson        } catch (IOException expected) {
694d4bddd7d1fb7b1b7f0836648228235c6e4b56a18Jesse Wilson        }
695d4bddd7d1fb7b1b7f0836648228235c6e4b56a18Jesse Wilson    }
696d4bddd7d1fb7b1b7f0836648228235c6e4b56a18Jesse Wilson
697d742d7fc7f0593eb8c6e4ac9dd4c0f6a80374e46Jesse Wilson    public void testDisconnectBeforeConnect() throws IOException {
698d742d7fc7f0593eb8c6e4ac9dd4c0f6a80374e46Jesse Wilson        server.enqueue(new MockResponse().setBody("A"));
699d742d7fc7f0593eb8c6e4ac9dd4c0f6a80374e46Jesse Wilson        server.play();
700d742d7fc7f0593eb8c6e4ac9dd4c0f6a80374e46Jesse Wilson
701d742d7fc7f0593eb8c6e4ac9dd4c0f6a80374e46Jesse Wilson        HttpURLConnection connection = (HttpURLConnection) server.getUrl("/").openConnection();
702d742d7fc7f0593eb8c6e4ac9dd4c0f6a80374e46Jesse Wilson        connection.disconnect();
703d742d7fc7f0593eb8c6e4ac9dd4c0f6a80374e46Jesse Wilson
704d742d7fc7f0593eb8c6e4ac9dd4c0f6a80374e46Jesse Wilson        assertContent("A", connection);
705d742d7fc7f0593eb8c6e4ac9dd4c0f6a80374e46Jesse Wilson        assertEquals(200, connection.getResponseCode());
706d742d7fc7f0593eb8c6e4ac9dd4c0f6a80374e46Jesse Wilson    }
707d742d7fc7f0593eb8c6e4ac9dd4c0f6a80374e46Jesse Wilson
708d742d7fc7f0593eb8c6e4ac9dd4c0f6a80374e46Jesse Wilson    public void testDefaultRequestProperty() throws Exception {
709d742d7fc7f0593eb8c6e4ac9dd4c0f6a80374e46Jesse Wilson        URLConnection.setDefaultRequestProperty("X-testSetDefaultRequestProperty", "A");
710d742d7fc7f0593eb8c6e4ac9dd4c0f6a80374e46Jesse Wilson        assertNull(URLConnection.getDefaultRequestProperty("X-setDefaultRequestProperty"));
711d742d7fc7f0593eb8c6e4ac9dd4c0f6a80374e46Jesse Wilson    }
712d742d7fc7f0593eb8c6e4ac9dd4c0f6a80374e46Jesse Wilson
71351e468abf2628ce964d3657042f3ac8f2c947504Jesse Wilson    /**
71451e468abf2628ce964d3657042f3ac8f2c947504Jesse Wilson     * Reads {@code count} characters from the stream. If the stream is
71551e468abf2628ce964d3657042f3ac8f2c947504Jesse Wilson     * exhausted before {@code count} characters can be read, the remaining
71651e468abf2628ce964d3657042f3ac8f2c947504Jesse Wilson     * characters are returned and the stream is closed.
71751e468abf2628ce964d3657042f3ac8f2c947504Jesse Wilson     */
71851e468abf2628ce964d3657042f3ac8f2c947504Jesse Wilson    private String readAscii(InputStream in, int count) throws IOException {
71951e468abf2628ce964d3657042f3ac8f2c947504Jesse Wilson        StringBuilder result = new StringBuilder();
72051e468abf2628ce964d3657042f3ac8f2c947504Jesse Wilson        for (int i = 0; i < count; i++) {
72151e468abf2628ce964d3657042f3ac8f2c947504Jesse Wilson            int value = in.read();
72251e468abf2628ce964d3657042f3ac8f2c947504Jesse Wilson            if (value == -1) {
72351e468abf2628ce964d3657042f3ac8f2c947504Jesse Wilson                in.close();
72451e468abf2628ce964d3657042f3ac8f2c947504Jesse Wilson                break;
72551e468abf2628ce964d3657042f3ac8f2c947504Jesse Wilson            }
72651e468abf2628ce964d3657042f3ac8f2c947504Jesse Wilson            result.append((char) value);
72751e468abf2628ce964d3657042f3ac8f2c947504Jesse Wilson        }
72851e468abf2628ce964d3657042f3ac8f2c947504Jesse Wilson        return result.toString();
72951e468abf2628ce964d3657042f3ac8f2c947504Jesse Wilson    }
73051e468abf2628ce964d3657042f3ac8f2c947504Jesse Wilson
73151e468abf2628ce964d3657042f3ac8f2c947504Jesse Wilson    public void testMarkAndResetWithContentLengthHeader() throws IOException {
73251e468abf2628ce964d3657042f3ac8f2c947504Jesse Wilson        testMarkAndReset(TransferKind.FIXED_LENGTH);
73351e468abf2628ce964d3657042f3ac8f2c947504Jesse Wilson    }
73451e468abf2628ce964d3657042f3ac8f2c947504Jesse Wilson
73551e468abf2628ce964d3657042f3ac8f2c947504Jesse Wilson    public void testMarkAndResetWithChunkedEncoding() throws IOException {
73651e468abf2628ce964d3657042f3ac8f2c947504Jesse Wilson        testMarkAndReset(TransferKind.CHUNKED);
73751e468abf2628ce964d3657042f3ac8f2c947504Jesse Wilson    }
73851e468abf2628ce964d3657042f3ac8f2c947504Jesse Wilson
73951e468abf2628ce964d3657042f3ac8f2c947504Jesse Wilson    public void testMarkAndResetWithNoLengthHeaders() throws IOException {
74051e468abf2628ce964d3657042f3ac8f2c947504Jesse Wilson        testMarkAndReset(TransferKind.END_OF_STREAM);
74151e468abf2628ce964d3657042f3ac8f2c947504Jesse Wilson    }
74251e468abf2628ce964d3657042f3ac8f2c947504Jesse Wilson
7430c2fd828abec671333b8b88281825fd27a783723Jesse Wilson    private void testMarkAndReset(TransferKind transferKind) throws IOException {
74451e468abf2628ce964d3657042f3ac8f2c947504Jesse Wilson        MockResponse response = new MockResponse();
74551e468abf2628ce964d3657042f3ac8f2c947504Jesse Wilson        transferKind.setBody(response, "ABCDEFGHIJKLMNOPQRSTUVWXYZ", 1024);
74651e468abf2628ce964d3657042f3ac8f2c947504Jesse Wilson        server.enqueue(response);
747953df613522e12a418cb7cb73248594d6c9f53d4Jesse Wilson        server.enqueue(response);
74851e468abf2628ce964d3657042f3ac8f2c947504Jesse Wilson        server.play();
74951e468abf2628ce964d3657042f3ac8f2c947504Jesse Wilson
75051e468abf2628ce964d3657042f3ac8f2c947504Jesse Wilson        InputStream in = server.getUrl("/").openConnection().getInputStream();
75151e468abf2628ce964d3657042f3ac8f2c947504Jesse Wilson        assertFalse("This implementation claims to support mark().", in.markSupported());
75251e468abf2628ce964d3657042f3ac8f2c947504Jesse Wilson        in.mark(5);
75351e468abf2628ce964d3657042f3ac8f2c947504Jesse Wilson        assertEquals("ABCDE", readAscii(in, 5));
75451e468abf2628ce964d3657042f3ac8f2c947504Jesse Wilson        try {
75551e468abf2628ce964d3657042f3ac8f2c947504Jesse Wilson            in.reset();
75651e468abf2628ce964d3657042f3ac8f2c947504Jesse Wilson            fail();
75751e468abf2628ce964d3657042f3ac8f2c947504Jesse Wilson        } catch (IOException expected) {
75851e468abf2628ce964d3657042f3ac8f2c947504Jesse Wilson        }
75951e468abf2628ce964d3657042f3ac8f2c947504Jesse Wilson        assertEquals("FGHIJKLMNOPQRSTUVWXYZ", readAscii(in, Integer.MAX_VALUE));
76051e468abf2628ce964d3657042f3ac8f2c947504Jesse Wilson        assertContent("ABCDEFGHIJKLMNOPQRSTUVWXYZ", server.getUrl("/").openConnection());
76151e468abf2628ce964d3657042f3ac8f2c947504Jesse Wilson    }
76251e468abf2628ce964d3657042f3ac8f2c947504Jesse Wilson
76351e468abf2628ce964d3657042f3ac8f2c947504Jesse Wilson    /**
76451e468abf2628ce964d3657042f3ac8f2c947504Jesse Wilson     * We've had a bug where we forget the HTTP response when we see response
76551e468abf2628ce964d3657042f3ac8f2c947504Jesse Wilson     * code 401. This causes a new HTTP request to be issued for every call into
76651e468abf2628ce964d3657042f3ac8f2c947504Jesse Wilson     * the URLConnection.
76751e468abf2628ce964d3657042f3ac8f2c947504Jesse Wilson     */
76851e468abf2628ce964d3657042f3ac8f2c947504Jesse Wilson    public void testUnauthorizedResponseHandling() throws IOException {
76951e468abf2628ce964d3657042f3ac8f2c947504Jesse Wilson        MockResponse response = new MockResponse()
77051e468abf2628ce964d3657042f3ac8f2c947504Jesse Wilson                .addHeader("WWW-Authenticate: challenge")
77151e468abf2628ce964d3657042f3ac8f2c947504Jesse Wilson                .setResponseCode(401) // UNAUTHORIZED
77251e468abf2628ce964d3657042f3ac8f2c947504Jesse Wilson                .setBody("Unauthorized");
77351e468abf2628ce964d3657042f3ac8f2c947504Jesse Wilson        server.enqueue(response);
77451e468abf2628ce964d3657042f3ac8f2c947504Jesse Wilson        server.enqueue(response);
77551e468abf2628ce964d3657042f3ac8f2c947504Jesse Wilson        server.enqueue(response);
77651e468abf2628ce964d3657042f3ac8f2c947504Jesse Wilson        server.play();
77751e468abf2628ce964d3657042f3ac8f2c947504Jesse Wilson
77851e468abf2628ce964d3657042f3ac8f2c947504Jesse Wilson        URL url = server.getUrl("/");
77951e468abf2628ce964d3657042f3ac8f2c947504Jesse Wilson        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
78051e468abf2628ce964d3657042f3ac8f2c947504Jesse Wilson
78151e468abf2628ce964d3657042f3ac8f2c947504Jesse Wilson        assertEquals(401, conn.getResponseCode());
78251e468abf2628ce964d3657042f3ac8f2c947504Jesse Wilson        assertEquals(401, conn.getResponseCode());
78351e468abf2628ce964d3657042f3ac8f2c947504Jesse Wilson        assertEquals(401, conn.getResponseCode());
78451e468abf2628ce964d3657042f3ac8f2c947504Jesse Wilson        assertEquals(1, server.getRequestCount());
78551e468abf2628ce964d3657042f3ac8f2c947504Jesse Wilson    }
78651e468abf2628ce964d3657042f3ac8f2c947504Jesse Wilson
7876906b0c12dcf3216883d0373973a252812a20d32Jesse Wilson    public void testNonHexChunkSize() throws IOException {
7886906b0c12dcf3216883d0373973a252812a20d32Jesse Wilson        server.enqueue(new MockResponse()
7896906b0c12dcf3216883d0373973a252812a20d32Jesse Wilson                .setBody("5\r\nABCDE\r\nG\r\nFGHIJKLMNOPQRSTU\r\n0\r\n\r\n")
7906906b0c12dcf3216883d0373973a252812a20d32Jesse Wilson                .clearHeaders()
7916906b0c12dcf3216883d0373973a252812a20d32Jesse Wilson                .addHeader("Transfer-encoding: chunked"));
7926906b0c12dcf3216883d0373973a252812a20d32Jesse Wilson        server.play();
7936906b0c12dcf3216883d0373973a252812a20d32Jesse Wilson
7946906b0c12dcf3216883d0373973a252812a20d32Jesse Wilson        URLConnection connection = server.getUrl("/").openConnection();
7956906b0c12dcf3216883d0373973a252812a20d32Jesse Wilson        try {
7966906b0c12dcf3216883d0373973a252812a20d32Jesse Wilson            readAscii(connection.getInputStream(), Integer.MAX_VALUE);
7976906b0c12dcf3216883d0373973a252812a20d32Jesse Wilson            fail();
7986906b0c12dcf3216883d0373973a252812a20d32Jesse Wilson        } catch (IOException e) {
7996906b0c12dcf3216883d0373973a252812a20d32Jesse Wilson        }
8006906b0c12dcf3216883d0373973a252812a20d32Jesse Wilson    }
8016906b0c12dcf3216883d0373973a252812a20d32Jesse Wilson
8026906b0c12dcf3216883d0373973a252812a20d32Jesse Wilson    public void testMissingChunkBody() throws IOException {
8036906b0c12dcf3216883d0373973a252812a20d32Jesse Wilson        server.enqueue(new MockResponse()
8046906b0c12dcf3216883d0373973a252812a20d32Jesse Wilson                .setBody("5")
8056906b0c12dcf3216883d0373973a252812a20d32Jesse Wilson                .clearHeaders()
8066906b0c12dcf3216883d0373973a252812a20d32Jesse Wilson                .addHeader("Transfer-encoding: chunked")
807e942f46f10bb9384a1b186b3d7b74f9704c57090Jesse Wilson                .setSocketPolicy(DISCONNECT_AT_END));
8086906b0c12dcf3216883d0373973a252812a20d32Jesse Wilson        server.play();
8096906b0c12dcf3216883d0373973a252812a20d32Jesse Wilson
8106906b0c12dcf3216883d0373973a252812a20d32Jesse Wilson        URLConnection connection = server.getUrl("/").openConnection();
8116906b0c12dcf3216883d0373973a252812a20d32Jesse Wilson        try {
8126906b0c12dcf3216883d0373973a252812a20d32Jesse Wilson            readAscii(connection.getInputStream(), Integer.MAX_VALUE);
8136906b0c12dcf3216883d0373973a252812a20d32Jesse Wilson            fail();
8146906b0c12dcf3216883d0373973a252812a20d32Jesse Wilson        } catch (IOException e) {
8156906b0c12dcf3216883d0373973a252812a20d32Jesse Wilson        }
8166906b0c12dcf3216883d0373973a252812a20d32Jesse Wilson    }
8176906b0c12dcf3216883d0373973a252812a20d32Jesse Wilson
81850ae32218918eae80298bd1ab8e4f588bbbabdb2Jesse Wilson    /**
81950ae32218918eae80298bd1ab8e4f588bbbabdb2Jesse Wilson     * This test checks whether connections are gzipped by default. This
82050ae32218918eae80298bd1ab8e4f588bbbabdb2Jesse Wilson     * behavior in not required by the API, so a failure of this test does not
82150ae32218918eae80298bd1ab8e4f588bbbabdb2Jesse Wilson     * imply a bug in the implementation.
82250ae32218918eae80298bd1ab8e4f588bbbabdb2Jesse Wilson     */
82350ae32218918eae80298bd1ab8e4f588bbbabdb2Jesse Wilson    public void testGzipEncodingEnabledByDefault() throws IOException, InterruptedException {
82450ae32218918eae80298bd1ab8e4f588bbbabdb2Jesse Wilson        server.enqueue(new MockResponse()
82550ae32218918eae80298bd1ab8e4f588bbbabdb2Jesse Wilson                .setBody(gzip("ABCABCABC".getBytes("UTF-8")))
82650ae32218918eae80298bd1ab8e4f588bbbabdb2Jesse Wilson                .addHeader("Content-Encoding: gzip"));
82750ae32218918eae80298bd1ab8e4f588bbbabdb2Jesse Wilson        server.play();
82850ae32218918eae80298bd1ab8e4f588bbbabdb2Jesse Wilson
82950ae32218918eae80298bd1ab8e4f588bbbabdb2Jesse Wilson        URLConnection connection = server.getUrl("/").openConnection();
83050ae32218918eae80298bd1ab8e4f588bbbabdb2Jesse Wilson        assertEquals("ABCABCABC", readAscii(connection.getInputStream(), Integer.MAX_VALUE));
8318116f7e97e00d223e7fbe5c950c9a5e3277de124Jesse Wilson        assertNull(connection.getContentEncoding());
83250ae32218918eae80298bd1ab8e4f588bbbabdb2Jesse Wilson
83350ae32218918eae80298bd1ab8e4f588bbbabdb2Jesse Wilson        RecordedRequest request = server.takeRequest();
83450ae32218918eae80298bd1ab8e4f588bbbabdb2Jesse Wilson        assertContains(request.getHeaders(), "Accept-Encoding: gzip");
83550ae32218918eae80298bd1ab8e4f588bbbabdb2Jesse Wilson    }
83650ae32218918eae80298bd1ab8e4f588bbbabdb2Jesse Wilson
837deb236fb06f2a14861e7d40dea959f181cd5cf28Jesse Wilson    public void testClientConfiguredGzipContentEncoding() throws Exception {
838deb236fb06f2a14861e7d40dea959f181cd5cf28Jesse Wilson        server.enqueue(new MockResponse()
839deb236fb06f2a14861e7d40dea959f181cd5cf28Jesse Wilson                .setBody(gzip("ABCDEFGHIJKLMNOPQRSTUVWXYZ".getBytes("UTF-8")))
840deb236fb06f2a14861e7d40dea959f181cd5cf28Jesse Wilson                .addHeader("Content-Encoding: gzip"));
841deb236fb06f2a14861e7d40dea959f181cd5cf28Jesse Wilson        server.play();
842deb236fb06f2a14861e7d40dea959f181cd5cf28Jesse Wilson
843deb236fb06f2a14861e7d40dea959f181cd5cf28Jesse Wilson        URLConnection connection = server.getUrl("/").openConnection();
844deb236fb06f2a14861e7d40dea959f181cd5cf28Jesse Wilson        connection.addRequestProperty("Accept-Encoding", "gzip");
845deb236fb06f2a14861e7d40dea959f181cd5cf28Jesse Wilson        InputStream gunzippedIn = new GZIPInputStream(connection.getInputStream());
846deb236fb06f2a14861e7d40dea959f181cd5cf28Jesse Wilson        assertEquals("ABCDEFGHIJKLMNOPQRSTUVWXYZ", readAscii(gunzippedIn, Integer.MAX_VALUE));
847deb236fb06f2a14861e7d40dea959f181cd5cf28Jesse Wilson
848deb236fb06f2a14861e7d40dea959f181cd5cf28Jesse Wilson        RecordedRequest request = server.takeRequest();
849deb236fb06f2a14861e7d40dea959f181cd5cf28Jesse Wilson        assertContains(request.getHeaders(), "Accept-Encoding: gzip");
850deb236fb06f2a14861e7d40dea959f181cd5cf28Jesse Wilson    }
851deb236fb06f2a14861e7d40dea959f181cd5cf28Jesse Wilson
852deb236fb06f2a14861e7d40dea959f181cd5cf28Jesse Wilson    public void testGzipAndConnectionReuseWithFixedLength() throws Exception {
853deb236fb06f2a14861e7d40dea959f181cd5cf28Jesse Wilson        testClientConfiguredGzipContentEncodingAndConnectionReuse(TransferKind.FIXED_LENGTH);
854deb236fb06f2a14861e7d40dea959f181cd5cf28Jesse Wilson    }
855deb236fb06f2a14861e7d40dea959f181cd5cf28Jesse Wilson
856deb236fb06f2a14861e7d40dea959f181cd5cf28Jesse Wilson    public void testGzipAndConnectionReuseWithChunkedEncoding() throws Exception {
857deb236fb06f2a14861e7d40dea959f181cd5cf28Jesse Wilson        testClientConfiguredGzipContentEncodingAndConnectionReuse(TransferKind.CHUNKED);
858deb236fb06f2a14861e7d40dea959f181cd5cf28Jesse Wilson    }
859deb236fb06f2a14861e7d40dea959f181cd5cf28Jesse Wilson
86050ae32218918eae80298bd1ab8e4f588bbbabdb2Jesse Wilson    public void testClientConfiguredCustomContentEncoding() throws Exception {
86150ae32218918eae80298bd1ab8e4f588bbbabdb2Jesse Wilson        server.enqueue(new MockResponse()
86250ae32218918eae80298bd1ab8e4f588bbbabdb2Jesse Wilson                .setBody("ABCDE")
86350ae32218918eae80298bd1ab8e4f588bbbabdb2Jesse Wilson                .addHeader("Content-Encoding: custom"));
86450ae32218918eae80298bd1ab8e4f588bbbabdb2Jesse Wilson        server.play();
86550ae32218918eae80298bd1ab8e4f588bbbabdb2Jesse Wilson
86650ae32218918eae80298bd1ab8e4f588bbbabdb2Jesse Wilson        URLConnection connection = server.getUrl("/").openConnection();
86750ae32218918eae80298bd1ab8e4f588bbbabdb2Jesse Wilson        connection.addRequestProperty("Accept-Encoding", "custom");
86850ae32218918eae80298bd1ab8e4f588bbbabdb2Jesse Wilson        assertEquals("ABCDE", readAscii(connection.getInputStream(), Integer.MAX_VALUE));
86950ae32218918eae80298bd1ab8e4f588bbbabdb2Jesse Wilson
87050ae32218918eae80298bd1ab8e4f588bbbabdb2Jesse Wilson        RecordedRequest request = server.takeRequest();
87150ae32218918eae80298bd1ab8e4f588bbbabdb2Jesse Wilson        assertContains(request.getHeaders(), "Accept-Encoding: custom");
87250ae32218918eae80298bd1ab8e4f588bbbabdb2Jesse Wilson    }
87350ae32218918eae80298bd1ab8e4f588bbbabdb2Jesse Wilson
874deb236fb06f2a14861e7d40dea959f181cd5cf28Jesse Wilson    /**
875deb236fb06f2a14861e7d40dea959f181cd5cf28Jesse Wilson     * Test a bug where gzip input streams weren't exhausting the input stream,
876deb236fb06f2a14861e7d40dea959f181cd5cf28Jesse Wilson     * which corrupted the request that followed.
877deb236fb06f2a14861e7d40dea959f181cd5cf28Jesse Wilson     * http://code.google.com/p/android/issues/detail?id=7059
878deb236fb06f2a14861e7d40dea959f181cd5cf28Jesse Wilson     */
879deb236fb06f2a14861e7d40dea959f181cd5cf28Jesse Wilson    private void testClientConfiguredGzipContentEncodingAndConnectionReuse(
880deb236fb06f2a14861e7d40dea959f181cd5cf28Jesse Wilson            TransferKind transferKind) throws Exception {
881deb236fb06f2a14861e7d40dea959f181cd5cf28Jesse Wilson        MockResponse responseOne = new MockResponse();
882deb236fb06f2a14861e7d40dea959f181cd5cf28Jesse Wilson        responseOne.addHeader("Content-Encoding: gzip");
883deb236fb06f2a14861e7d40dea959f181cd5cf28Jesse Wilson        transferKind.setBody(responseOne, gzip("one (gzipped)".getBytes("UTF-8")), 5);
884deb236fb06f2a14861e7d40dea959f181cd5cf28Jesse Wilson        server.enqueue(responseOne);
885deb236fb06f2a14861e7d40dea959f181cd5cf28Jesse Wilson        MockResponse responseTwo = new MockResponse();
886deb236fb06f2a14861e7d40dea959f181cd5cf28Jesse Wilson        transferKind.setBody(responseTwo, "two (identity)", 5);
887deb236fb06f2a14861e7d40dea959f181cd5cf28Jesse Wilson        server.enqueue(responseTwo);
888deb236fb06f2a14861e7d40dea959f181cd5cf28Jesse Wilson        server.play();
889deb236fb06f2a14861e7d40dea959f181cd5cf28Jesse Wilson
890deb236fb06f2a14861e7d40dea959f181cd5cf28Jesse Wilson        URLConnection connection = server.getUrl("/").openConnection();
891deb236fb06f2a14861e7d40dea959f181cd5cf28Jesse Wilson        connection.addRequestProperty("Accept-Encoding", "gzip");
892deb236fb06f2a14861e7d40dea959f181cd5cf28Jesse Wilson        InputStream gunzippedIn = new GZIPInputStream(connection.getInputStream());
893deb236fb06f2a14861e7d40dea959f181cd5cf28Jesse Wilson        assertEquals("one (gzipped)", readAscii(gunzippedIn, Integer.MAX_VALUE));
894deb236fb06f2a14861e7d40dea959f181cd5cf28Jesse Wilson        assertEquals(0, server.takeRequest().getSequenceNumber());
895deb236fb06f2a14861e7d40dea959f181cd5cf28Jesse Wilson
896deb236fb06f2a14861e7d40dea959f181cd5cf28Jesse Wilson        connection = server.getUrl("/").openConnection();
897deb236fb06f2a14861e7d40dea959f181cd5cf28Jesse Wilson        assertEquals("two (identity)", readAscii(connection.getInputStream(), Integer.MAX_VALUE));
898deb236fb06f2a14861e7d40dea959f181cd5cf28Jesse Wilson        assertEquals(1, server.takeRequest().getSequenceNumber());
899deb236fb06f2a14861e7d40dea959f181cd5cf28Jesse Wilson    }
900deb236fb06f2a14861e7d40dea959f181cd5cf28Jesse Wilson
901deb236fb06f2a14861e7d40dea959f181cd5cf28Jesse Wilson    /**
902ffd579b668428272b78f5c6c64f9c89766f37c1aJesse Wilson     * Obnoxiously test that the chunk sizes transmitted exactly equal the
903ffd579b668428272b78f5c6c64f9c89766f37c1aJesse Wilson     * requested data+chunk header size. Although setChunkedStreamingMode()
904ffd579b668428272b78f5c6c64f9c89766f37c1aJesse Wilson     * isn't specific about whether the size applies to the data or the
905ffd579b668428272b78f5c6c64f9c89766f37c1aJesse Wilson     * complete chunk, the RI interprets it as a complete chunk.
906ffd579b668428272b78f5c6c64f9c89766f37c1aJesse Wilson     */
907ffd579b668428272b78f5c6c64f9c89766f37c1aJesse Wilson    public void testSetChunkedStreamingMode() throws IOException, InterruptedException {
908ffd579b668428272b78f5c6c64f9c89766f37c1aJesse Wilson        server.enqueue(new MockResponse());
909ffd579b668428272b78f5c6c64f9c89766f37c1aJesse Wilson        server.play();
910ffd579b668428272b78f5c6c64f9c89766f37c1aJesse Wilson
911ffd579b668428272b78f5c6c64f9c89766f37c1aJesse Wilson        HttpURLConnection urlConnection = (HttpURLConnection) server.getUrl("/").openConnection();
912ffd579b668428272b78f5c6c64f9c89766f37c1aJesse Wilson        urlConnection.setChunkedStreamingMode(8);
913ffd579b668428272b78f5c6c64f9c89766f37c1aJesse Wilson        urlConnection.setDoOutput(true);
914ffd579b668428272b78f5c6c64f9c89766f37c1aJesse Wilson        OutputStream outputStream = urlConnection.getOutputStream();
915ffd579b668428272b78f5c6c64f9c89766f37c1aJesse Wilson        outputStream.write("ABCDEFGHIJKLMNOPQ".getBytes("US-ASCII"));
916ffd579b668428272b78f5c6c64f9c89766f37c1aJesse Wilson        assertEquals(200, urlConnection.getResponseCode());
917ffd579b668428272b78f5c6c64f9c89766f37c1aJesse Wilson
918ffd579b668428272b78f5c6c64f9c89766f37c1aJesse Wilson        RecordedRequest request = server.takeRequest();
919ffd579b668428272b78f5c6c64f9c89766f37c1aJesse Wilson        assertEquals("ABCDEFGHIJKLMNOPQ", new String(request.getBody(), "US-ASCII"));
920ffd579b668428272b78f5c6c64f9c89766f37c1aJesse Wilson        assertEquals(Arrays.asList(3, 3, 3, 3, 3, 2), request.getChunkSizes());
921ffd579b668428272b78f5c6c64f9c89766f37c1aJesse Wilson    }
922ffd579b668428272b78f5c6c64f9c89766f37c1aJesse Wilson
923ffd579b668428272b78f5c6c64f9c89766f37c1aJesse Wilson    public void testAuthenticateWithFixedLengthStreaming() throws Exception {
924ffd579b668428272b78f5c6c64f9c89766f37c1aJesse Wilson        testAuthenticateWithStreamingPost(StreamingMode.FIXED_LENGTH);
925ffd579b668428272b78f5c6c64f9c89766f37c1aJesse Wilson    }
926ffd579b668428272b78f5c6c64f9c89766f37c1aJesse Wilson
927ffd579b668428272b78f5c6c64f9c89766f37c1aJesse Wilson    public void testAuthenticateWithChunkedStreaming() throws Exception {
928ffd579b668428272b78f5c6c64f9c89766f37c1aJesse Wilson        testAuthenticateWithStreamingPost(StreamingMode.CHUNKED);
929ffd579b668428272b78f5c6c64f9c89766f37c1aJesse Wilson    }
930ffd579b668428272b78f5c6c64f9c89766f37c1aJesse Wilson
931ffd579b668428272b78f5c6c64f9c89766f37c1aJesse Wilson    private void testAuthenticateWithStreamingPost(StreamingMode streamingMode) throws Exception {
932ffd579b668428272b78f5c6c64f9c89766f37c1aJesse Wilson        MockResponse pleaseAuthenticate = new MockResponse()
933ffd579b668428272b78f5c6c64f9c89766f37c1aJesse Wilson                .setResponseCode(401)
934ffd579b668428272b78f5c6c64f9c89766f37c1aJesse Wilson                .addHeader("WWW-Authenticate: Basic realm=\"protected area\"")
935ffd579b668428272b78f5c6c64f9c89766f37c1aJesse Wilson                .setBody("Please authenticate.");
936ffd579b668428272b78f5c6c64f9c89766f37c1aJesse Wilson        server.enqueue(pleaseAuthenticate);
937ffd579b668428272b78f5c6c64f9c89766f37c1aJesse Wilson        server.play();
938ffd579b668428272b78f5c6c64f9c89766f37c1aJesse Wilson
939ffd579b668428272b78f5c6c64f9c89766f37c1aJesse Wilson        Authenticator.setDefault(SIMPLE_AUTHENTICATOR);
940ffd579b668428272b78f5c6c64f9c89766f37c1aJesse Wilson        HttpURLConnection connection = (HttpURLConnection) server.getUrl("/").openConnection();
941ffd579b668428272b78f5c6c64f9c89766f37c1aJesse Wilson        connection.setDoOutput(true);
942ffd579b668428272b78f5c6c64f9c89766f37c1aJesse Wilson        byte[] requestBody = { 'A', 'B', 'C', 'D' };
943ffd579b668428272b78f5c6c64f9c89766f37c1aJesse Wilson        if (streamingMode == StreamingMode.FIXED_LENGTH) {
944ffd579b668428272b78f5c6c64f9c89766f37c1aJesse Wilson            connection.setFixedLengthStreamingMode(requestBody.length);
945ffd579b668428272b78f5c6c64f9c89766f37c1aJesse Wilson        } else if (streamingMode == StreamingMode.CHUNKED) {
946ffd579b668428272b78f5c6c64f9c89766f37c1aJesse Wilson            connection.setChunkedStreamingMode(0);
947ffd579b668428272b78f5c6c64f9c89766f37c1aJesse Wilson        }
948ffd579b668428272b78f5c6c64f9c89766f37c1aJesse Wilson        OutputStream outputStream = connection.getOutputStream();
949ffd579b668428272b78f5c6c64f9c89766f37c1aJesse Wilson        outputStream.write(requestBody);
950ffd579b668428272b78f5c6c64f9c89766f37c1aJesse Wilson        outputStream.close();
951ffd579b668428272b78f5c6c64f9c89766f37c1aJesse Wilson        try {
952ffd579b668428272b78f5c6c64f9c89766f37c1aJesse Wilson            connection.getInputStream();
953ffd579b668428272b78f5c6c64f9c89766f37c1aJesse Wilson            fail();
954ffd579b668428272b78f5c6c64f9c89766f37c1aJesse Wilson        } catch (HttpRetryException expected) {
955ffd579b668428272b78f5c6c64f9c89766f37c1aJesse Wilson        }
956ffd579b668428272b78f5c6c64f9c89766f37c1aJesse Wilson
957ffd579b668428272b78f5c6c64f9c89766f37c1aJesse Wilson        // no authorization header for the request...
958ffd579b668428272b78f5c6c64f9c89766f37c1aJesse Wilson        RecordedRequest request = server.takeRequest();
959ffd579b668428272b78f5c6c64f9c89766f37c1aJesse Wilson        assertContainsNoneMatching(request.getHeaders(), "Authorization: Basic .*");
960ffd579b668428272b78f5c6c64f9c89766f37c1aJesse Wilson        assertEquals(Arrays.toString(requestBody), Arrays.toString(request.getBody()));
961ffd579b668428272b78f5c6c64f9c89766f37c1aJesse Wilson    }
962ffd579b668428272b78f5c6c64f9c89766f37c1aJesse Wilson
963ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson    public void testSetValidRequestMethod() throws Exception {
964ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson        server.play();
965ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson        assertValidRequestMethod("GET");
966ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson        assertValidRequestMethod("DELETE");
967ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson        assertValidRequestMethod("HEAD");
968ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson        assertValidRequestMethod("OPTIONS");
969ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson        assertValidRequestMethod("POST");
970ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson        assertValidRequestMethod("PUT");
971ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson        assertValidRequestMethod("TRACE");
972ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson    }
973ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson
974ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson    private void assertValidRequestMethod(String requestMethod) throws Exception {
975ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson        HttpURLConnection connection = (HttpURLConnection) server.getUrl("/").openConnection();
976ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson        connection.setRequestMethod(requestMethod);
977ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson        assertEquals(requestMethod, connection.getRequestMethod());
978ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson    }
979ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson
980ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson    public void testSetInvalidRequestMethodLowercase() throws Exception {
981ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson        server.play();
982ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson        assertInvalidRequestMethod("get");
983ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson    }
984ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson
985ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson    public void testSetInvalidRequestMethodConnect() throws Exception {
986ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson        server.play();
987ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson        assertInvalidRequestMethod("CONNECT");
988ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson    }
989ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson
990ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson    private void assertInvalidRequestMethod(String requestMethod) throws Exception {
991ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson        HttpURLConnection connection = (HttpURLConnection) server.getUrl("/").openConnection();
992ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson        try {
993ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson            connection.setRequestMethod(requestMethod);
994ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson            fail();
995ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson        } catch (ProtocolException expected) {
996ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson        }
997ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson    }
998ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson
999ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson    public void testCannotSetNegativeFixedLengthStreamingMode() throws Exception {
1000ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson        server.play();
1001ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson        HttpURLConnection connection = (HttpURLConnection) server.getUrl("/").openConnection();
1002ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson        try {
1003ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson            connection.setFixedLengthStreamingMode(-2);
1004ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson            fail();
1005ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson        } catch (IllegalArgumentException expected) {
1006ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson        }
1007ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson    }
1008ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson
1009ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson    public void testCanSetNegativeChunkedStreamingMode() throws Exception {
1010ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson        server.play();
1011ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson        HttpURLConnection connection = (HttpURLConnection) server.getUrl("/").openConnection();
1012ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson        connection.setChunkedStreamingMode(-2);
1013ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson    }
1014ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson
1015ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson    public void testCannotSetFixedLengthStreamingModeAfterConnect() throws Exception {
1016ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson        server.enqueue(new MockResponse().setBody("A"));
1017ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson        server.play();
1018ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson        HttpURLConnection connection = (HttpURLConnection) server.getUrl("/").openConnection();
1019ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson        assertEquals("A", readAscii(connection.getInputStream(), Integer.MAX_VALUE));
1020ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson        try {
1021ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson            connection.setFixedLengthStreamingMode(1);
1022ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson            fail();
1023ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson        } catch (IllegalStateException expected) {
1024ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson        }
1025ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson    }
1026ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson
1027ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson    public void testCannotSetChunkedStreamingModeAfterConnect() throws Exception {
1028ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson        server.enqueue(new MockResponse().setBody("A"));
1029ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson        server.play();
1030ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson        HttpURLConnection connection = (HttpURLConnection) server.getUrl("/").openConnection();
1031ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson        assertEquals("A", readAscii(connection.getInputStream(), Integer.MAX_VALUE));
1032ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson        try {
1033ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson            connection.setChunkedStreamingMode(1);
1034ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson            fail();
1035ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson        } catch (IllegalStateException expected) {
1036ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson        }
1037ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson    }
1038ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson
1039ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson    public void testCannotSetFixedLengthStreamingModeAfterChunkedStreamingMode() throws Exception {
1040ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson        server.play();
1041ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson        HttpURLConnection connection = (HttpURLConnection) server.getUrl("/").openConnection();
1042ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson        connection.setChunkedStreamingMode(1);
1043ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson        try {
1044ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson            connection.setFixedLengthStreamingMode(1);
1045ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson            fail();
1046ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson        } catch (IllegalStateException expected) {
1047ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson        }
1048ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson    }
1049ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson
1050ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson    public void testCannotSetChunkedStreamingModeAfterFixedLengthStreamingMode() throws Exception {
1051ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson        server.play();
1052ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson        HttpURLConnection connection = (HttpURLConnection) server.getUrl("/").openConnection();
1053ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson        connection.setFixedLengthStreamingMode(1);
1054ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson        try {
1055ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson            connection.setChunkedStreamingMode(1);
1056ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson            fail();
1057ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson        } catch (IllegalStateException expected) {
1058ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson        }
1059ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson    }
1060ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson
106135eef71e8ce721c4199c525890ecc1a263054596Jesse Wilson    public void testSecureFixedLengthStreaming() throws Exception {
106235eef71e8ce721c4199c525890ecc1a263054596Jesse Wilson        testSecureStreamingPost(StreamingMode.FIXED_LENGTH);
106335eef71e8ce721c4199c525890ecc1a263054596Jesse Wilson    }
106435eef71e8ce721c4199c525890ecc1a263054596Jesse Wilson
106535eef71e8ce721c4199c525890ecc1a263054596Jesse Wilson    public void testSecureChunkedStreaming() throws Exception {
106635eef71e8ce721c4199c525890ecc1a263054596Jesse Wilson        testSecureStreamingPost(StreamingMode.CHUNKED);
106735eef71e8ce721c4199c525890ecc1a263054596Jesse Wilson    }
106835eef71e8ce721c4199c525890ecc1a263054596Jesse Wilson
106935eef71e8ce721c4199c525890ecc1a263054596Jesse Wilson    /**
107035eef71e8ce721c4199c525890ecc1a263054596Jesse Wilson     * Users have reported problems using HTTPS with streaming request bodies.
107135eef71e8ce721c4199c525890ecc1a263054596Jesse Wilson     * http://code.google.com/p/android/issues/detail?id=12860
107235eef71e8ce721c4199c525890ecc1a263054596Jesse Wilson     */
107335eef71e8ce721c4199c525890ecc1a263054596Jesse Wilson    private void testSecureStreamingPost(StreamingMode streamingMode) throws Exception {
107435eef71e8ce721c4199c525890ecc1a263054596Jesse Wilson        TestSSLContext testSSLContext = TestSSLContext.create();
107535eef71e8ce721c4199c525890ecc1a263054596Jesse Wilson        server.useHttps(testSSLContext.serverContext.getSocketFactory(), false);
107635eef71e8ce721c4199c525890ecc1a263054596Jesse Wilson        server.enqueue(new MockResponse().setBody("Success!"));
107735eef71e8ce721c4199c525890ecc1a263054596Jesse Wilson        server.play();
107835eef71e8ce721c4199c525890ecc1a263054596Jesse Wilson
107935eef71e8ce721c4199c525890ecc1a263054596Jesse Wilson        HttpsURLConnection connection = (HttpsURLConnection) server.getUrl("/").openConnection();
108035eef71e8ce721c4199c525890ecc1a263054596Jesse Wilson        connection.setSSLSocketFactory(testSSLContext.clientContext.getSocketFactory());
108135eef71e8ce721c4199c525890ecc1a263054596Jesse Wilson        connection.setDoOutput(true);
108235eef71e8ce721c4199c525890ecc1a263054596Jesse Wilson        byte[] requestBody = { 'A', 'B', 'C', 'D' };
108335eef71e8ce721c4199c525890ecc1a263054596Jesse Wilson        if (streamingMode == StreamingMode.FIXED_LENGTH) {
108435eef71e8ce721c4199c525890ecc1a263054596Jesse Wilson            connection.setFixedLengthStreamingMode(requestBody.length);
108535eef71e8ce721c4199c525890ecc1a263054596Jesse Wilson        } else if (streamingMode == StreamingMode.CHUNKED) {
108635eef71e8ce721c4199c525890ecc1a263054596Jesse Wilson            connection.setChunkedStreamingMode(0);
108735eef71e8ce721c4199c525890ecc1a263054596Jesse Wilson        }
108835eef71e8ce721c4199c525890ecc1a263054596Jesse Wilson        OutputStream outputStream = connection.getOutputStream();
108935eef71e8ce721c4199c525890ecc1a263054596Jesse Wilson        outputStream.write(requestBody);
109035eef71e8ce721c4199c525890ecc1a263054596Jesse Wilson        outputStream.close();
109135eef71e8ce721c4199c525890ecc1a263054596Jesse Wilson        assertEquals("Success!", readAscii(connection.getInputStream(), Integer.MAX_VALUE));
109235eef71e8ce721c4199c525890ecc1a263054596Jesse Wilson
109335eef71e8ce721c4199c525890ecc1a263054596Jesse Wilson        RecordedRequest request = server.takeRequest();
109435eef71e8ce721c4199c525890ecc1a263054596Jesse Wilson        assertEquals("POST / HTTP/1.1", request.getRequestLine());
109535eef71e8ce721c4199c525890ecc1a263054596Jesse Wilson        if (streamingMode == StreamingMode.FIXED_LENGTH) {
109635eef71e8ce721c4199c525890ecc1a263054596Jesse Wilson            assertEquals(Collections.<Integer>emptyList(), request.getChunkSizes());
109735eef71e8ce721c4199c525890ecc1a263054596Jesse Wilson        } else if (streamingMode == StreamingMode.CHUNKED) {
109835eef71e8ce721c4199c525890ecc1a263054596Jesse Wilson            assertEquals(Arrays.asList(4), request.getChunkSizes());
109935eef71e8ce721c4199c525890ecc1a263054596Jesse Wilson        }
110035eef71e8ce721c4199c525890ecc1a263054596Jesse Wilson        assertEquals(Arrays.toString(requestBody), Arrays.toString(request.getBody()));
110135eef71e8ce721c4199c525890ecc1a263054596Jesse Wilson    }
110235eef71e8ce721c4199c525890ecc1a263054596Jesse Wilson
1103ffd579b668428272b78f5c6c64f9c89766f37c1aJesse Wilson    enum StreamingMode {
1104ffd579b668428272b78f5c6c64f9c89766f37c1aJesse Wilson        FIXED_LENGTH, CHUNKED
1105ffd579b668428272b78f5c6c64f9c89766f37c1aJesse Wilson    }
1106ffd579b668428272b78f5c6c64f9c89766f37c1aJesse Wilson
1107ffd579b668428272b78f5c6c64f9c89766f37c1aJesse Wilson    public void testAuthenticateWithPost() throws Exception {
1108ffd579b668428272b78f5c6c64f9c89766f37c1aJesse Wilson        MockResponse pleaseAuthenticate = new MockResponse()
1109ffd579b668428272b78f5c6c64f9c89766f37c1aJesse Wilson                .setResponseCode(401)
1110ffd579b668428272b78f5c6c64f9c89766f37c1aJesse Wilson                .addHeader("WWW-Authenticate: Basic realm=\"protected area\"")
1111ffd579b668428272b78f5c6c64f9c89766f37c1aJesse Wilson                .setBody("Please authenticate.");
1112ffd579b668428272b78f5c6c64f9c89766f37c1aJesse Wilson        // fail auth three times...
1113ffd579b668428272b78f5c6c64f9c89766f37c1aJesse Wilson        server.enqueue(pleaseAuthenticate);
1114ffd579b668428272b78f5c6c64f9c89766f37c1aJesse Wilson        server.enqueue(pleaseAuthenticate);
1115ffd579b668428272b78f5c6c64f9c89766f37c1aJesse Wilson        server.enqueue(pleaseAuthenticate);
1116ffd579b668428272b78f5c6c64f9c89766f37c1aJesse Wilson        // ...then succeed the fourth time
1117ffd579b668428272b78f5c6c64f9c89766f37c1aJesse Wilson        server.enqueue(new MockResponse().setBody("Successful auth!"));
1118ffd579b668428272b78f5c6c64f9c89766f37c1aJesse Wilson        server.play();
1119ffd579b668428272b78f5c6c64f9c89766f37c1aJesse Wilson
1120ffd579b668428272b78f5c6c64f9c89766f37c1aJesse Wilson        Authenticator.setDefault(SIMPLE_AUTHENTICATOR);
1121ffd579b668428272b78f5c6c64f9c89766f37c1aJesse Wilson        HttpURLConnection connection = (HttpURLConnection) server.getUrl("/").openConnection();
1122ffd579b668428272b78f5c6c64f9c89766f37c1aJesse Wilson        connection.setDoOutput(true);
1123ffd579b668428272b78f5c6c64f9c89766f37c1aJesse Wilson        byte[] requestBody = { 'A', 'B', 'C', 'D' };
1124ffd579b668428272b78f5c6c64f9c89766f37c1aJesse Wilson        OutputStream outputStream = connection.getOutputStream();
1125ffd579b668428272b78f5c6c64f9c89766f37c1aJesse Wilson        outputStream.write(requestBody);
1126ffd579b668428272b78f5c6c64f9c89766f37c1aJesse Wilson        outputStream.close();
1127ffd579b668428272b78f5c6c64f9c89766f37c1aJesse Wilson        assertEquals("Successful auth!", readAscii(connection.getInputStream(), Integer.MAX_VALUE));
1128ffd579b668428272b78f5c6c64f9c89766f37c1aJesse Wilson
1129ffd579b668428272b78f5c6c64f9c89766f37c1aJesse Wilson        // no authorization header for the first request...
1130ffd579b668428272b78f5c6c64f9c89766f37c1aJesse Wilson        RecordedRequest request = server.takeRequest();
1131ffd579b668428272b78f5c6c64f9c89766f37c1aJesse Wilson        assertContainsNoneMatching(request.getHeaders(), "Authorization: Basic .*");
1132ffd579b668428272b78f5c6c64f9c89766f37c1aJesse Wilson
1133da289bcd0a9e207cc03c752f7c21c9004056e179Jesse Wilson        // ...but the three requests that follow include an authorization header
1134ffd579b668428272b78f5c6c64f9c89766f37c1aJesse Wilson        for (int i = 0; i < 3; i++) {
1135ffd579b668428272b78f5c6c64f9c89766f37c1aJesse Wilson            request = server.takeRequest();
1136ffd579b668428272b78f5c6c64f9c89766f37c1aJesse Wilson            assertEquals("POST / HTTP/1.1", request.getRequestLine());
1137c996149b500fc4825156106554457fe2394ae087Jesse Wilson            assertContains(request.getHeaders(), "Authorization: Basic " + BASE_64_CREDENTIALS);
1138ffd579b668428272b78f5c6c64f9c89766f37c1aJesse Wilson            assertEquals(Arrays.toString(requestBody), Arrays.toString(request.getBody()));
1139ffd579b668428272b78f5c6c64f9c89766f37c1aJesse Wilson        }
1140ffd579b668428272b78f5c6c64f9c89766f37c1aJesse Wilson    }
1141ffd579b668428272b78f5c6c64f9c89766f37c1aJesse Wilson
1142ffd579b668428272b78f5c6c64f9c89766f37c1aJesse Wilson    public void testAuthenticateWithGet() throws Exception {
1143ffd579b668428272b78f5c6c64f9c89766f37c1aJesse Wilson        MockResponse pleaseAuthenticate = new MockResponse()
1144ffd579b668428272b78f5c6c64f9c89766f37c1aJesse Wilson                .setResponseCode(401)
1145ffd579b668428272b78f5c6c64f9c89766f37c1aJesse Wilson                .addHeader("WWW-Authenticate: Basic realm=\"protected area\"")
1146ffd579b668428272b78f5c6c64f9c89766f37c1aJesse Wilson                .setBody("Please authenticate.");
1147ffd579b668428272b78f5c6c64f9c89766f37c1aJesse Wilson        // fail auth three times...
1148ffd579b668428272b78f5c6c64f9c89766f37c1aJesse Wilson        server.enqueue(pleaseAuthenticate);
1149ffd579b668428272b78f5c6c64f9c89766f37c1aJesse Wilson        server.enqueue(pleaseAuthenticate);
1150ffd579b668428272b78f5c6c64f9c89766f37c1aJesse Wilson        server.enqueue(pleaseAuthenticate);
1151ffd579b668428272b78f5c6c64f9c89766f37c1aJesse Wilson        // ...then succeed the fourth time
1152ffd579b668428272b78f5c6c64f9c89766f37c1aJesse Wilson        server.enqueue(new MockResponse().setBody("Successful auth!"));
1153ffd579b668428272b78f5c6c64f9c89766f37c1aJesse Wilson        server.play();
1154ffd579b668428272b78f5c6c64f9c89766f37c1aJesse Wilson
1155ffd579b668428272b78f5c6c64f9c89766f37c1aJesse Wilson        Authenticator.setDefault(SIMPLE_AUTHENTICATOR);
1156ffd579b668428272b78f5c6c64f9c89766f37c1aJesse Wilson        HttpURLConnection connection = (HttpURLConnection) server.getUrl("/").openConnection();
1157ffd579b668428272b78f5c6c64f9c89766f37c1aJesse Wilson        assertEquals("Successful auth!", readAscii(connection.getInputStream(), Integer.MAX_VALUE));
1158ffd579b668428272b78f5c6c64f9c89766f37c1aJesse Wilson
1159ffd579b668428272b78f5c6c64f9c89766f37c1aJesse Wilson        // no authorization header for the first request...
1160ffd579b668428272b78f5c6c64f9c89766f37c1aJesse Wilson        RecordedRequest request = server.takeRequest();
1161ffd579b668428272b78f5c6c64f9c89766f37c1aJesse Wilson        assertContainsNoneMatching(request.getHeaders(), "Authorization: Basic .*");
1162ffd579b668428272b78f5c6c64f9c89766f37c1aJesse Wilson
1163ffd579b668428272b78f5c6c64f9c89766f37c1aJesse Wilson        // ...but the three requests that follow requests include an authorization header
1164ffd579b668428272b78f5c6c64f9c89766f37c1aJesse Wilson        for (int i = 0; i < 3; i++) {
1165ffd579b668428272b78f5c6c64f9c89766f37c1aJesse Wilson            request = server.takeRequest();
1166ffd579b668428272b78f5c6c64f9c89766f37c1aJesse Wilson            assertEquals("GET / HTTP/1.1", request.getRequestLine());
1167c996149b500fc4825156106554457fe2394ae087Jesse Wilson            assertContains(request.getHeaders(), "Authorization: Basic " + BASE_64_CREDENTIALS);
1168ffd579b668428272b78f5c6c64f9c89766f37c1aJesse Wilson        }
1169ffd579b668428272b78f5c6c64f9c89766f37c1aJesse Wilson    }
1170ffd579b668428272b78f5c6c64f9c89766f37c1aJesse Wilson
1171c0372d90016d241ac979faa6fa1731f30b6f2a03Jesse Wilson    public void testRedirectedWithChunkedEncoding() throws Exception {
1172c0372d90016d241ac979faa6fa1731f30b6f2a03Jesse Wilson        testRedirected(TransferKind.CHUNKED, true);
1173c0372d90016d241ac979faa6fa1731f30b6f2a03Jesse Wilson    }
1174c0372d90016d241ac979faa6fa1731f30b6f2a03Jesse Wilson
1175c0372d90016d241ac979faa6fa1731f30b6f2a03Jesse Wilson    public void testRedirectedWithContentLengthHeader() throws Exception {
1176c0372d90016d241ac979faa6fa1731f30b6f2a03Jesse Wilson        testRedirected(TransferKind.FIXED_LENGTH, true);
1177c0372d90016d241ac979faa6fa1731f30b6f2a03Jesse Wilson    }
1178c0372d90016d241ac979faa6fa1731f30b6f2a03Jesse Wilson
1179c0372d90016d241ac979faa6fa1731f30b6f2a03Jesse Wilson    public void testRedirectedWithNoLengthHeaders() throws Exception {
1180c0372d90016d241ac979faa6fa1731f30b6f2a03Jesse Wilson        testRedirected(TransferKind.END_OF_STREAM, false);
1181c0372d90016d241ac979faa6fa1731f30b6f2a03Jesse Wilson    }
1182c0372d90016d241ac979faa6fa1731f30b6f2a03Jesse Wilson
1183c0372d90016d241ac979faa6fa1731f30b6f2a03Jesse Wilson    private void testRedirected(TransferKind transferKind, boolean reuse) throws Exception {
1184c0372d90016d241ac979faa6fa1731f30b6f2a03Jesse Wilson        MockResponse response = new MockResponse()
1185c0372d90016d241ac979faa6fa1731f30b6f2a03Jesse Wilson                .setResponseCode(HttpURLConnection.HTTP_MOVED_TEMP)
1186c0372d90016d241ac979faa6fa1731f30b6f2a03Jesse Wilson                .addHeader("Location: /foo");
1187c0372d90016d241ac979faa6fa1731f30b6f2a03Jesse Wilson        transferKind.setBody(response, "This page has moved!", 10);
1188c0372d90016d241ac979faa6fa1731f30b6f2a03Jesse Wilson        server.enqueue(response);
1189c0372d90016d241ac979faa6fa1731f30b6f2a03Jesse Wilson        server.enqueue(new MockResponse().setBody("This is the new location!"));
1190c0372d90016d241ac979faa6fa1731f30b6f2a03Jesse Wilson        server.play();
1191c0372d90016d241ac979faa6fa1731f30b6f2a03Jesse Wilson
1192c0372d90016d241ac979faa6fa1731f30b6f2a03Jesse Wilson        URLConnection connection = server.getUrl("/").openConnection();
1193c0372d90016d241ac979faa6fa1731f30b6f2a03Jesse Wilson        assertEquals("This is the new location!",
1194c0372d90016d241ac979faa6fa1731f30b6f2a03Jesse Wilson                readAscii(connection.getInputStream(), Integer.MAX_VALUE));
1195c0372d90016d241ac979faa6fa1731f30b6f2a03Jesse Wilson
1196c0372d90016d241ac979faa6fa1731f30b6f2a03Jesse Wilson        RecordedRequest first = server.takeRequest();
1197c0372d90016d241ac979faa6fa1731f30b6f2a03Jesse Wilson        assertEquals("GET / HTTP/1.1", first.getRequestLine());
1198c0372d90016d241ac979faa6fa1731f30b6f2a03Jesse Wilson        RecordedRequest retry = server.takeRequest();
1199c0372d90016d241ac979faa6fa1731f30b6f2a03Jesse Wilson        assertEquals("GET /foo HTTP/1.1", retry.getRequestLine());
1200c0372d90016d241ac979faa6fa1731f30b6f2a03Jesse Wilson        if (reuse) {
1201c0372d90016d241ac979faa6fa1731f30b6f2a03Jesse Wilson            assertEquals("Expected connection reuse", 1, retry.getSequenceNumber());
1202c0372d90016d241ac979faa6fa1731f30b6f2a03Jesse Wilson        }
1203c0372d90016d241ac979faa6fa1731f30b6f2a03Jesse Wilson    }
1204c0372d90016d241ac979faa6fa1731f30b6f2a03Jesse Wilson
1205c0372d90016d241ac979faa6fa1731f30b6f2a03Jesse Wilson    public void testRedirectedOnHttps() throws IOException, InterruptedException {
1206c0372d90016d241ac979faa6fa1731f30b6f2a03Jesse Wilson        TestSSLContext testSSLContext = TestSSLContext.create();
1207059dbc04218144f985b20a228bbe98139d400d0cBrian Carlstrom        server.useHttps(testSSLContext.serverContext.getSocketFactory(), false);
1208c0372d90016d241ac979faa6fa1731f30b6f2a03Jesse Wilson        server.enqueue(new MockResponse()
1209c0372d90016d241ac979faa6fa1731f30b6f2a03Jesse Wilson                .setResponseCode(HttpURLConnection.HTTP_MOVED_TEMP)
1210c0372d90016d241ac979faa6fa1731f30b6f2a03Jesse Wilson                .addHeader("Location: /foo")
1211c0372d90016d241ac979faa6fa1731f30b6f2a03Jesse Wilson                .setBody("This page has moved!"));
1212c0372d90016d241ac979faa6fa1731f30b6f2a03Jesse Wilson        server.enqueue(new MockResponse().setBody("This is the new location!"));
1213c0372d90016d241ac979faa6fa1731f30b6f2a03Jesse Wilson        server.play();
1214c0372d90016d241ac979faa6fa1731f30b6f2a03Jesse Wilson
1215c0372d90016d241ac979faa6fa1731f30b6f2a03Jesse Wilson        HttpsURLConnection connection = (HttpsURLConnection) server.getUrl("/").openConnection();
1216059dbc04218144f985b20a228bbe98139d400d0cBrian Carlstrom        connection.setSSLSocketFactory(testSSLContext.clientContext.getSocketFactory());
1217c0372d90016d241ac979faa6fa1731f30b6f2a03Jesse Wilson        assertEquals("This is the new location!",
1218c0372d90016d241ac979faa6fa1731f30b6f2a03Jesse Wilson                readAscii(connection.getInputStream(), Integer.MAX_VALUE));
1219c0372d90016d241ac979faa6fa1731f30b6f2a03Jesse Wilson
1220c0372d90016d241ac979faa6fa1731f30b6f2a03Jesse Wilson        RecordedRequest first = server.takeRequest();
1221c0372d90016d241ac979faa6fa1731f30b6f2a03Jesse Wilson        assertEquals("GET / HTTP/1.1", first.getRequestLine());
1222c0372d90016d241ac979faa6fa1731f30b6f2a03Jesse Wilson        RecordedRequest retry = server.takeRequest();
1223c0372d90016d241ac979faa6fa1731f30b6f2a03Jesse Wilson        assertEquals("GET /foo HTTP/1.1", retry.getRequestLine());
1224c0372d90016d241ac979faa6fa1731f30b6f2a03Jesse Wilson        assertEquals("Expected connection reuse", 1, retry.getSequenceNumber());
1225c0372d90016d241ac979faa6fa1731f30b6f2a03Jesse Wilson    }
1226c0372d90016d241ac979faa6fa1731f30b6f2a03Jesse Wilson
1227c0372d90016d241ac979faa6fa1731f30b6f2a03Jesse Wilson    public void testNotRedirectedFromHttpsToHttp() throws IOException, InterruptedException {
1228c0372d90016d241ac979faa6fa1731f30b6f2a03Jesse Wilson        TestSSLContext testSSLContext = TestSSLContext.create();
1229059dbc04218144f985b20a228bbe98139d400d0cBrian Carlstrom        server.useHttps(testSSLContext.serverContext.getSocketFactory(), false);
1230c0372d90016d241ac979faa6fa1731f30b6f2a03Jesse Wilson        server.enqueue(new MockResponse()
1231c0372d90016d241ac979faa6fa1731f30b6f2a03Jesse Wilson                .setResponseCode(HttpURLConnection.HTTP_MOVED_TEMP)
1232c0372d90016d241ac979faa6fa1731f30b6f2a03Jesse Wilson                .addHeader("Location: http://anyhost/foo")
1233c0372d90016d241ac979faa6fa1731f30b6f2a03Jesse Wilson                .setBody("This page has moved!"));
1234c0372d90016d241ac979faa6fa1731f30b6f2a03Jesse Wilson        server.play();
1235c0372d90016d241ac979faa6fa1731f30b6f2a03Jesse Wilson
1236c0372d90016d241ac979faa6fa1731f30b6f2a03Jesse Wilson        HttpsURLConnection connection = (HttpsURLConnection) server.getUrl("/").openConnection();
1237059dbc04218144f985b20a228bbe98139d400d0cBrian Carlstrom        connection.setSSLSocketFactory(testSSLContext.clientContext.getSocketFactory());
1238c0372d90016d241ac979faa6fa1731f30b6f2a03Jesse Wilson        assertEquals("This page has moved!",
1239c0372d90016d241ac979faa6fa1731f30b6f2a03Jesse Wilson                readAscii(connection.getInputStream(), Integer.MAX_VALUE));
1240c0372d90016d241ac979faa6fa1731f30b6f2a03Jesse Wilson    }
1241c0372d90016d241ac979faa6fa1731f30b6f2a03Jesse Wilson
1242c0372d90016d241ac979faa6fa1731f30b6f2a03Jesse Wilson    public void testNotRedirectedFromHttpToHttps() throws IOException, InterruptedException {
1243c0372d90016d241ac979faa6fa1731f30b6f2a03Jesse Wilson        server.enqueue(new MockResponse()
1244c0372d90016d241ac979faa6fa1731f30b6f2a03Jesse Wilson                .setResponseCode(HttpURLConnection.HTTP_MOVED_TEMP)
1245c0372d90016d241ac979faa6fa1731f30b6f2a03Jesse Wilson                .addHeader("Location: https://anyhost/foo")
1246c0372d90016d241ac979faa6fa1731f30b6f2a03Jesse Wilson                .setBody("This page has moved!"));
1247c0372d90016d241ac979faa6fa1731f30b6f2a03Jesse Wilson        server.play();
1248c0372d90016d241ac979faa6fa1731f30b6f2a03Jesse Wilson
1249c0372d90016d241ac979faa6fa1731f30b6f2a03Jesse Wilson        HttpURLConnection connection = (HttpURLConnection) server.getUrl("/").openConnection();
1250c0372d90016d241ac979faa6fa1731f30b6f2a03Jesse Wilson        assertEquals("This page has moved!",
1251c0372d90016d241ac979faa6fa1731f30b6f2a03Jesse Wilson                readAscii(connection.getInputStream(), Integer.MAX_VALUE));
1252c0372d90016d241ac979faa6fa1731f30b6f2a03Jesse Wilson    }
1253c0372d90016d241ac979faa6fa1731f30b6f2a03Jesse Wilson
1254c0372d90016d241ac979faa6fa1731f30b6f2a03Jesse Wilson    public void testRedirectToAnotherOriginServer() throws Exception {
1255c0372d90016d241ac979faa6fa1731f30b6f2a03Jesse Wilson        MockWebServer server2 = new MockWebServer();
1256c0372d90016d241ac979faa6fa1731f30b6f2a03Jesse Wilson        server2.enqueue(new MockResponse().setBody("This is the 2nd server!"));
1257c0372d90016d241ac979faa6fa1731f30b6f2a03Jesse Wilson        server2.play();
1258c0372d90016d241ac979faa6fa1731f30b6f2a03Jesse Wilson
1259c0372d90016d241ac979faa6fa1731f30b6f2a03Jesse Wilson        server.enqueue(new MockResponse()
1260c0372d90016d241ac979faa6fa1731f30b6f2a03Jesse Wilson                .setResponseCode(HttpURLConnection.HTTP_MOVED_TEMP)
1261c0372d90016d241ac979faa6fa1731f30b6f2a03Jesse Wilson                .addHeader("Location: " + server2.getUrl("/").toString())
1262c0372d90016d241ac979faa6fa1731f30b6f2a03Jesse Wilson                .setBody("This page has moved!"));
1263c0372d90016d241ac979faa6fa1731f30b6f2a03Jesse Wilson        server.enqueue(new MockResponse().setBody("This is the first server again!"));
1264c0372d90016d241ac979faa6fa1731f30b6f2a03Jesse Wilson        server.play();
1265c0372d90016d241ac979faa6fa1731f30b6f2a03Jesse Wilson
1266c0372d90016d241ac979faa6fa1731f30b6f2a03Jesse Wilson        URLConnection connection = server.getUrl("/").openConnection();
1267c0372d90016d241ac979faa6fa1731f30b6f2a03Jesse Wilson        assertEquals("This is the 2nd server!",
1268c0372d90016d241ac979faa6fa1731f30b6f2a03Jesse Wilson                readAscii(connection.getInputStream(), Integer.MAX_VALUE));
1269c0372d90016d241ac979faa6fa1731f30b6f2a03Jesse Wilson        assertEquals(server2.getUrl("/"), connection.getURL());
1270c0372d90016d241ac979faa6fa1731f30b6f2a03Jesse Wilson
1271c0372d90016d241ac979faa6fa1731f30b6f2a03Jesse Wilson        // make sure the first server was careful to recycle the connection
1272c0372d90016d241ac979faa6fa1731f30b6f2a03Jesse Wilson        assertEquals("This is the first server again!",
1273c0372d90016d241ac979faa6fa1731f30b6f2a03Jesse Wilson                readAscii(server.getUrl("/").openStream(), Integer.MAX_VALUE));
1274c0372d90016d241ac979faa6fa1731f30b6f2a03Jesse Wilson
1275c0372d90016d241ac979faa6fa1731f30b6f2a03Jesse Wilson        RecordedRequest first = server.takeRequest();
12760c2fd828abec671333b8b88281825fd27a783723Jesse Wilson        assertContains(first.getHeaders(), "Host: " + hostName + ":" + server.getPort());
1277c0372d90016d241ac979faa6fa1731f30b6f2a03Jesse Wilson        RecordedRequest second = server2.takeRequest();
12780c2fd828abec671333b8b88281825fd27a783723Jesse Wilson        assertContains(second.getHeaders(), "Host: " + hostName + ":" + server2.getPort());
1279c0372d90016d241ac979faa6fa1731f30b6f2a03Jesse Wilson        RecordedRequest third = server.takeRequest();
1280c0372d90016d241ac979faa6fa1731f30b6f2a03Jesse Wilson        assertEquals("Expected connection reuse", 1, third.getSequenceNumber());
1281c0372d90016d241ac979faa6fa1731f30b6f2a03Jesse Wilson
1282c0372d90016d241ac979faa6fa1731f30b6f2a03Jesse Wilson        server2.shutdown();
1283c0372d90016d241ac979faa6fa1731f30b6f2a03Jesse Wilson    }
1284c0372d90016d241ac979faa6fa1731f30b6f2a03Jesse Wilson
1285d742d7fc7f0593eb8c6e4ac9dd4c0f6a80374e46Jesse Wilson    public void testResponse300MultipleChoiceWithPost() throws Exception {
1286d742d7fc7f0593eb8c6e4ac9dd4c0f6a80374e46Jesse Wilson        // Chrome doesn't follow the redirect, but Firefox and the RI both do
1287d742d7fc7f0593eb8c6e4ac9dd4c0f6a80374e46Jesse Wilson        testResponseRedirectedWithPost(HttpURLConnection.HTTP_MULT_CHOICE);
1288d742d7fc7f0593eb8c6e4ac9dd4c0f6a80374e46Jesse Wilson    }
1289d742d7fc7f0593eb8c6e4ac9dd4c0f6a80374e46Jesse Wilson
1290d742d7fc7f0593eb8c6e4ac9dd4c0f6a80374e46Jesse Wilson    public void testResponse301MovedPermanentlyWithPost() throws Exception {
1291d742d7fc7f0593eb8c6e4ac9dd4c0f6a80374e46Jesse Wilson        testResponseRedirectedWithPost(HttpURLConnection.HTTP_MOVED_PERM);
1292d742d7fc7f0593eb8c6e4ac9dd4c0f6a80374e46Jesse Wilson    }
1293d742d7fc7f0593eb8c6e4ac9dd4c0f6a80374e46Jesse Wilson
1294d742d7fc7f0593eb8c6e4ac9dd4c0f6a80374e46Jesse Wilson    public void testResponse302MovedTemporarilyWithPost() throws Exception {
1295d742d7fc7f0593eb8c6e4ac9dd4c0f6a80374e46Jesse Wilson        testResponseRedirectedWithPost(HttpURLConnection.HTTP_MOVED_TEMP);
1296d742d7fc7f0593eb8c6e4ac9dd4c0f6a80374e46Jesse Wilson    }
1297d742d7fc7f0593eb8c6e4ac9dd4c0f6a80374e46Jesse Wilson
1298d742d7fc7f0593eb8c6e4ac9dd4c0f6a80374e46Jesse Wilson    public void testResponse303SeeOtherWithPost() throws Exception {
1299d742d7fc7f0593eb8c6e4ac9dd4c0f6a80374e46Jesse Wilson        testResponseRedirectedWithPost(HttpURLConnection.HTTP_SEE_OTHER);
1300d742d7fc7f0593eb8c6e4ac9dd4c0f6a80374e46Jesse Wilson    }
1301d742d7fc7f0593eb8c6e4ac9dd4c0f6a80374e46Jesse Wilson
1302d742d7fc7f0593eb8c6e4ac9dd4c0f6a80374e46Jesse Wilson    private void testResponseRedirectedWithPost(int redirectCode) throws Exception {
1303d742d7fc7f0593eb8c6e4ac9dd4c0f6a80374e46Jesse Wilson        server.enqueue(new MockResponse()
1304d742d7fc7f0593eb8c6e4ac9dd4c0f6a80374e46Jesse Wilson                .setResponseCode(redirectCode)
1305d742d7fc7f0593eb8c6e4ac9dd4c0f6a80374e46Jesse Wilson                .addHeader("Location: /page2")
1306d742d7fc7f0593eb8c6e4ac9dd4c0f6a80374e46Jesse Wilson                .setBody("This page has moved!"));
1307d742d7fc7f0593eb8c6e4ac9dd4c0f6a80374e46Jesse Wilson        server.enqueue(new MockResponse().setBody("Page 2"));
1308d742d7fc7f0593eb8c6e4ac9dd4c0f6a80374e46Jesse Wilson        server.play();
1309d742d7fc7f0593eb8c6e4ac9dd4c0f6a80374e46Jesse Wilson
1310d742d7fc7f0593eb8c6e4ac9dd4c0f6a80374e46Jesse Wilson        HttpURLConnection connection = (HttpURLConnection) server.getUrl("/page1").openConnection();
1311d742d7fc7f0593eb8c6e4ac9dd4c0f6a80374e46Jesse Wilson        connection.setDoOutput(true);
1312d742d7fc7f0593eb8c6e4ac9dd4c0f6a80374e46Jesse Wilson        byte[] requestBody = { 'A', 'B', 'C', 'D' };
1313d742d7fc7f0593eb8c6e4ac9dd4c0f6a80374e46Jesse Wilson        OutputStream outputStream = connection.getOutputStream();
1314d742d7fc7f0593eb8c6e4ac9dd4c0f6a80374e46Jesse Wilson        outputStream.write(requestBody);
1315d742d7fc7f0593eb8c6e4ac9dd4c0f6a80374e46Jesse Wilson        outputStream.close();
1316d742d7fc7f0593eb8c6e4ac9dd4c0f6a80374e46Jesse Wilson        assertEquals("Page 2", readAscii(connection.getInputStream(), Integer.MAX_VALUE));
1317d742d7fc7f0593eb8c6e4ac9dd4c0f6a80374e46Jesse Wilson        assertTrue(connection.getDoOutput());
1318d742d7fc7f0593eb8c6e4ac9dd4c0f6a80374e46Jesse Wilson
1319d742d7fc7f0593eb8c6e4ac9dd4c0f6a80374e46Jesse Wilson        RecordedRequest page1 = server.takeRequest();
1320d742d7fc7f0593eb8c6e4ac9dd4c0f6a80374e46Jesse Wilson        assertEquals("POST /page1 HTTP/1.1", page1.getRequestLine());
1321d742d7fc7f0593eb8c6e4ac9dd4c0f6a80374e46Jesse Wilson        assertEquals(Arrays.toString(requestBody), Arrays.toString(page1.getBody()));
1322d742d7fc7f0593eb8c6e4ac9dd4c0f6a80374e46Jesse Wilson
1323d742d7fc7f0593eb8c6e4ac9dd4c0f6a80374e46Jesse Wilson        RecordedRequest page2 = server.takeRequest();
1324d742d7fc7f0593eb8c6e4ac9dd4c0f6a80374e46Jesse Wilson        assertEquals("GET /page2 HTTP/1.1", page2.getRequestLine());
1325d742d7fc7f0593eb8c6e4ac9dd4c0f6a80374e46Jesse Wilson    }
1326d742d7fc7f0593eb8c6e4ac9dd4c0f6a80374e46Jesse Wilson
1327d742d7fc7f0593eb8c6e4ac9dd4c0f6a80374e46Jesse Wilson    public void testResponse305UseProxy() throws Exception {
1328d742d7fc7f0593eb8c6e4ac9dd4c0f6a80374e46Jesse Wilson        server.play();
1329d742d7fc7f0593eb8c6e4ac9dd4c0f6a80374e46Jesse Wilson        server.enqueue(new MockResponse()
1330d742d7fc7f0593eb8c6e4ac9dd4c0f6a80374e46Jesse Wilson                .setResponseCode(HttpURLConnection.HTTP_USE_PROXY)
1331d742d7fc7f0593eb8c6e4ac9dd4c0f6a80374e46Jesse Wilson                .addHeader("Location: " + server.getUrl("/"))
1332d742d7fc7f0593eb8c6e4ac9dd4c0f6a80374e46Jesse Wilson                .setBody("This page has moved!"));
1333d742d7fc7f0593eb8c6e4ac9dd4c0f6a80374e46Jesse Wilson        server.enqueue(new MockResponse().setBody("Proxy Response"));
1334d742d7fc7f0593eb8c6e4ac9dd4c0f6a80374e46Jesse Wilson
1335d742d7fc7f0593eb8c6e4ac9dd4c0f6a80374e46Jesse Wilson        HttpURLConnection connection = (HttpURLConnection) server.getUrl("/foo").openConnection();
1336d742d7fc7f0593eb8c6e4ac9dd4c0f6a80374e46Jesse Wilson        // Fails on the RI, which gets "Proxy Response"
1337d742d7fc7f0593eb8c6e4ac9dd4c0f6a80374e46Jesse Wilson        assertEquals("This page has moved!",
1338d742d7fc7f0593eb8c6e4ac9dd4c0f6a80374e46Jesse Wilson                readAscii(connection.getInputStream(), Integer.MAX_VALUE));
1339d742d7fc7f0593eb8c6e4ac9dd4c0f6a80374e46Jesse Wilson
1340d742d7fc7f0593eb8c6e4ac9dd4c0f6a80374e46Jesse Wilson        RecordedRequest page1 = server.takeRequest();
1341d742d7fc7f0593eb8c6e4ac9dd4c0f6a80374e46Jesse Wilson        assertEquals("GET /foo HTTP/1.1", page1.getRequestLine());
1342d742d7fc7f0593eb8c6e4ac9dd4c0f6a80374e46Jesse Wilson        assertEquals(1, server.getRequestCount());
1343d742d7fc7f0593eb8c6e4ac9dd4c0f6a80374e46Jesse Wilson    }
1344d742d7fc7f0593eb8c6e4ac9dd4c0f6a80374e46Jesse Wilson
1345c0372d90016d241ac979faa6fa1731f30b6f2a03Jesse Wilson    public void testHttpsWithCustomTrustManager() throws Exception {
1346c0372d90016d241ac979faa6fa1731f30b6f2a03Jesse Wilson        RecordingHostnameVerifier hostnameVerifier = new RecordingHostnameVerifier();
1347c0372d90016d241ac979faa6fa1731f30b6f2a03Jesse Wilson        RecordingTrustManager trustManager = new RecordingTrustManager();
1348c0372d90016d241ac979faa6fa1731f30b6f2a03Jesse Wilson        SSLContext sc = SSLContext.getInstance("TLS");
1349c0372d90016d241ac979faa6fa1731f30b6f2a03Jesse Wilson        sc.init(null, new TrustManager[] { trustManager }, new java.security.SecureRandom());
1350c0372d90016d241ac979faa6fa1731f30b6f2a03Jesse Wilson
1351c0372d90016d241ac979faa6fa1731f30b6f2a03Jesse Wilson        HostnameVerifier defaultHostnameVerifier = HttpsURLConnection.getDefaultHostnameVerifier();
1352c0372d90016d241ac979faa6fa1731f30b6f2a03Jesse Wilson        HttpsURLConnection.setDefaultHostnameVerifier(hostnameVerifier);
1353c0372d90016d241ac979faa6fa1731f30b6f2a03Jesse Wilson        SSLSocketFactory defaultSSLSocketFactory = HttpsURLConnection.getDefaultSSLSocketFactory();
1354c0372d90016d241ac979faa6fa1731f30b6f2a03Jesse Wilson        HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
1355c0372d90016d241ac979faa6fa1731f30b6f2a03Jesse Wilson        try {
1356c0372d90016d241ac979faa6fa1731f30b6f2a03Jesse Wilson            TestSSLContext testSSLContext = TestSSLContext.create();
1357059dbc04218144f985b20a228bbe98139d400d0cBrian Carlstrom            server.useHttps(testSSLContext.serverContext.getSocketFactory(), false);
1358c0372d90016d241ac979faa6fa1731f30b6f2a03Jesse Wilson            server.enqueue(new MockResponse().setBody("ABC"));
1359c0372d90016d241ac979faa6fa1731f30b6f2a03Jesse Wilson            server.enqueue(new MockResponse().setBody("DEF"));
1360c0372d90016d241ac979faa6fa1731f30b6f2a03Jesse Wilson            server.enqueue(new MockResponse().setBody("GHI"));
1361c0372d90016d241ac979faa6fa1731f30b6f2a03Jesse Wilson            server.play();
1362c0372d90016d241ac979faa6fa1731f30b6f2a03Jesse Wilson
1363c0372d90016d241ac979faa6fa1731f30b6f2a03Jesse Wilson            URL url = server.getUrl("/");
1364c0372d90016d241ac979faa6fa1731f30b6f2a03Jesse Wilson            assertEquals("ABC", readAscii(url.openStream(), Integer.MAX_VALUE));
1365c0372d90016d241ac979faa6fa1731f30b6f2a03Jesse Wilson            assertEquals("DEF", readAscii(url.openStream(), Integer.MAX_VALUE));
1366c0372d90016d241ac979faa6fa1731f30b6f2a03Jesse Wilson            assertEquals("GHI", readAscii(url.openStream(), Integer.MAX_VALUE));
1367c0372d90016d241ac979faa6fa1731f30b6f2a03Jesse Wilson
13680c2fd828abec671333b8b88281825fd27a783723Jesse Wilson            assertEquals(Arrays.asList("verify " + hostName), hostnameVerifier.calls);
13694559b1d37edcb5d7f1da086cf2e3290388d74f46Brian Carlstrom            assertEquals(Arrays.asList("checkServerTrusted ["
13700c2fd828abec671333b8b88281825fd27a783723Jesse Wilson                    + "CN=" + hostName + " 1, "
1371b7f4d6c3968c372767b2510f38a3d506067aced6Jesse Wilson                    + "CN=Test Intermediate Certificate Authority 1, "
1372b7f4d6c3968c372767b2510f38a3d506067aced6Jesse Wilson                    + "CN=Test Root Certificate Authority 1"
1373b7f4d6c3968c372767b2510f38a3d506067aced6Jesse Wilson                    + "] RSA"),
1374c0372d90016d241ac979faa6fa1731f30b6f2a03Jesse Wilson                    trustManager.calls);
1375c0372d90016d241ac979faa6fa1731f30b6f2a03Jesse Wilson        } finally {
1376c0372d90016d241ac979faa6fa1731f30b6f2a03Jesse Wilson            HttpsURLConnection.setDefaultHostnameVerifier(defaultHostnameVerifier);
1377c0372d90016d241ac979faa6fa1731f30b6f2a03Jesse Wilson            HttpsURLConnection.setDefaultSSLSocketFactory(defaultSSLSocketFactory);
1378c0372d90016d241ac979faa6fa1731f30b6f2a03Jesse Wilson        }
1379c0372d90016d241ac979faa6fa1731f30b6f2a03Jesse Wilson    }
1380c0372d90016d241ac979faa6fa1731f30b6f2a03Jesse Wilson
1381eafede536f2059bb6c869e7a5f07fd7ad9758e28Jesse Wilson    public void testConnectTimeouts() throws IOException {
13825fc5dde4c719c1dfdac46b67d5d2e4884d07721eElliott Hughes        StuckServer ss = new StuckServer();
13835fc5dde4c719c1dfdac46b67d5d2e4884d07721eElliott Hughes        int serverPort = ss.getLocalPort();
1384f02c695ed03e708623d9365dec26d533356ef2d0Brian Carlstrom        URLConnection urlConnection = new URL("http://localhost:" + serverPort).openConnection();
1385b7f4d6c3968c372767b2510f38a3d506067aced6Jesse Wilson        int timeout = 1000;
1386b7f4d6c3968c372767b2510f38a3d506067aced6Jesse Wilson        urlConnection.setConnectTimeout(timeout);
1387b7f4d6c3968c372767b2510f38a3d506067aced6Jesse Wilson        long start = System.currentTimeMillis();
1388eafede536f2059bb6c869e7a5f07fd7ad9758e28Jesse Wilson        try {
1389eafede536f2059bb6c869e7a5f07fd7ad9758e28Jesse Wilson            urlConnection.getInputStream();
1390eafede536f2059bb6c869e7a5f07fd7ad9758e28Jesse Wilson            fail();
1391eafede536f2059bb6c869e7a5f07fd7ad9758e28Jesse Wilson        } catch (SocketTimeoutException expected) {
1392b7f4d6c3968c372767b2510f38a3d506067aced6Jesse Wilson            long actual = System.currentTimeMillis() - start;
1393b7f4d6c3968c372767b2510f38a3d506067aced6Jesse Wilson            assertTrue(Math.abs(timeout - actual) < 500);
13945fc5dde4c719c1dfdac46b67d5d2e4884d07721eElliott Hughes        } finally {
13955fc5dde4c719c1dfdac46b67d5d2e4884d07721eElliott Hughes            ss.close();
1396f02c695ed03e708623d9365dec26d533356ef2d0Brian Carlstrom        }
1397eafede536f2059bb6c869e7a5f07fd7ad9758e28Jesse Wilson    }
1398eafede536f2059bb6c869e7a5f07fd7ad9758e28Jesse Wilson
1399eafede536f2059bb6c869e7a5f07fd7ad9758e28Jesse Wilson    public void testReadTimeouts() throws IOException {
1400eafede536f2059bb6c869e7a5f07fd7ad9758e28Jesse Wilson        /*
1401eafede536f2059bb6c869e7a5f07fd7ad9758e28Jesse Wilson         * This relies on the fact that MockWebServer doesn't close the
1402eafede536f2059bb6c869e7a5f07fd7ad9758e28Jesse Wilson         * connection after a response has been sent. This causes the client to
1403eafede536f2059bb6c869e7a5f07fd7ad9758e28Jesse Wilson         * try to read more bytes than are sent, which results in a timeout.
1404eafede536f2059bb6c869e7a5f07fd7ad9758e28Jesse Wilson         */
1405eafede536f2059bb6c869e7a5f07fd7ad9758e28Jesse Wilson        MockResponse timeout = new MockResponse()
1406eafede536f2059bb6c869e7a5f07fd7ad9758e28Jesse Wilson                .setBody("ABC")
1407eafede536f2059bb6c869e7a5f07fd7ad9758e28Jesse Wilson                .clearHeaders()
1408eafede536f2059bb6c869e7a5f07fd7ad9758e28Jesse Wilson                .addHeader("Content-Length: 4");
1409eafede536f2059bb6c869e7a5f07fd7ad9758e28Jesse Wilson        server.enqueue(timeout);
1410b7f4d6c3968c372767b2510f38a3d506067aced6Jesse Wilson        server.enqueue(new MockResponse().setBody("unused")); // to keep the server alive
1411eafede536f2059bb6c869e7a5f07fd7ad9758e28Jesse Wilson        server.play();
1412eafede536f2059bb6c869e7a5f07fd7ad9758e28Jesse Wilson
1413eafede536f2059bb6c869e7a5f07fd7ad9758e28Jesse Wilson        URLConnection urlConnection = server.getUrl("/").openConnection();
1414eafede536f2059bb6c869e7a5f07fd7ad9758e28Jesse Wilson        urlConnection.setReadTimeout(1000);
1415eafede536f2059bb6c869e7a5f07fd7ad9758e28Jesse Wilson        InputStream in = urlConnection.getInputStream();
1416eafede536f2059bb6c869e7a5f07fd7ad9758e28Jesse Wilson        assertEquals('A', in.read());
1417eafede536f2059bb6c869e7a5f07fd7ad9758e28Jesse Wilson        assertEquals('B', in.read());
1418eafede536f2059bb6c869e7a5f07fd7ad9758e28Jesse Wilson        assertEquals('C', in.read());
1419eafede536f2059bb6c869e7a5f07fd7ad9758e28Jesse Wilson        try {
1420eafede536f2059bb6c869e7a5f07fd7ad9758e28Jesse Wilson            in.read(); // if Content-Length was accurate, this would return -1 immediately
1421eafede536f2059bb6c869e7a5f07fd7ad9758e28Jesse Wilson            fail();
1422eafede536f2059bb6c869e7a5f07fd7ad9758e28Jesse Wilson        } catch (SocketTimeoutException expected) {
1423eafede536f2059bb6c869e7a5f07fd7ad9758e28Jesse Wilson        }
1424eafede536f2059bb6c869e7a5f07fd7ad9758e28Jesse Wilson    }
1425eafede536f2059bb6c869e7a5f07fd7ad9758e28Jesse Wilson
1426125f068f0a6cd739beac97821c9421cf8317cc87Jesse Wilson    public void testSetChunkedEncodingAsRequestProperty() throws IOException, InterruptedException {
1427125f068f0a6cd739beac97821c9421cf8317cc87Jesse Wilson        server.enqueue(new MockResponse());
1428125f068f0a6cd739beac97821c9421cf8317cc87Jesse Wilson        server.play();
1429125f068f0a6cd739beac97821c9421cf8317cc87Jesse Wilson
1430125f068f0a6cd739beac97821c9421cf8317cc87Jesse Wilson        HttpURLConnection urlConnection = (HttpURLConnection) server.getUrl("/").openConnection();
1431125f068f0a6cd739beac97821c9421cf8317cc87Jesse Wilson        urlConnection.setRequestProperty("Transfer-encoding", "chunked");
1432125f068f0a6cd739beac97821c9421cf8317cc87Jesse Wilson        urlConnection.setDoOutput(true);
1433125f068f0a6cd739beac97821c9421cf8317cc87Jesse Wilson        urlConnection.getOutputStream().write("ABC".getBytes("UTF-8"));
1434125f068f0a6cd739beac97821c9421cf8317cc87Jesse Wilson        assertEquals(200, urlConnection.getResponseCode());
1435125f068f0a6cd739beac97821c9421cf8317cc87Jesse Wilson
1436125f068f0a6cd739beac97821c9421cf8317cc87Jesse Wilson        RecordedRequest request = server.takeRequest();
1437125f068f0a6cd739beac97821c9421cf8317cc87Jesse Wilson        assertEquals("ABC", new String(request.getBody(), "UTF-8"));
1438125f068f0a6cd739beac97821c9421cf8317cc87Jesse Wilson    }
1439125f068f0a6cd739beac97821c9421cf8317cc87Jesse Wilson
1440f418bf447fd007cd2ec2d45b4b0399a11904e9b4Jesse Wilson    public void testConnectionCloseInRequest() throws IOException, InterruptedException {
1441f418bf447fd007cd2ec2d45b4b0399a11904e9b4Jesse Wilson        server.enqueue(new MockResponse()); // server doesn't honor the connection: close header!
1442f418bf447fd007cd2ec2d45b4b0399a11904e9b4Jesse Wilson        server.enqueue(new MockResponse());
1443f418bf447fd007cd2ec2d45b4b0399a11904e9b4Jesse Wilson        server.play();
1444f418bf447fd007cd2ec2d45b4b0399a11904e9b4Jesse Wilson
1445f418bf447fd007cd2ec2d45b4b0399a11904e9b4Jesse Wilson        HttpURLConnection a = (HttpURLConnection) server.getUrl("/").openConnection();
1446f418bf447fd007cd2ec2d45b4b0399a11904e9b4Jesse Wilson        a.setRequestProperty("Connection", "close");
1447f418bf447fd007cd2ec2d45b4b0399a11904e9b4Jesse Wilson        assertEquals(200, a.getResponseCode());
1448f418bf447fd007cd2ec2d45b4b0399a11904e9b4Jesse Wilson
1449f418bf447fd007cd2ec2d45b4b0399a11904e9b4Jesse Wilson        HttpURLConnection b = (HttpURLConnection) server.getUrl("/").openConnection();
1450f418bf447fd007cd2ec2d45b4b0399a11904e9b4Jesse Wilson        assertEquals(200, b.getResponseCode());
1451f418bf447fd007cd2ec2d45b4b0399a11904e9b4Jesse Wilson
1452f418bf447fd007cd2ec2d45b4b0399a11904e9b4Jesse Wilson        assertEquals(0, server.takeRequest().getSequenceNumber());
1453f418bf447fd007cd2ec2d45b4b0399a11904e9b4Jesse Wilson        assertEquals("When connection: close is used, each request should get its own connection",
1454f418bf447fd007cd2ec2d45b4b0399a11904e9b4Jesse Wilson                0, server.takeRequest().getSequenceNumber());
1455f418bf447fd007cd2ec2d45b4b0399a11904e9b4Jesse Wilson    }
1456f418bf447fd007cd2ec2d45b4b0399a11904e9b4Jesse Wilson
1457f418bf447fd007cd2ec2d45b4b0399a11904e9b4Jesse Wilson    public void testConnectionCloseInResponse() throws IOException, InterruptedException {
1458f418bf447fd007cd2ec2d45b4b0399a11904e9b4Jesse Wilson        server.enqueue(new MockResponse().addHeader("Connection: close"));
1459f418bf447fd007cd2ec2d45b4b0399a11904e9b4Jesse Wilson        server.enqueue(new MockResponse());
1460f418bf447fd007cd2ec2d45b4b0399a11904e9b4Jesse Wilson        server.play();
1461f418bf447fd007cd2ec2d45b4b0399a11904e9b4Jesse Wilson
1462f418bf447fd007cd2ec2d45b4b0399a11904e9b4Jesse Wilson        HttpURLConnection a = (HttpURLConnection) server.getUrl("/").openConnection();
1463f418bf447fd007cd2ec2d45b4b0399a11904e9b4Jesse Wilson        assertEquals(200, a.getResponseCode());
1464f418bf447fd007cd2ec2d45b4b0399a11904e9b4Jesse Wilson
1465f418bf447fd007cd2ec2d45b4b0399a11904e9b4Jesse Wilson        HttpURLConnection b = (HttpURLConnection) server.getUrl("/").openConnection();
1466f418bf447fd007cd2ec2d45b4b0399a11904e9b4Jesse Wilson        assertEquals(200, b.getResponseCode());
1467f418bf447fd007cd2ec2d45b4b0399a11904e9b4Jesse Wilson
1468f418bf447fd007cd2ec2d45b4b0399a11904e9b4Jesse Wilson        assertEquals(0, server.takeRequest().getSequenceNumber());
1469f418bf447fd007cd2ec2d45b4b0399a11904e9b4Jesse Wilson        assertEquals("When connection: close is used, each request should get its own connection",
1470f418bf447fd007cd2ec2d45b4b0399a11904e9b4Jesse Wilson                0, server.takeRequest().getSequenceNumber());
1471f418bf447fd007cd2ec2d45b4b0399a11904e9b4Jesse Wilson    }
1472f418bf447fd007cd2ec2d45b4b0399a11904e9b4Jesse Wilson
1473f418bf447fd007cd2ec2d45b4b0399a11904e9b4Jesse Wilson    public void testConnectionCloseWithRedirect() throws IOException, InterruptedException {
1474f418bf447fd007cd2ec2d45b4b0399a11904e9b4Jesse Wilson        MockResponse response = new MockResponse()
1475f418bf447fd007cd2ec2d45b4b0399a11904e9b4Jesse Wilson                .setResponseCode(HttpURLConnection.HTTP_MOVED_TEMP)
1476f418bf447fd007cd2ec2d45b4b0399a11904e9b4Jesse Wilson                .addHeader("Location: /foo")
1477f418bf447fd007cd2ec2d45b4b0399a11904e9b4Jesse Wilson                .addHeader("Connection: close");
1478f418bf447fd007cd2ec2d45b4b0399a11904e9b4Jesse Wilson        server.enqueue(response);
1479f418bf447fd007cd2ec2d45b4b0399a11904e9b4Jesse Wilson        server.enqueue(new MockResponse().setBody("This is the new location!"));
1480f418bf447fd007cd2ec2d45b4b0399a11904e9b4Jesse Wilson        server.play();
1481f418bf447fd007cd2ec2d45b4b0399a11904e9b4Jesse Wilson
1482f418bf447fd007cd2ec2d45b4b0399a11904e9b4Jesse Wilson        URLConnection connection = server.getUrl("/").openConnection();
1483f418bf447fd007cd2ec2d45b4b0399a11904e9b4Jesse Wilson        assertEquals("This is the new location!",
1484f418bf447fd007cd2ec2d45b4b0399a11904e9b4Jesse Wilson                readAscii(connection.getInputStream(), Integer.MAX_VALUE));
1485f418bf447fd007cd2ec2d45b4b0399a11904e9b4Jesse Wilson
1486f418bf447fd007cd2ec2d45b4b0399a11904e9b4Jesse Wilson        assertEquals(0, server.takeRequest().getSequenceNumber());
1487f418bf447fd007cd2ec2d45b4b0399a11904e9b4Jesse Wilson        assertEquals("When connection: close is used, each request should get its own connection",
1488f418bf447fd007cd2ec2d45b4b0399a11904e9b4Jesse Wilson                0, server.takeRequest().getSequenceNumber());
1489f418bf447fd007cd2ec2d45b4b0399a11904e9b4Jesse Wilson    }
1490f418bf447fd007cd2ec2d45b4b0399a11904e9b4Jesse Wilson
149165d890eb22aeba9b009ee642ffd4fff48a6f98aeJesse Wilson    public void testResponseCodeDisagreesWithHeaders() throws IOException, InterruptedException {
149265d890eb22aeba9b009ee642ffd4fff48a6f98aeJesse Wilson        server.enqueue(new MockResponse()
149365d890eb22aeba9b009ee642ffd4fff48a6f98aeJesse Wilson                .setResponseCode(HttpURLConnection.HTTP_NO_CONTENT)
149465d890eb22aeba9b009ee642ffd4fff48a6f98aeJesse Wilson                .setBody("This body is not allowed!"));
149565d890eb22aeba9b009ee642ffd4fff48a6f98aeJesse Wilson        server.play();
149665d890eb22aeba9b009ee642ffd4fff48a6f98aeJesse Wilson
149765d890eb22aeba9b009ee642ffd4fff48a6f98aeJesse Wilson        URLConnection connection = server.getUrl("/").openConnection();
149865d890eb22aeba9b009ee642ffd4fff48a6f98aeJesse Wilson        assertEquals("This body is not allowed!",
149965d890eb22aeba9b009ee642ffd4fff48a6f98aeJesse Wilson                readAscii(connection.getInputStream(), Integer.MAX_VALUE));
150065d890eb22aeba9b009ee642ffd4fff48a6f98aeJesse Wilson    }
150165d890eb22aeba9b009ee642ffd4fff48a6f98aeJesse Wilson
1502ef66494dce45a0b7ec22ec3fb20c60096517a4e3Jesse Wilson    public void testSingleByteReadIsSigned() throws IOException {
1503ef66494dce45a0b7ec22ec3fb20c60096517a4e3Jesse Wilson        server.enqueue(new MockResponse().setBody(new byte[] { -2, -1 }));
1504ef66494dce45a0b7ec22ec3fb20c60096517a4e3Jesse Wilson        server.play();
1505ef66494dce45a0b7ec22ec3fb20c60096517a4e3Jesse Wilson
1506ef66494dce45a0b7ec22ec3fb20c60096517a4e3Jesse Wilson        URLConnection connection = server.getUrl("/").openConnection();
1507ef66494dce45a0b7ec22ec3fb20c60096517a4e3Jesse Wilson        InputStream in = connection.getInputStream();
1508ef66494dce45a0b7ec22ec3fb20c60096517a4e3Jesse Wilson        assertEquals(254, in.read());
1509ef66494dce45a0b7ec22ec3fb20c60096517a4e3Jesse Wilson        assertEquals(255, in.read());
1510ef66494dce45a0b7ec22ec3fb20c60096517a4e3Jesse Wilson        assertEquals(-1, in.read());
1511ef66494dce45a0b7ec22ec3fb20c60096517a4e3Jesse Wilson    }
1512ef66494dce45a0b7ec22ec3fb20c60096517a4e3Jesse Wilson
1513f29ad8a60254345d1943d1b3836482395a7c916fJesse Wilson    public void testFlushAfterStreamTransmittedWithChunkedEncoding() throws IOException {
1514f29ad8a60254345d1943d1b3836482395a7c916fJesse Wilson        testFlushAfterStreamTransmitted(TransferKind.CHUNKED);
1515f29ad8a60254345d1943d1b3836482395a7c916fJesse Wilson    }
1516f29ad8a60254345d1943d1b3836482395a7c916fJesse Wilson
1517f29ad8a60254345d1943d1b3836482395a7c916fJesse Wilson    public void testFlushAfterStreamTransmittedWithFixedLength() throws IOException {
1518f29ad8a60254345d1943d1b3836482395a7c916fJesse Wilson        testFlushAfterStreamTransmitted(TransferKind.FIXED_LENGTH);
1519f29ad8a60254345d1943d1b3836482395a7c916fJesse Wilson    }
1520f29ad8a60254345d1943d1b3836482395a7c916fJesse Wilson
1521f29ad8a60254345d1943d1b3836482395a7c916fJesse Wilson    public void testFlushAfterStreamTransmittedWithNoLengthHeaders() throws IOException {
1522f29ad8a60254345d1943d1b3836482395a7c916fJesse Wilson        testFlushAfterStreamTransmitted(TransferKind.END_OF_STREAM);
1523f29ad8a60254345d1943d1b3836482395a7c916fJesse Wilson    }
1524f29ad8a60254345d1943d1b3836482395a7c916fJesse Wilson
1525f29ad8a60254345d1943d1b3836482395a7c916fJesse Wilson    /**
1526f29ad8a60254345d1943d1b3836482395a7c916fJesse Wilson     * We explicitly permit apps to close the upload stream even after it has
1527f29ad8a60254345d1943d1b3836482395a7c916fJesse Wilson     * been transmitted.  We also permit flush so that buffered streams can
1528f29ad8a60254345d1943d1b3836482395a7c916fJesse Wilson     * do a no-op flush when they are closed. http://b/3038470
1529f29ad8a60254345d1943d1b3836482395a7c916fJesse Wilson     */
1530f29ad8a60254345d1943d1b3836482395a7c916fJesse Wilson    private void testFlushAfterStreamTransmitted(TransferKind transferKind) throws IOException {
1531f29ad8a60254345d1943d1b3836482395a7c916fJesse Wilson        server.enqueue(new MockResponse().setBody("abc"));
1532f29ad8a60254345d1943d1b3836482395a7c916fJesse Wilson        server.play();
1533f29ad8a60254345d1943d1b3836482395a7c916fJesse Wilson
1534f29ad8a60254345d1943d1b3836482395a7c916fJesse Wilson        HttpURLConnection connection = (HttpURLConnection) server.getUrl("/").openConnection();
1535f29ad8a60254345d1943d1b3836482395a7c916fJesse Wilson        connection.setDoOutput(true);
1536f29ad8a60254345d1943d1b3836482395a7c916fJesse Wilson        byte[] upload = "def".getBytes("UTF-8");
1537f29ad8a60254345d1943d1b3836482395a7c916fJesse Wilson
1538f29ad8a60254345d1943d1b3836482395a7c916fJesse Wilson        if (transferKind == TransferKind.CHUNKED) {
1539f29ad8a60254345d1943d1b3836482395a7c916fJesse Wilson            connection.setChunkedStreamingMode(0);
1540f29ad8a60254345d1943d1b3836482395a7c916fJesse Wilson        } else if (transferKind == TransferKind.FIXED_LENGTH) {
1541f29ad8a60254345d1943d1b3836482395a7c916fJesse Wilson            connection.setFixedLengthStreamingMode(upload.length);
1542f29ad8a60254345d1943d1b3836482395a7c916fJesse Wilson        }
1543f29ad8a60254345d1943d1b3836482395a7c916fJesse Wilson
1544f29ad8a60254345d1943d1b3836482395a7c916fJesse Wilson        OutputStream out = connection.getOutputStream();
1545f29ad8a60254345d1943d1b3836482395a7c916fJesse Wilson        out.write(upload);
1546f29ad8a60254345d1943d1b3836482395a7c916fJesse Wilson        assertEquals("abc", readAscii(connection.getInputStream(), Integer.MAX_VALUE));
1547f29ad8a60254345d1943d1b3836482395a7c916fJesse Wilson
1548f29ad8a60254345d1943d1b3836482395a7c916fJesse Wilson        out.flush(); // dubious but permitted
1549f29ad8a60254345d1943d1b3836482395a7c916fJesse Wilson        try {
1550f29ad8a60254345d1943d1b3836482395a7c916fJesse Wilson            out.write("ghi".getBytes("UTF-8"));
1551f29ad8a60254345d1943d1b3836482395a7c916fJesse Wilson            fail();
1552f29ad8a60254345d1943d1b3836482395a7c916fJesse Wilson        } catch (IOException expected) {
1553f29ad8a60254345d1943d1b3836482395a7c916fJesse Wilson        }
1554f29ad8a60254345d1943d1b3836482395a7c916fJesse Wilson    }
1555f29ad8a60254345d1943d1b3836482395a7c916fJesse Wilson
1556c6dae581716b9362a5c7f166c80a7f2b46ed1124Jesse Wilson    public void testGetHeadersThrows() throws IOException {
1557e942f46f10bb9384a1b186b3d7b74f9704c57090Jesse Wilson        server.enqueue(new MockResponse().setSocketPolicy(DISCONNECT_AT_START));
1558c6dae581716b9362a5c7f166c80a7f2b46ed1124Jesse Wilson        server.play();
1559c6dae581716b9362a5c7f166c80a7f2b46ed1124Jesse Wilson
1560c6dae581716b9362a5c7f166c80a7f2b46ed1124Jesse Wilson        HttpURLConnection connection = (HttpURLConnection) server.getUrl("/").openConnection();
1561c6dae581716b9362a5c7f166c80a7f2b46ed1124Jesse Wilson        try {
1562c6dae581716b9362a5c7f166c80a7f2b46ed1124Jesse Wilson            connection.getInputStream();
1563c6dae581716b9362a5c7f166c80a7f2b46ed1124Jesse Wilson            fail();
1564c6dae581716b9362a5c7f166c80a7f2b46ed1124Jesse Wilson        } catch (IOException expected) {
1565c6dae581716b9362a5c7f166c80a7f2b46ed1124Jesse Wilson        }
1566c6dae581716b9362a5c7f166c80a7f2b46ed1124Jesse Wilson
1567c6dae581716b9362a5c7f166c80a7f2b46ed1124Jesse Wilson        try {
1568c6dae581716b9362a5c7f166c80a7f2b46ed1124Jesse Wilson            connection.getInputStream();
1569c6dae581716b9362a5c7f166c80a7f2b46ed1124Jesse Wilson            fail();
1570f29ad8a60254345d1943d1b3836482395a7c916fJesse Wilson        } catch (IOException expected) {
1571f29ad8a60254345d1943d1b3836482395a7c916fJesse Wilson        }
1572f29ad8a60254345d1943d1b3836482395a7c916fJesse Wilson    }
1573f29ad8a60254345d1943d1b3836482395a7c916fJesse Wilson
1574b7f4d6c3968c372767b2510f38a3d506067aced6Jesse Wilson    public void testGetKeepAlive() throws Exception {
1575b7f4d6c3968c372767b2510f38a3d506067aced6Jesse Wilson        MockWebServer server = new MockWebServer();
1576b7f4d6c3968c372767b2510f38a3d506067aced6Jesse Wilson        server.enqueue(new MockResponse().setBody("ABC"));
1577b7f4d6c3968c372767b2510f38a3d506067aced6Jesse Wilson        server.play();
1578b7f4d6c3968c372767b2510f38a3d506067aced6Jesse Wilson
1579b7f4d6c3968c372767b2510f38a3d506067aced6Jesse Wilson        // The request should work once and then fail
1580b7f4d6c3968c372767b2510f38a3d506067aced6Jesse Wilson        URLConnection connection = server.getUrl("").openConnection();
1581b7f4d6c3968c372767b2510f38a3d506067aced6Jesse Wilson        InputStream input = connection.getInputStream();
1582b7f4d6c3968c372767b2510f38a3d506067aced6Jesse Wilson        assertEquals("ABC", readAscii(input, Integer.MAX_VALUE));
1583b7f4d6c3968c372767b2510f38a3d506067aced6Jesse Wilson        input.close();
1584b7f4d6c3968c372767b2510f38a3d506067aced6Jesse Wilson        try {
1585b7f4d6c3968c372767b2510f38a3d506067aced6Jesse Wilson            server.getUrl("").openConnection().getInputStream();
1586b7f4d6c3968c372767b2510f38a3d506067aced6Jesse Wilson            fail();
1587b7f4d6c3968c372767b2510f38a3d506067aced6Jesse Wilson        } catch (ConnectException expected) {
1588b7f4d6c3968c372767b2510f38a3d506067aced6Jesse Wilson        }
1589b7f4d6c3968c372767b2510f38a3d506067aced6Jesse Wilson    }
1590b7f4d6c3968c372767b2510f38a3d506067aced6Jesse Wilson
1591b7f4d6c3968c372767b2510f38a3d506067aced6Jesse Wilson    /**
1592d1b5e5da828434388e486a388710d21e4306dae0Jesse Wilson     * This test goes through the exhaustive set of interesting ASCII characters
1593d1b5e5da828434388e486a388710d21e4306dae0Jesse Wilson     * because most of those characters are interesting in some way according to
1594d1b5e5da828434388e486a388710d21e4306dae0Jesse Wilson     * RFC 2396 and RFC 2732. http://b/1158780
1595b7f4d6c3968c372767b2510f38a3d506067aced6Jesse Wilson     */
1596d1b5e5da828434388e486a388710d21e4306dae0Jesse Wilson    public void testLenientUrlToUri() throws Exception {
1597d1b5e5da828434388e486a388710d21e4306dae0Jesse Wilson        // alphanum
1598d1b5e5da828434388e486a388710d21e4306dae0Jesse Wilson        testUrlToUriMapping("abzABZ09", "abzABZ09", "abzABZ09", "abzABZ09", "abzABZ09");
1599d1b5e5da828434388e486a388710d21e4306dae0Jesse Wilson
1600d1b5e5da828434388e486a388710d21e4306dae0Jesse Wilson        // control characters
1601d1b5e5da828434388e486a388710d21e4306dae0Jesse Wilson        testUrlToUriMapping("\u0001", "%01", "%01", "%01", "%01");
1602d1b5e5da828434388e486a388710d21e4306dae0Jesse Wilson        testUrlToUriMapping("\u001f", "%1F", "%1F", "%1F", "%1F");
1603d1b5e5da828434388e486a388710d21e4306dae0Jesse Wilson
1604d1b5e5da828434388e486a388710d21e4306dae0Jesse Wilson        // ascii characters
1605d1b5e5da828434388e486a388710d21e4306dae0Jesse Wilson        testUrlToUriMapping("%20", "%20", "%20", "%20", "%20");
1606d1b5e5da828434388e486a388710d21e4306dae0Jesse Wilson        testUrlToUriMapping("%20", "%20", "%20", "%20", "%20");
1607d1b5e5da828434388e486a388710d21e4306dae0Jesse Wilson        testUrlToUriMapping(" ", "%20", "%20", "%20", "%20");
1608d1b5e5da828434388e486a388710d21e4306dae0Jesse Wilson        testUrlToUriMapping("!", "!", "!", "!", "!");
1609d1b5e5da828434388e486a388710d21e4306dae0Jesse Wilson        testUrlToUriMapping("\"", "%22", "%22", "%22", "%22");
1610d1b5e5da828434388e486a388710d21e4306dae0Jesse Wilson        testUrlToUriMapping("#", null, null, null, "%23");
1611d1b5e5da828434388e486a388710d21e4306dae0Jesse Wilson        testUrlToUriMapping("$", "$", "$", "$", "$");
1612d1b5e5da828434388e486a388710d21e4306dae0Jesse Wilson        testUrlToUriMapping("&", "&", "&", "&", "&");
1613d1b5e5da828434388e486a388710d21e4306dae0Jesse Wilson        testUrlToUriMapping("'", "'", "'", "'", "'");
1614d1b5e5da828434388e486a388710d21e4306dae0Jesse Wilson        testUrlToUriMapping("(", "(", "(", "(", "(");
1615d1b5e5da828434388e486a388710d21e4306dae0Jesse Wilson        testUrlToUriMapping(")", ")", ")", ")", ")");
1616d1b5e5da828434388e486a388710d21e4306dae0Jesse Wilson        testUrlToUriMapping("*", "*", "*", "*", "*");
1617d1b5e5da828434388e486a388710d21e4306dae0Jesse Wilson        testUrlToUriMapping("+", "+", "+", "+", "+");
1618d1b5e5da828434388e486a388710d21e4306dae0Jesse Wilson        testUrlToUriMapping(",", ",", ",", ",", ",");
1619d1b5e5da828434388e486a388710d21e4306dae0Jesse Wilson        testUrlToUriMapping("-", "-", "-", "-", "-");
1620d1b5e5da828434388e486a388710d21e4306dae0Jesse Wilson        testUrlToUriMapping(".", ".", ".", ".", ".");
1621d1b5e5da828434388e486a388710d21e4306dae0Jesse Wilson        testUrlToUriMapping("/", null, "/", "/", "/");
1622d1b5e5da828434388e486a388710d21e4306dae0Jesse Wilson        testUrlToUriMapping(":", null, ":", ":", ":");
1623d1b5e5da828434388e486a388710d21e4306dae0Jesse Wilson        testUrlToUriMapping(";", ";", ";", ";", ";");
1624d1b5e5da828434388e486a388710d21e4306dae0Jesse Wilson        testUrlToUriMapping("<", "%3C", "%3C", "%3C", "%3C");
1625d1b5e5da828434388e486a388710d21e4306dae0Jesse Wilson        testUrlToUriMapping("=", "=", "=", "=", "=");
1626d1b5e5da828434388e486a388710d21e4306dae0Jesse Wilson        testUrlToUriMapping(">", "%3E", "%3E", "%3E", "%3E");
1627d1b5e5da828434388e486a388710d21e4306dae0Jesse Wilson        testUrlToUriMapping("?", null, null, "?", "?");
1628d1b5e5da828434388e486a388710d21e4306dae0Jesse Wilson        testUrlToUriMapping("@", "@", "@", "@", "@");
1629d1b5e5da828434388e486a388710d21e4306dae0Jesse Wilson        testUrlToUriMapping("[", null, "%5B", null, "%5B");
1630d1b5e5da828434388e486a388710d21e4306dae0Jesse Wilson        testUrlToUriMapping("\\", "%5C", "%5C", "%5C", "%5C");
1631d1b5e5da828434388e486a388710d21e4306dae0Jesse Wilson        testUrlToUriMapping("]", null, "%5D", null, "%5D");
1632d1b5e5da828434388e486a388710d21e4306dae0Jesse Wilson        testUrlToUriMapping("^", "%5E", "%5E", "%5E", "%5E");
1633d1b5e5da828434388e486a388710d21e4306dae0Jesse Wilson        testUrlToUriMapping("_", "_", "_", "_", "_");
1634d1b5e5da828434388e486a388710d21e4306dae0Jesse Wilson        testUrlToUriMapping("`", "%60", "%60", "%60", "%60");
1635d1b5e5da828434388e486a388710d21e4306dae0Jesse Wilson        testUrlToUriMapping("{", "%7B", "%7B", "%7B", "%7B");
1636d1b5e5da828434388e486a388710d21e4306dae0Jesse Wilson        testUrlToUriMapping("|", "%7C", "%7C", "%7C", "%7C");
1637d1b5e5da828434388e486a388710d21e4306dae0Jesse Wilson        testUrlToUriMapping("}", "%7D", "%7D", "%7D", "%7D");
1638d1b5e5da828434388e486a388710d21e4306dae0Jesse Wilson        testUrlToUriMapping("~", "~", "~", "~", "~");
1639d1b5e5da828434388e486a388710d21e4306dae0Jesse Wilson        testUrlToUriMapping("~", "~", "~", "~", "~");
1640d1b5e5da828434388e486a388710d21e4306dae0Jesse Wilson        testUrlToUriMapping("\u007f", "%7F", "%7F", "%7F", "%7F");
1641d1b5e5da828434388e486a388710d21e4306dae0Jesse Wilson
1642d1b5e5da828434388e486a388710d21e4306dae0Jesse Wilson        // beyond ascii
1643d1b5e5da828434388e486a388710d21e4306dae0Jesse Wilson        testUrlToUriMapping("\u0080", "%C2%80", "%C2%80", "%C2%80", "%C2%80");
1644d1b5e5da828434388e486a388710d21e4306dae0Jesse Wilson        testUrlToUriMapping("\u20ac", "\u20ac", "\u20ac", "\u20ac", "\u20ac");
164532559028b14b9b321b10eede050afd554a376569Jesse Wilson        testUrlToUriMapping("\ud842\udf9f",
164632559028b14b9b321b10eede050afd554a376569Jesse Wilson                "\ud842\udf9f", "\ud842\udf9f", "\ud842\udf9f", "\ud842\udf9f");
1647d1b5e5da828434388e486a388710d21e4306dae0Jesse Wilson    }
1648d1b5e5da828434388e486a388710d21e4306dae0Jesse Wilson
1649d1b5e5da828434388e486a388710d21e4306dae0Jesse Wilson    public void testLenientUrlToUriNul() throws Exception {
1650d1b5e5da828434388e486a388710d21e4306dae0Jesse Wilson        testUrlToUriMapping("\u0000", "%00", "%00", "%00", "%00"); // RI fails this
1651d1b5e5da828434388e486a388710d21e4306dae0Jesse Wilson    }
1652d1b5e5da828434388e486a388710d21e4306dae0Jesse Wilson
1653d1b5e5da828434388e486a388710d21e4306dae0Jesse Wilson    private void testUrlToUriMapping(String string, String asAuthority, String asFile,
1654d1b5e5da828434388e486a388710d21e4306dae0Jesse Wilson            String asQuery, String asFragment) throws Exception {
1655d1b5e5da828434388e486a388710d21e4306dae0Jesse Wilson        if (asAuthority != null) {
1656d1b5e5da828434388e486a388710d21e4306dae0Jesse Wilson            assertEquals("http://host" + asAuthority + ".tld/",
1657d1b5e5da828434388e486a388710d21e4306dae0Jesse Wilson                    backdoorUrlToUri(new URL("http://host" + string + ".tld/")).toString());
1658d1b5e5da828434388e486a388710d21e4306dae0Jesse Wilson        }
1659d1b5e5da828434388e486a388710d21e4306dae0Jesse Wilson        if (asFile != null) {
1660d1b5e5da828434388e486a388710d21e4306dae0Jesse Wilson            assertEquals("http://host.tld/file" + asFile + "/",
1661d1b5e5da828434388e486a388710d21e4306dae0Jesse Wilson                    backdoorUrlToUri(new URL("http://host.tld/file" + string + "/")).toString());
1662d1b5e5da828434388e486a388710d21e4306dae0Jesse Wilson        }
1663d1b5e5da828434388e486a388710d21e4306dae0Jesse Wilson        if (asQuery != null) {
1664d1b5e5da828434388e486a388710d21e4306dae0Jesse Wilson            assertEquals("http://host.tld/file?q" + asQuery + "=x",
1665d1b5e5da828434388e486a388710d21e4306dae0Jesse Wilson                    backdoorUrlToUri(new URL("http://host.tld/file?q" + string + "=x")).toString());
1666d1b5e5da828434388e486a388710d21e4306dae0Jesse Wilson        }
1667d1b5e5da828434388e486a388710d21e4306dae0Jesse Wilson        assertEquals("http://host.tld/file#" + asFragment + "-x",
1668d1b5e5da828434388e486a388710d21e4306dae0Jesse Wilson                backdoorUrlToUri(new URL("http://host.tld/file#" + asFragment + "-x")).toString());
1669d1b5e5da828434388e486a388710d21e4306dae0Jesse Wilson    }
1670b7f4d6c3968c372767b2510f38a3d506067aced6Jesse Wilson
1671d1b5e5da828434388e486a388710d21e4306dae0Jesse Wilson    /**
1672d1b5e5da828434388e486a388710d21e4306dae0Jesse Wilson     * Exercises HttpURLConnection to convert URL to a URI. Unlike URL#toURI,
1673d1b5e5da828434388e486a388710d21e4306dae0Jesse Wilson     * HttpURLConnection recovers from URLs with unescaped but unsupported URI
1674d1b5e5da828434388e486a388710d21e4306dae0Jesse Wilson     * characters like '{' and '|' by escaping these characters.
1675d1b5e5da828434388e486a388710d21e4306dae0Jesse Wilson     */
1676d1b5e5da828434388e486a388710d21e4306dae0Jesse Wilson    private URI backdoorUrlToUri(URL url) throws Exception {
1677d1b5e5da828434388e486a388710d21e4306dae0Jesse Wilson        final AtomicReference<URI> uriReference = new AtomicReference<URI>();
1678d1b5e5da828434388e486a388710d21e4306dae0Jesse Wilson
1679d1b5e5da828434388e486a388710d21e4306dae0Jesse Wilson        ResponseCache.setDefault(new ResponseCache() {
1680d1b5e5da828434388e486a388710d21e4306dae0Jesse Wilson            @Override public CacheRequest put(URI uri, URLConnection connection) throws IOException {
1681d1b5e5da828434388e486a388710d21e4306dae0Jesse Wilson                return null;
1682d1b5e5da828434388e486a388710d21e4306dae0Jesse Wilson            }
1683d1b5e5da828434388e486a388710d21e4306dae0Jesse Wilson            @Override public CacheResponse get(URI uri, String requestMethod,
1684d1b5e5da828434388e486a388710d21e4306dae0Jesse Wilson                    Map<String, List<String>> requestHeaders) throws IOException {
1685d1b5e5da828434388e486a388710d21e4306dae0Jesse Wilson                uriReference.set(uri);
1686d1b5e5da828434388e486a388710d21e4306dae0Jesse Wilson                throw new UnsupportedOperationException();
1687d1b5e5da828434388e486a388710d21e4306dae0Jesse Wilson            }
1688d1b5e5da828434388e486a388710d21e4306dae0Jesse Wilson        });
1689d1b5e5da828434388e486a388710d21e4306dae0Jesse Wilson
1690d1b5e5da828434388e486a388710d21e4306dae0Jesse Wilson        try {
1691d1b5e5da828434388e486a388710d21e4306dae0Jesse Wilson            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
1692d1b5e5da828434388e486a388710d21e4306dae0Jesse Wilson            connection.getResponseCode();
1693d1b5e5da828434388e486a388710d21e4306dae0Jesse Wilson        } catch (Exception expected) {
1694d1b5e5da828434388e486a388710d21e4306dae0Jesse Wilson        }
1695d1b5e5da828434388e486a388710d21e4306dae0Jesse Wilson
1696d1b5e5da828434388e486a388710d21e4306dae0Jesse Wilson        return uriReference.get();
1697b7f4d6c3968c372767b2510f38a3d506067aced6Jesse Wilson    }
1698b7f4d6c3968c372767b2510f38a3d506067aced6Jesse Wilson
1699afd9b157f467b7c4f2f0b5592dca72f18d844602Jesse Wilson    /**
1700afd9b157f467b7c4f2f0b5592dca72f18d844602Jesse Wilson     * Don't explode if the cache returns a null body. http://b/3373699
1701afd9b157f467b7c4f2f0b5592dca72f18d844602Jesse Wilson     */
1702afd9b157f467b7c4f2f0b5592dca72f18d844602Jesse Wilson    public void testResponseCacheReturnsNullOutputStream() throws Exception {
1703afd9b157f467b7c4f2f0b5592dca72f18d844602Jesse Wilson        final AtomicBoolean aborted = new AtomicBoolean();
1704afd9b157f467b7c4f2f0b5592dca72f18d844602Jesse Wilson        ResponseCache.setDefault(new ResponseCache() {
1705afd9b157f467b7c4f2f0b5592dca72f18d844602Jesse Wilson            @Override public CacheResponse get(URI uri, String requestMethod,
1706afd9b157f467b7c4f2f0b5592dca72f18d844602Jesse Wilson                    Map<String, List<String>> requestHeaders) throws IOException {
1707afd9b157f467b7c4f2f0b5592dca72f18d844602Jesse Wilson                return null;
1708afd9b157f467b7c4f2f0b5592dca72f18d844602Jesse Wilson            }
1709afd9b157f467b7c4f2f0b5592dca72f18d844602Jesse Wilson            @Override public CacheRequest put(URI uri, URLConnection connection) throws IOException {
1710afd9b157f467b7c4f2f0b5592dca72f18d844602Jesse Wilson                return new CacheRequest() {
1711afd9b157f467b7c4f2f0b5592dca72f18d844602Jesse Wilson                    @Override public void abort() {
1712afd9b157f467b7c4f2f0b5592dca72f18d844602Jesse Wilson                        aborted.set(true);
1713afd9b157f467b7c4f2f0b5592dca72f18d844602Jesse Wilson                    }
1714afd9b157f467b7c4f2f0b5592dca72f18d844602Jesse Wilson                    @Override public OutputStream getBody() throws IOException {
1715afd9b157f467b7c4f2f0b5592dca72f18d844602Jesse Wilson                        return null;
1716afd9b157f467b7c4f2f0b5592dca72f18d844602Jesse Wilson                    }
1717afd9b157f467b7c4f2f0b5592dca72f18d844602Jesse Wilson                };
1718afd9b157f467b7c4f2f0b5592dca72f18d844602Jesse Wilson            }
1719afd9b157f467b7c4f2f0b5592dca72f18d844602Jesse Wilson        });
1720afd9b157f467b7c4f2f0b5592dca72f18d844602Jesse Wilson
1721afd9b157f467b7c4f2f0b5592dca72f18d844602Jesse Wilson        server.enqueue(new MockResponse().setBody("abcdef"));
1722afd9b157f467b7c4f2f0b5592dca72f18d844602Jesse Wilson        server.play();
1723afd9b157f467b7c4f2f0b5592dca72f18d844602Jesse Wilson
1724afd9b157f467b7c4f2f0b5592dca72f18d844602Jesse Wilson        HttpURLConnection connection = (HttpURLConnection) server.getUrl("/").openConnection();
1725afd9b157f467b7c4f2f0b5592dca72f18d844602Jesse Wilson        InputStream in = connection.getInputStream();
1726afd9b157f467b7c4f2f0b5592dca72f18d844602Jesse Wilson        assertEquals("abc", readAscii(in, 3));
1727afd9b157f467b7c4f2f0b5592dca72f18d844602Jesse Wilson        in.close();
1728afd9b157f467b7c4f2f0b5592dca72f18d844602Jesse Wilson        assertFalse(aborted.get()); // The best behavior is ambiguous, but RI 6 doesn't abort here
1729afd9b157f467b7c4f2f0b5592dca72f18d844602Jesse Wilson    }
1730d1b5e5da828434388e486a388710d21e4306dae0Jesse Wilson
17315e8b5a55eda914b67c62b4e77152922d5c77eb68Jesse Wilson
17325e8b5a55eda914b67c62b4e77152922d5c77eb68Jesse Wilson    /**
17335e8b5a55eda914b67c62b4e77152922d5c77eb68Jesse Wilson     * http://code.google.com/p/android/issues/detail?id=14562
17345e8b5a55eda914b67c62b4e77152922d5c77eb68Jesse Wilson     */
17355e8b5a55eda914b67c62b4e77152922d5c77eb68Jesse Wilson    public void testReadAfterLastByte() throws Exception {
17365e8b5a55eda914b67c62b4e77152922d5c77eb68Jesse Wilson        server.enqueue(new MockResponse()
17375e8b5a55eda914b67c62b4e77152922d5c77eb68Jesse Wilson                .setBody("ABC")
17385e8b5a55eda914b67c62b4e77152922d5c77eb68Jesse Wilson                .clearHeaders()
17395e8b5a55eda914b67c62b4e77152922d5c77eb68Jesse Wilson                .addHeader("Connection: close")
17405e8b5a55eda914b67c62b4e77152922d5c77eb68Jesse Wilson                .setSocketPolicy(SocketPolicy.DISCONNECT_AT_END));
17415e8b5a55eda914b67c62b4e77152922d5c77eb68Jesse Wilson        server.play();
17425e8b5a55eda914b67c62b4e77152922d5c77eb68Jesse Wilson
17435e8b5a55eda914b67c62b4e77152922d5c77eb68Jesse Wilson        HttpURLConnection connection = (HttpURLConnection) server.getUrl("/").openConnection();
17445e8b5a55eda914b67c62b4e77152922d5c77eb68Jesse Wilson        InputStream in = connection.getInputStream();
17455e8b5a55eda914b67c62b4e77152922d5c77eb68Jesse Wilson        assertEquals("ABC", readAscii(in, 3));
17465e8b5a55eda914b67c62b4e77152922d5c77eb68Jesse Wilson        assertEquals(-1, in.read());
1747bc4c79c6a2059003f695f7ad204de36700e8d701Jesse Wilson        assertEquals(-1, in.read()); // throws IOException in Gingerbread
1748bc4c79c6a2059003f695f7ad204de36700e8d701Jesse Wilson    }
1749bc4c79c6a2059003f695f7ad204de36700e8d701Jesse Wilson
1750ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson    public void testGetContent() throws Exception {
1751ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson        server.enqueue(new MockResponse().setBody("A"));
1752ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson        server.play();
1753ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson        HttpURLConnection connection = (HttpURLConnection) server.getUrl("/").openConnection();
1754ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson        InputStream in = (InputStream) connection.getContent();
1755ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson        assertEquals("A", readAscii(in, Integer.MAX_VALUE));
1756ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson    }
1757ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson
1758ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson    public void testGetContentOfType() throws Exception {
1759ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson        server.enqueue(new MockResponse().setBody("A"));
1760ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson        server.play();
1761ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson        HttpURLConnection connection = (HttpURLConnection) server.getUrl("/").openConnection();
1762ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson        try {
1763ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson            connection.getContent(null);
1764ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson            fail();
1765ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson        } catch (NullPointerException expected) {
1766ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson        }
1767ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson        try {
1768ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson            connection.getContent(new Class[] { null });
1769ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson            fail();
1770ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson        } catch (NullPointerException expected) {
1771ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson        }
1772ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson        assertNull(connection.getContent(new Class[] { getClass() }));
1773ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson        connection.disconnect();
1774ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson    }
1775ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson
1776ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson    public void testGetOutputStreamOnGetFails() throws Exception {
1777ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson        server.enqueue(new MockResponse());
1778ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson        server.play();
1779ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson        HttpURLConnection connection = (HttpURLConnection) server.getUrl("/").openConnection();
1780ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson        try {
1781ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson            connection.getOutputStream();
1782ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson            fail();
1783ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson        } catch (ProtocolException expected) {
1784ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson        }
1785ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson    }
1786ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson
1787ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson    public void testGetOutputAfterGetInputStreamFails() throws Exception {
1788ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson        server.enqueue(new MockResponse());
1789ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson        server.play();
1790ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson        HttpURLConnection connection = (HttpURLConnection) server.getUrl("/").openConnection();
1791ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson        connection.setDoOutput(true);
1792ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson        try {
1793ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson            connection.getInputStream();
1794ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson            connection.getOutputStream();
1795ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson            fail();
1796ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson        } catch (ProtocolException expected) {
1797ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson        }
1798ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson    }
1799ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson
1800ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson    public void testSetDoOutputOrDoInputAfterConnectFails() throws Exception {
1801ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson        server.enqueue(new MockResponse());
1802ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson        server.play();
1803ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson        HttpURLConnection connection = (HttpURLConnection) server.getUrl("/").openConnection();
1804ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson        connection.connect();
1805ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson        try {
1806ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson            connection.setDoOutput(true);
1807ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson            fail();
1808ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson        } catch (IllegalStateException expected) {
1809ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson        }
1810ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson        try {
1811ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson            connection.setDoInput(true);
1812ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson            fail();
1813ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson        } catch (IllegalStateException expected) {
1814ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson        }
1815ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson        connection.disconnect();
1816ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson    }
1817ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson
1818ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson    public void testClientSendsContentLength() throws Exception {
1819ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson        server.enqueue(new MockResponse().setBody("A"));
1820ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson        server.play();
1821ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson        HttpURLConnection connection = (HttpURLConnection) server.getUrl("/").openConnection();
1822ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson        connection.setDoOutput(true);
1823ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson        OutputStream out = connection.getOutputStream();
1824ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson        out.write(new byte[] { 'A', 'B', 'C' });
1825ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson        out.close();
1826ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson        assertEquals("A", readAscii(connection.getInputStream(), Integer.MAX_VALUE));
1827ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson        RecordedRequest request = server.takeRequest();
1828ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson        assertContains(request.getHeaders(), "Content-Length: 3");
1829ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson    }
1830ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson
1831ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson    public void testGetContentLengthConnects() throws Exception {
1832ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson        server.enqueue(new MockResponse().setBody("ABC"));
1833ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson        server.play();
1834ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson        HttpURLConnection connection = (HttpURLConnection) server.getUrl("/").openConnection();
1835ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson        assertEquals(3, connection.getContentLength());
1836ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson        connection.disconnect();
1837ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson    }
1838ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson
1839ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson    public void testGetContentTypeConnects() throws Exception {
1840ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson        server.enqueue(new MockResponse()
1841ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson                .addHeader("Content-Type: text/plain")
1842ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson                .setBody("ABC"));
1843ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson        server.play();
1844ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson        HttpURLConnection connection = (HttpURLConnection) server.getUrl("/").openConnection();
1845ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson        assertEquals("text/plain", connection.getContentType());
1846ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson        connection.disconnect();
1847ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson    }
1848ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson
1849ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson    public void testGetContentEncodingConnects() throws Exception {
1850ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson        server.enqueue(new MockResponse()
1851ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson                .addHeader("Content-Encoding: identity")
1852ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson                .setBody("ABC"));
1853ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson        server.play();
1854ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson        HttpURLConnection connection = (HttpURLConnection) server.getUrl("/").openConnection();
1855ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson        assertEquals("identity", connection.getContentEncoding());
1856ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson        connection.disconnect();
1857ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson    }
1858ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson
18595292410e4ebf7fb5149eefd2f52fcb94c46690a6Jesse Wilson    // http://b/4361656
18605292410e4ebf7fb5149eefd2f52fcb94c46690a6Jesse Wilson    public void testUrlContainsQueryButNoPath() throws Exception {
18615292410e4ebf7fb5149eefd2f52fcb94c46690a6Jesse Wilson        server.enqueue(new MockResponse().setBody("A"));
18625292410e4ebf7fb5149eefd2f52fcb94c46690a6Jesse Wilson        server.play();
18635292410e4ebf7fb5149eefd2f52fcb94c46690a6Jesse Wilson        URL url = new URL("http", server.getHostName(), server.getPort(), "?query");
18645292410e4ebf7fb5149eefd2f52fcb94c46690a6Jesse Wilson        assertEquals("A", readAscii(url.openConnection().getInputStream(), Integer.MAX_VALUE));
18655292410e4ebf7fb5149eefd2f52fcb94c46690a6Jesse Wilson        RecordedRequest request = server.takeRequest();
18665292410e4ebf7fb5149eefd2f52fcb94c46690a6Jesse Wilson        assertEquals("GET /?query HTTP/1.1", request.getRequestLine());
18675292410e4ebf7fb5149eefd2f52fcb94c46690a6Jesse Wilson    }
18685292410e4ebf7fb5149eefd2f52fcb94c46690a6Jesse Wilson
186925a753691a80186cd4d7086b12c0e52225d95897Jesse Wilson    // http://code.google.com/p/android/issues/detail?id=20442
187025a753691a80186cd4d7086b12c0e52225d95897Jesse Wilson    public void testInputStreamAvailableWithChunkedEncoding() throws Exception {
187125a753691a80186cd4d7086b12c0e52225d95897Jesse Wilson        testInputStreamAvailable(TransferKind.CHUNKED);
187225a753691a80186cd4d7086b12c0e52225d95897Jesse Wilson    }
187325a753691a80186cd4d7086b12c0e52225d95897Jesse Wilson
187425a753691a80186cd4d7086b12c0e52225d95897Jesse Wilson    public void testInputStreamAvailableWithContentLengthHeader() throws Exception {
187525a753691a80186cd4d7086b12c0e52225d95897Jesse Wilson        testInputStreamAvailable(TransferKind.FIXED_LENGTH);
187625a753691a80186cd4d7086b12c0e52225d95897Jesse Wilson    }
187725a753691a80186cd4d7086b12c0e52225d95897Jesse Wilson
187825a753691a80186cd4d7086b12c0e52225d95897Jesse Wilson    public void testInputStreamAvailableWithNoLengthHeaders() throws Exception {
187925a753691a80186cd4d7086b12c0e52225d95897Jesse Wilson        testInputStreamAvailable(TransferKind.END_OF_STREAM);
188025a753691a80186cd4d7086b12c0e52225d95897Jesse Wilson    }
188125a753691a80186cd4d7086b12c0e52225d95897Jesse Wilson
188225a753691a80186cd4d7086b12c0e52225d95897Jesse Wilson    private void testInputStreamAvailable(TransferKind transferKind) throws IOException {
188325a753691a80186cd4d7086b12c0e52225d95897Jesse Wilson        String body = "ABCDEFGH";
188425a753691a80186cd4d7086b12c0e52225d95897Jesse Wilson        MockResponse response = new MockResponse();
188525a753691a80186cd4d7086b12c0e52225d95897Jesse Wilson        transferKind.setBody(response, body, 4);
188625a753691a80186cd4d7086b12c0e52225d95897Jesse Wilson        server.enqueue(response);
188725a753691a80186cd4d7086b12c0e52225d95897Jesse Wilson        server.play();
188825a753691a80186cd4d7086b12c0e52225d95897Jesse Wilson        URLConnection connection = server.getUrl("/").openConnection();
188925a753691a80186cd4d7086b12c0e52225d95897Jesse Wilson        InputStream in = connection.getInputStream();
189025a753691a80186cd4d7086b12c0e52225d95897Jesse Wilson        for (int i = 0; i < body.length(); i++) {
189125a753691a80186cd4d7086b12c0e52225d95897Jesse Wilson            assertTrue(in.available() >= 0);
189225a753691a80186cd4d7086b12c0e52225d95897Jesse Wilson            assertEquals(body.charAt(i), in.read());
189325a753691a80186cd4d7086b12c0e52225d95897Jesse Wilson        }
189425a753691a80186cd4d7086b12c0e52225d95897Jesse Wilson        assertEquals(0, in.available());
189525a753691a80186cd4d7086b12c0e52225d95897Jesse Wilson        assertEquals(-1, in.read());
189625a753691a80186cd4d7086b12c0e52225d95897Jesse Wilson    }
189725a753691a80186cd4d7086b12c0e52225d95897Jesse Wilson
1898a468471e8ccc2f642d5b2ae3c75873a74267ece2Jesse Wilson    public void testInspectSslBeforeConnect() throws Exception {
1899a468471e8ccc2f642d5b2ae3c75873a74267ece2Jesse Wilson        TestSSLContext testSSLContext = TestSSLContext.create();
1900a468471e8ccc2f642d5b2ae3c75873a74267ece2Jesse Wilson        server.useHttps(testSSLContext.serverContext.getSocketFactory(), false);
1901a468471e8ccc2f642d5b2ae3c75873a74267ece2Jesse Wilson        server.enqueue(new MockResponse());
1902a468471e8ccc2f642d5b2ae3c75873a74267ece2Jesse Wilson        server.play();
1903a468471e8ccc2f642d5b2ae3c75873a74267ece2Jesse Wilson
1904a468471e8ccc2f642d5b2ae3c75873a74267ece2Jesse Wilson        HttpsURLConnection connection = (HttpsURLConnection) server.getUrl("/").openConnection();
1905a468471e8ccc2f642d5b2ae3c75873a74267ece2Jesse Wilson        connection.setSSLSocketFactory(testSSLContext.clientContext.getSocketFactory());
1906a468471e8ccc2f642d5b2ae3c75873a74267ece2Jesse Wilson        assertNotNull(connection.getHostnameVerifier());
1907a468471e8ccc2f642d5b2ae3c75873a74267ece2Jesse Wilson        try {
1908a468471e8ccc2f642d5b2ae3c75873a74267ece2Jesse Wilson            connection.getLocalCertificates();
1909a468471e8ccc2f642d5b2ae3c75873a74267ece2Jesse Wilson            fail();
1910a468471e8ccc2f642d5b2ae3c75873a74267ece2Jesse Wilson        } catch (IllegalStateException expected) {
1911a468471e8ccc2f642d5b2ae3c75873a74267ece2Jesse Wilson        }
1912a468471e8ccc2f642d5b2ae3c75873a74267ece2Jesse Wilson        try {
1913a468471e8ccc2f642d5b2ae3c75873a74267ece2Jesse Wilson            connection.getServerCertificates();
1914a468471e8ccc2f642d5b2ae3c75873a74267ece2Jesse Wilson            fail();
1915a468471e8ccc2f642d5b2ae3c75873a74267ece2Jesse Wilson        } catch (IllegalStateException expected) {
1916a468471e8ccc2f642d5b2ae3c75873a74267ece2Jesse Wilson        }
1917a468471e8ccc2f642d5b2ae3c75873a74267ece2Jesse Wilson        try {
1918a468471e8ccc2f642d5b2ae3c75873a74267ece2Jesse Wilson            connection.getCipherSuite();
1919a468471e8ccc2f642d5b2ae3c75873a74267ece2Jesse Wilson            fail();
1920a468471e8ccc2f642d5b2ae3c75873a74267ece2Jesse Wilson        } catch (IllegalStateException expected) {
1921a468471e8ccc2f642d5b2ae3c75873a74267ece2Jesse Wilson        }
1922a468471e8ccc2f642d5b2ae3c75873a74267ece2Jesse Wilson        try {
1923a468471e8ccc2f642d5b2ae3c75873a74267ece2Jesse Wilson            connection.getPeerPrincipal();
1924a468471e8ccc2f642d5b2ae3c75873a74267ece2Jesse Wilson            fail();
1925a468471e8ccc2f642d5b2ae3c75873a74267ece2Jesse Wilson        } catch (IllegalStateException expected) {
1926a468471e8ccc2f642d5b2ae3c75873a74267ece2Jesse Wilson        }
1927a468471e8ccc2f642d5b2ae3c75873a74267ece2Jesse Wilson    }
1928a468471e8ccc2f642d5b2ae3c75873a74267ece2Jesse Wilson
1929a468471e8ccc2f642d5b2ae3c75873a74267ece2Jesse Wilson    /**
1930a468471e8ccc2f642d5b2ae3c75873a74267ece2Jesse Wilson     * Test that we can inspect the SSL session after connect().
1931a468471e8ccc2f642d5b2ae3c75873a74267ece2Jesse Wilson     * http://code.google.com/p/android/issues/detail?id=24431
1932a468471e8ccc2f642d5b2ae3c75873a74267ece2Jesse Wilson     */
1933a468471e8ccc2f642d5b2ae3c75873a74267ece2Jesse Wilson    public void testInspectSslAfterConnect() throws Exception {
1934a468471e8ccc2f642d5b2ae3c75873a74267ece2Jesse Wilson        TestSSLContext testSSLContext = TestSSLContext.create();
1935a468471e8ccc2f642d5b2ae3c75873a74267ece2Jesse Wilson        server.useHttps(testSSLContext.serverContext.getSocketFactory(), false);
1936a468471e8ccc2f642d5b2ae3c75873a74267ece2Jesse Wilson        server.enqueue(new MockResponse());
1937a468471e8ccc2f642d5b2ae3c75873a74267ece2Jesse Wilson        server.play();
1938a468471e8ccc2f642d5b2ae3c75873a74267ece2Jesse Wilson
1939a468471e8ccc2f642d5b2ae3c75873a74267ece2Jesse Wilson        HttpsURLConnection connection = (HttpsURLConnection) server.getUrl("/").openConnection();
1940a468471e8ccc2f642d5b2ae3c75873a74267ece2Jesse Wilson        connection.setSSLSocketFactory(testSSLContext.clientContext.getSocketFactory());
1941a468471e8ccc2f642d5b2ae3c75873a74267ece2Jesse Wilson        connection.connect();
1942a468471e8ccc2f642d5b2ae3c75873a74267ece2Jesse Wilson        assertNotNull(connection.getHostnameVerifier());
1943a468471e8ccc2f642d5b2ae3c75873a74267ece2Jesse Wilson        assertNull(connection.getLocalCertificates());
1944a468471e8ccc2f642d5b2ae3c75873a74267ece2Jesse Wilson        assertNotNull(connection.getServerCertificates());
1945a468471e8ccc2f642d5b2ae3c75873a74267ece2Jesse Wilson        assertNotNull(connection.getCipherSuite());
1946a468471e8ccc2f642d5b2ae3c75873a74267ece2Jesse Wilson        assertNotNull(connection.getPeerPrincipal());
1947a468471e8ccc2f642d5b2ae3c75873a74267ece2Jesse Wilson    }
1948a468471e8ccc2f642d5b2ae3c75873a74267ece2Jesse Wilson
1949bc4c79c6a2059003f695f7ad204de36700e8d701Jesse Wilson    /**
19500c59055dd24e1659f85d9ff7e2148883f663bd62Jesse Wilson     * Returns a gzipped copy of {@code bytes}.
1951deb236fb06f2a14861e7d40dea959f181cd5cf28Jesse Wilson     */
1952deb236fb06f2a14861e7d40dea959f181cd5cf28Jesse Wilson    public byte[] gzip(byte[] bytes) throws IOException {
1953deb236fb06f2a14861e7d40dea959f181cd5cf28Jesse Wilson        ByteArrayOutputStream bytesOut = new ByteArrayOutputStream();
1954deb236fb06f2a14861e7d40dea959f181cd5cf28Jesse Wilson        OutputStream gzippedOut = new GZIPOutputStream(bytesOut);
1955deb236fb06f2a14861e7d40dea959f181cd5cf28Jesse Wilson        gzippedOut.write(bytes);
1956deb236fb06f2a14861e7d40dea959f181cd5cf28Jesse Wilson        gzippedOut.close();
1957deb236fb06f2a14861e7d40dea959f181cd5cf28Jesse Wilson        return bytesOut.toByteArray();
1958deb236fb06f2a14861e7d40dea959f181cd5cf28Jesse Wilson    }
1959deb236fb06f2a14861e7d40dea959f181cd5cf28Jesse Wilson
1960c8977f474b30c5f3807398859a6b16687af6fc7bJesse Wilson    /**
1961c8977f474b30c5f3807398859a6b16687af6fc7bJesse Wilson     * Reads at most {@code limit} characters from {@code in} and asserts that
1962c8977f474b30c5f3807398859a6b16687af6fc7bJesse Wilson     * content equals {@code expected}.
1963c8977f474b30c5f3807398859a6b16687af6fc7bJesse Wilson     */
1964c8977f474b30c5f3807398859a6b16687af6fc7bJesse Wilson    private void assertContent(String expected, URLConnection connection, int limit)
1965c8977f474b30c5f3807398859a6b16687af6fc7bJesse Wilson            throws IOException {
1966f02c695ed03e708623d9365dec26d533356ef2d0Brian Carlstrom        connection.connect();
196751e468abf2628ce964d3657042f3ac8f2c947504Jesse Wilson        assertEquals(expected, readAscii(connection.getInputStream(), limit));
1968c8977f474b30c5f3807398859a6b16687af6fc7bJesse Wilson        ((HttpURLConnection) connection).disconnect();
1969c8977f474b30c5f3807398859a6b16687af6fc7bJesse Wilson    }
1970c8977f474b30c5f3807398859a6b16687af6fc7bJesse Wilson
1971c8977f474b30c5f3807398859a6b16687af6fc7bJesse Wilson    private void assertContent(String expected, URLConnection connection) throws IOException {
1972c8977f474b30c5f3807398859a6b16687af6fc7bJesse Wilson        assertContent(expected, connection, Integer.MAX_VALUE);
1973c8977f474b30c5f3807398859a6b16687af6fc7bJesse Wilson    }
1974c8977f474b30c5f3807398859a6b16687af6fc7bJesse Wilson
197560476787f0e0f052366d8031c74e507ffd3d16a3Jesse Wilson    private void assertContains(List<String> headers, String header) {
197660476787f0e0f052366d8031c74e507ffd3d16a3Jesse Wilson        assertTrue(headers.toString(), headers.contains(header));
197760476787f0e0f052366d8031c74e507ffd3d16a3Jesse Wilson    }
197851e468abf2628ce964d3657042f3ac8f2c947504Jesse Wilson
1979ffd579b668428272b78f5c6c64f9c89766f37c1aJesse Wilson    private void assertContainsNoneMatching(List<String> headers, String pattern) {
1980ffd579b668428272b78f5c6c64f9c89766f37c1aJesse Wilson        for (String header : headers) {
1981ffd579b668428272b78f5c6c64f9c89766f37c1aJesse Wilson            if (header.matches(pattern)) {
1982ffd579b668428272b78f5c6c64f9c89766f37c1aJesse Wilson                fail("Header " + header + " matches " + pattern);
1983ffd579b668428272b78f5c6c64f9c89766f37c1aJesse Wilson            }
1984ffd579b668428272b78f5c6c64f9c89766f37c1aJesse Wilson        }
1985ffd579b668428272b78f5c6c64f9c89766f37c1aJesse Wilson    }
1986ffd579b668428272b78f5c6c64f9c89766f37c1aJesse Wilson
1987eafede536f2059bb6c869e7a5f07fd7ad9758e28Jesse Wilson    private Set<String> newSet(String... elements) {
198883a47d4d0c536e06fc53eda9d5a1a5d93f9accc6Jesse Wilson        return new HashSet<String>(Arrays.asList(elements));
198983a47d4d0c536e06fc53eda9d5a1a5d93f9accc6Jesse Wilson    }
199083a47d4d0c536e06fc53eda9d5a1a5d93f9accc6Jesse Wilson
199151e468abf2628ce964d3657042f3ac8f2c947504Jesse Wilson    enum TransferKind {
199251e468abf2628ce964d3657042f3ac8f2c947504Jesse Wilson        CHUNKED() {
1993deb236fb06f2a14861e7d40dea959f181cd5cf28Jesse Wilson            @Override void setBody(MockResponse response, byte[] content, int chunkSize)
199451e468abf2628ce964d3657042f3ac8f2c947504Jesse Wilson                    throws IOException {
199551e468abf2628ce964d3657042f3ac8f2c947504Jesse Wilson                response.setChunkedBody(content, chunkSize);
199651e468abf2628ce964d3657042f3ac8f2c947504Jesse Wilson            }
199751e468abf2628ce964d3657042f3ac8f2c947504Jesse Wilson        },
199851e468abf2628ce964d3657042f3ac8f2c947504Jesse Wilson        FIXED_LENGTH() {
1999deb236fb06f2a14861e7d40dea959f181cd5cf28Jesse Wilson            @Override void setBody(MockResponse response, byte[] content, int chunkSize) {
200051e468abf2628ce964d3657042f3ac8f2c947504Jesse Wilson                response.setBody(content);
200151e468abf2628ce964d3657042f3ac8f2c947504Jesse Wilson            }
200251e468abf2628ce964d3657042f3ac8f2c947504Jesse Wilson        },
200351e468abf2628ce964d3657042f3ac8f2c947504Jesse Wilson        END_OF_STREAM() {
2004deb236fb06f2a14861e7d40dea959f181cd5cf28Jesse Wilson            @Override void setBody(MockResponse response, byte[] content, int chunkSize) {
200551e468abf2628ce964d3657042f3ac8f2c947504Jesse Wilson                response.setBody(content);
2006e942f46f10bb9384a1b186b3d7b74f9704c57090Jesse Wilson                response.setSocketPolicy(DISCONNECT_AT_END);
200751e468abf2628ce964d3657042f3ac8f2c947504Jesse Wilson                for (Iterator<String> h = response.getHeaders().iterator(); h.hasNext(); ) {
200851e468abf2628ce964d3657042f3ac8f2c947504Jesse Wilson                    if (h.next().startsWith("Content-Length:")) {
200951e468abf2628ce964d3657042f3ac8f2c947504Jesse Wilson                        h.remove();
201051e468abf2628ce964d3657042f3ac8f2c947504Jesse Wilson                        break;
201151e468abf2628ce964d3657042f3ac8f2c947504Jesse Wilson                    }
201251e468abf2628ce964d3657042f3ac8f2c947504Jesse Wilson                }
201351e468abf2628ce964d3657042f3ac8f2c947504Jesse Wilson            }
201451e468abf2628ce964d3657042f3ac8f2c947504Jesse Wilson        };
201551e468abf2628ce964d3657042f3ac8f2c947504Jesse Wilson
2016deb236fb06f2a14861e7d40dea959f181cd5cf28Jesse Wilson        abstract void setBody(MockResponse response, byte[] content, int chunkSize)
201751e468abf2628ce964d3657042f3ac8f2c947504Jesse Wilson                throws IOException;
2018deb236fb06f2a14861e7d40dea959f181cd5cf28Jesse Wilson
2019deb236fb06f2a14861e7d40dea959f181cd5cf28Jesse Wilson        void setBody(MockResponse response, String content, int chunkSize) throws IOException {
2020deb236fb06f2a14861e7d40dea959f181cd5cf28Jesse Wilson            setBody(response, content.getBytes("UTF-8"), chunkSize);
2021deb236fb06f2a14861e7d40dea959f181cd5cf28Jesse Wilson        }
202251e468abf2628ce964d3657042f3ac8f2c947504Jesse Wilson    }
2023c0372d90016d241ac979faa6fa1731f30b6f2a03Jesse Wilson
2024984fcff696380abd6ea14e80030f9fd2d09dbad0Jesse Wilson    enum ProxyConfig {
2025f02c695ed03e708623d9365dec26d533356ef2d0Brian Carlstrom        NO_PROXY() {
2026f02c695ed03e708623d9365dec26d533356ef2d0Brian Carlstrom            @Override public HttpURLConnection connect(MockWebServer server, URL url)
2027f02c695ed03e708623d9365dec26d533356ef2d0Brian Carlstrom                    throws IOException {
2028f02c695ed03e708623d9365dec26d533356ef2d0Brian Carlstrom                return (HttpURLConnection) url.openConnection(Proxy.NO_PROXY);
2029f02c695ed03e708623d9365dec26d533356ef2d0Brian Carlstrom            }
2030f02c695ed03e708623d9365dec26d533356ef2d0Brian Carlstrom        },
2031f02c695ed03e708623d9365dec26d533356ef2d0Brian Carlstrom
2032984fcff696380abd6ea14e80030f9fd2d09dbad0Jesse Wilson        CREATE_ARG() {
2033984fcff696380abd6ea14e80030f9fd2d09dbad0Jesse Wilson            @Override public HttpURLConnection connect(MockWebServer server, URL url)
2034984fcff696380abd6ea14e80030f9fd2d09dbad0Jesse Wilson                    throws IOException {
2035984fcff696380abd6ea14e80030f9fd2d09dbad0Jesse Wilson                return (HttpURLConnection) url.openConnection(server.toProxyAddress());
2036984fcff696380abd6ea14e80030f9fd2d09dbad0Jesse Wilson            }
2037984fcff696380abd6ea14e80030f9fd2d09dbad0Jesse Wilson        },
2038984fcff696380abd6ea14e80030f9fd2d09dbad0Jesse Wilson
2039984fcff696380abd6ea14e80030f9fd2d09dbad0Jesse Wilson        PROXY_SYSTEM_PROPERTY() {
2040984fcff696380abd6ea14e80030f9fd2d09dbad0Jesse Wilson            @Override public HttpURLConnection connect(MockWebServer server, URL url)
2041984fcff696380abd6ea14e80030f9fd2d09dbad0Jesse Wilson                    throws IOException {
2042984fcff696380abd6ea14e80030f9fd2d09dbad0Jesse Wilson                System.setProperty("proxyHost", "localhost");
2043984fcff696380abd6ea14e80030f9fd2d09dbad0Jesse Wilson                System.setProperty("proxyPort", Integer.toString(server.getPort()));
2044984fcff696380abd6ea14e80030f9fd2d09dbad0Jesse Wilson                return (HttpURLConnection) url.openConnection();
2045984fcff696380abd6ea14e80030f9fd2d09dbad0Jesse Wilson            }
2046984fcff696380abd6ea14e80030f9fd2d09dbad0Jesse Wilson        },
2047984fcff696380abd6ea14e80030f9fd2d09dbad0Jesse Wilson
2048984fcff696380abd6ea14e80030f9fd2d09dbad0Jesse Wilson        HTTP_PROXY_SYSTEM_PROPERTY() {
2049984fcff696380abd6ea14e80030f9fd2d09dbad0Jesse Wilson            @Override public HttpURLConnection connect(MockWebServer server, URL url)
2050984fcff696380abd6ea14e80030f9fd2d09dbad0Jesse Wilson                    throws IOException {
2051984fcff696380abd6ea14e80030f9fd2d09dbad0Jesse Wilson                System.setProperty("http.proxyHost", "localhost");
2052984fcff696380abd6ea14e80030f9fd2d09dbad0Jesse Wilson                System.setProperty("http.proxyPort", Integer.toString(server.getPort()));
2053984fcff696380abd6ea14e80030f9fd2d09dbad0Jesse Wilson                return (HttpURLConnection) url.openConnection();
2054984fcff696380abd6ea14e80030f9fd2d09dbad0Jesse Wilson            }
2055984fcff696380abd6ea14e80030f9fd2d09dbad0Jesse Wilson        },
2056984fcff696380abd6ea14e80030f9fd2d09dbad0Jesse Wilson
2057984fcff696380abd6ea14e80030f9fd2d09dbad0Jesse Wilson        HTTPS_PROXY_SYSTEM_PROPERTY() {
2058984fcff696380abd6ea14e80030f9fd2d09dbad0Jesse Wilson            @Override public HttpURLConnection connect(MockWebServer server, URL url)
2059984fcff696380abd6ea14e80030f9fd2d09dbad0Jesse Wilson                    throws IOException {
2060984fcff696380abd6ea14e80030f9fd2d09dbad0Jesse Wilson                System.setProperty("https.proxyHost", "localhost");
2061984fcff696380abd6ea14e80030f9fd2d09dbad0Jesse Wilson                System.setProperty("https.proxyPort", Integer.toString(server.getPort()));
2062984fcff696380abd6ea14e80030f9fd2d09dbad0Jesse Wilson                return (HttpURLConnection) url.openConnection();
2063984fcff696380abd6ea14e80030f9fd2d09dbad0Jesse Wilson            }
2064984fcff696380abd6ea14e80030f9fd2d09dbad0Jesse Wilson        };
2065984fcff696380abd6ea14e80030f9fd2d09dbad0Jesse Wilson
2066984fcff696380abd6ea14e80030f9fd2d09dbad0Jesse Wilson        public abstract HttpURLConnection connect(MockWebServer server, URL url) throws IOException;
2067984fcff696380abd6ea14e80030f9fd2d09dbad0Jesse Wilson    }
2068984fcff696380abd6ea14e80030f9fd2d09dbad0Jesse Wilson
2069c0372d90016d241ac979faa6fa1731f30b6f2a03Jesse Wilson    private static class RecordingTrustManager implements X509TrustManager {
2070c0372d90016d241ac979faa6fa1731f30b6f2a03Jesse Wilson        private final List<String> calls = new ArrayList<String>();
2071c0372d90016d241ac979faa6fa1731f30b6f2a03Jesse Wilson
2072c0372d90016d241ac979faa6fa1731f30b6f2a03Jesse Wilson        public X509Certificate[] getAcceptedIssuers() {
2073c0372d90016d241ac979faa6fa1731f30b6f2a03Jesse Wilson            calls.add("getAcceptedIssuers");
2074c0372d90016d241ac979faa6fa1731f30b6f2a03Jesse Wilson            return new X509Certificate[] {};
2075c0372d90016d241ac979faa6fa1731f30b6f2a03Jesse Wilson        }
2076c0372d90016d241ac979faa6fa1731f30b6f2a03Jesse Wilson
2077c0372d90016d241ac979faa6fa1731f30b6f2a03Jesse Wilson        public void checkClientTrusted(X509Certificate[] chain, String authType)
2078c0372d90016d241ac979faa6fa1731f30b6f2a03Jesse Wilson                throws CertificateException {
2079c0372d90016d241ac979faa6fa1731f30b6f2a03Jesse Wilson            calls.add("checkClientTrusted " + certificatesToString(chain) + " " + authType);
2080c0372d90016d241ac979faa6fa1731f30b6f2a03Jesse Wilson        }
2081c0372d90016d241ac979faa6fa1731f30b6f2a03Jesse Wilson
2082c0372d90016d241ac979faa6fa1731f30b6f2a03Jesse Wilson        public void checkServerTrusted(X509Certificate[] chain, String authType)
2083c0372d90016d241ac979faa6fa1731f30b6f2a03Jesse Wilson                throws CertificateException {
2084c0372d90016d241ac979faa6fa1731f30b6f2a03Jesse Wilson            calls.add("checkServerTrusted " + certificatesToString(chain) + " " + authType);
2085c0372d90016d241ac979faa6fa1731f30b6f2a03Jesse Wilson        }
2086c0372d90016d241ac979faa6fa1731f30b6f2a03Jesse Wilson
2087c0372d90016d241ac979faa6fa1731f30b6f2a03Jesse Wilson        private String certificatesToString(X509Certificate[] certificates) {
2088c0372d90016d241ac979faa6fa1731f30b6f2a03Jesse Wilson            List<String> result = new ArrayList<String>();
2089c0372d90016d241ac979faa6fa1731f30b6f2a03Jesse Wilson            for (X509Certificate certificate : certificates) {
2090c0372d90016d241ac979faa6fa1731f30b6f2a03Jesse Wilson                result.add(certificate.getSubjectDN() + " " + certificate.getSerialNumber());
2091c0372d90016d241ac979faa6fa1731f30b6f2a03Jesse Wilson            }
2092c0372d90016d241ac979faa6fa1731f30b6f2a03Jesse Wilson            return result.toString();
2093c0372d90016d241ac979faa6fa1731f30b6f2a03Jesse Wilson        }
2094c0372d90016d241ac979faa6fa1731f30b6f2a03Jesse Wilson    }
2095c0372d90016d241ac979faa6fa1731f30b6f2a03Jesse Wilson
2096c0372d90016d241ac979faa6fa1731f30b6f2a03Jesse Wilson    private static class RecordingHostnameVerifier implements HostnameVerifier {
2097c0372d90016d241ac979faa6fa1731f30b6f2a03Jesse Wilson        private final List<String> calls = new ArrayList<String>();
2098c0372d90016d241ac979faa6fa1731f30b6f2a03Jesse Wilson
2099c0372d90016d241ac979faa6fa1731f30b6f2a03Jesse Wilson        public boolean verify(String hostname, SSLSession session) {
2100c0372d90016d241ac979faa6fa1731f30b6f2a03Jesse Wilson            calls.add("verify " + hostname);
2101c0372d90016d241ac979faa6fa1731f30b6f2a03Jesse Wilson            return true;
2102c0372d90016d241ac979faa6fa1731f30b6f2a03Jesse Wilson        }
2103c0372d90016d241ac979faa6fa1731f30b6f2a03Jesse Wilson    }
2104e40c9e3935a5024c0f3ebfb3f1441fcd5c48ed86Elliott Hughes}
2105