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;
278155888a2c4e7cc28596deec28433e1984cfaf11Brian Carlstromimport dalvik.system.CloseGuard;
28c8977f474b30c5f3807398859a6b16687af6fc7bJesse Wilsonimport java.io.ByteArrayOutputStream;
298155888a2c4e7cc28596deec28433e1984cfaf11Brian Carlstromimport java.io.Closeable;
304ec2d0dea800397fb32227e0631246f4d2a73191Brian Carlstromimport java.io.File;
316247987eb505a482a67f5f19678260d9e7240a5fElliott Hughesimport java.io.IOException;
3251e468abf2628ce964d3657042f3ac8f2c947504Jesse Wilsonimport java.io.InputStream;
3302f0cb2eb84a112fcf644d7d1fd0b5f94ea2f03bElliott Hughesimport java.io.OutputStream;
344557728efb66c455a52b7669a8eefef7a9e54854Jesse Wilsonimport java.net.Authenticator;
354557728efb66c455a52b7669a8eefef7a9e54854Jesse Wilsonimport java.net.CacheRequest;
364557728efb66c455a52b7669a8eefef7a9e54854Jesse Wilsonimport java.net.CacheResponse;
37b7f4d6c3968c372767b2510f38a3d506067aced6Jesse Wilsonimport java.net.ConnectException;
384557728efb66c455a52b7669a8eefef7a9e54854Jesse Wilsonimport java.net.HttpRetryException;
394557728efb66c455a52b7669a8eefef7a9e54854Jesse Wilsonimport java.net.HttpURLConnection;
402d9fa917aae6a6da38e9d1eda05841ffdf8855bbJesse Wilsonimport java.net.InetAddress;
414557728efb66c455a52b7669a8eefef7a9e54854Jesse Wilsonimport java.net.PasswordAuthentication;
42f14bee4dbf9f724a177a85a7b73f7b0bc6df1ec0Jesse Wilsonimport java.net.ProtocolException;
43f02c695ed03e708623d9365dec26d533356ef2d0Brian Carlstromimport java.net.Proxy;
444557728efb66c455a52b7669a8eefef7a9e54854Jesse Wilsonimport java.net.ResponseCache;
454557728efb66c455a52b7669a8eefef7a9e54854Jesse Wilsonimport java.net.SocketTimeoutException;
464557728efb66c455a52b7669a8eefef7a9e54854Jesse Wilsonimport java.net.URI;
474557728efb66c455a52b7669a8eefef7a9e54854Jesse Wilsonimport java.net.URL;
484557728efb66c455a52b7669a8eefef7a9e54854Jesse Wilsonimport java.net.URLConnection;
49d0d626655f1d452070d3116678037e8759f807f4Jesse Wilsonimport java.net.UnknownHostException;
50c0372d90016d241ac979faa6fa1731f30b6f2a03Jesse Wilsonimport java.security.cert.CertificateException;
51c0372d90016d241ac979faa6fa1731f30b6f2a03Jesse Wilsonimport java.security.cert.X509Certificate;
524ec2d0dea800397fb32227e0631246f4d2a73191Brian Carlstromimport java.text.DateFormat;
534ec2d0dea800397fb32227e0631246f4d2a73191Brian Carlstromimport java.text.SimpleDateFormat;
5451e468abf2628ce964d3657042f3ac8f2c947504Jesse Wilsonimport java.util.ArrayList;
5502f0cb2eb84a112fcf644d7d1fd0b5f94ea2f03bElliott Hughesimport java.util.Arrays;
5651e468abf2628ce964d3657042f3ac8f2c947504Jesse Wilsonimport java.util.Collections;
574ec2d0dea800397fb32227e0631246f4d2a73191Brian Carlstromimport java.util.Date;
5883a47d4d0c536e06fc53eda9d5a1a5d93f9accc6Jesse Wilsonimport java.util.HashSet;
5951e468abf2628ce964d3657042f3ac8f2c947504Jesse Wilsonimport java.util.Iterator;
606247987eb505a482a67f5f19678260d9e7240a5fElliott Hughesimport java.util.List;
614ec2d0dea800397fb32227e0631246f4d2a73191Brian Carlstromimport java.util.Locale;
6283a47d4d0c536e06fc53eda9d5a1a5d93f9accc6Jesse Wilsonimport java.util.Map;
6351e468abf2628ce964d3657042f3ac8f2c947504Jesse Wilsonimport java.util.Set;
644ec2d0dea800397fb32227e0631246f4d2a73191Brian Carlstromimport java.util.TimeZone;
654ec2d0dea800397fb32227e0631246f4d2a73191Brian Carlstromimport java.util.UUID;
664ec2d0dea800397fb32227e0631246f4d2a73191Brian Carlstromimport java.util.concurrent.TimeUnit;
67afd9b157f467b7c4f2f0b5592dca72f18d844602Jesse Wilsonimport java.util.concurrent.atomic.AtomicBoolean;
6883a47d4d0c536e06fc53eda9d5a1a5d93f9accc6Jesse Wilsonimport java.util.concurrent.atomic.AtomicReference;
69deb236fb06f2a14861e7d40dea959f181cd5cf28Jesse Wilsonimport java.util.zip.GZIPInputStream;
70deb236fb06f2a14861e7d40dea959f181cd5cf28Jesse Wilsonimport java.util.zip.GZIPOutputStream;
7160476787f0e0f052366d8031c74e507ffd3d16a3Jesse Wilsonimport javax.net.ssl.HostnameVerifier;
7260476787f0e0f052366d8031c74e507ffd3d16a3Jesse Wilsonimport javax.net.ssl.HttpsURLConnection;
73c0372d90016d241ac979faa6fa1731f30b6f2a03Jesse Wilsonimport javax.net.ssl.SSLContext;
74096aac7b8a607d3da237900f52cab1c5066bf992Jesse Wilsonimport javax.net.ssl.SSLException;
752915378e253f08e47fe5a9bfd026cd1ca7c6c351Brian Carlstromimport javax.net.ssl.SSLHandshakeException;
7660476787f0e0f052366d8031c74e507ffd3d16a3Jesse Wilsonimport javax.net.ssl.SSLSession;
77c0372d90016d241ac979faa6fa1731f30b6f2a03Jesse Wilsonimport javax.net.ssl.SSLSocketFactory;
78c0372d90016d241ac979faa6fa1731f30b6f2a03Jesse Wilsonimport javax.net.ssl.TrustManager;
79c0372d90016d241ac979faa6fa1731f30b6f2a03Jesse Wilsonimport javax.net.ssl.X509TrustManager;
80ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilsonimport junit.framework.TestCase;
818155888a2c4e7cc28596deec28433e1984cfaf11Brian Carlstromimport libcore.java.lang.ref.FinalizationTester;
822915378e253f08e47fe5a9bfd026cd1ca7c6c351Brian Carlstromimport libcore.java.security.TestKeyStore;
8350ae32218918eae80298bd1ab8e4f588bbbabdb2Jesse Wilsonimport libcore.javax.net.ssl.TestSSLContext;
844ec2d0dea800397fb32227e0631246f4d2a73191Brian Carlstromimport libcore.net.http.HttpResponseCache;
855fc5dde4c719c1dfdac46b67d5d2e4884d07721eElliott Hughesimport tests.net.StuckServer;
86e40c9e3935a5024c0f3ebfb3f1441fcd5c48ed86Elliott Hughes
87ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilsonpublic final class URLConnectionTest extends TestCase {
8851e468abf2628ce964d3657042f3ac8f2c947504Jesse Wilson    private MockWebServer server = new MockWebServer();
894ec2d0dea800397fb32227e0631246f4d2a73191Brian Carlstrom    private HttpResponseCache cache;
900c2fd828abec671333b8b88281825fd27a783723Jesse Wilson    private String hostName;
9100feece22909b7dc79fc96d666d157390b93858eJesse Wilson
9200feece22909b7dc79fc96d666d157390b93858eJesse Wilson    @Override protected void setUp() throws Exception {
9300feece22909b7dc79fc96d666d157390b93858eJesse Wilson        super.setUp();
940c2fd828abec671333b8b88281825fd27a783723Jesse Wilson        hostName = server.getHostName();
9500feece22909b7dc79fc96d666d157390b93858eJesse Wilson    }
9651e468abf2628ce964d3657042f3ac8f2c947504Jesse Wilson
9751e468abf2628ce964d3657042f3ac8f2c947504Jesse Wilson    @Override protected void tearDown() throws Exception {
9851e468abf2628ce964d3657042f3ac8f2c947504Jesse Wilson        ResponseCache.setDefault(null);
99ffd579b668428272b78f5c6c64f9c89766f37c1aJesse Wilson        Authenticator.setDefault(null);
100984fcff696380abd6ea14e80030f9fd2d09dbad0Jesse Wilson        System.clearProperty("proxyHost");
101984fcff696380abd6ea14e80030f9fd2d09dbad0Jesse Wilson        System.clearProperty("proxyPort");
102984fcff696380abd6ea14e80030f9fd2d09dbad0Jesse Wilson        System.clearProperty("http.proxyHost");
103984fcff696380abd6ea14e80030f9fd2d09dbad0Jesse Wilson        System.clearProperty("http.proxyPort");
104984fcff696380abd6ea14e80030f9fd2d09dbad0Jesse Wilson        System.clearProperty("https.proxyHost");
105984fcff696380abd6ea14e80030f9fd2d09dbad0Jesse Wilson        System.clearProperty("https.proxyPort");
10651e468abf2628ce964d3657042f3ac8f2c947504Jesse Wilson        server.shutdown();
1074ec2d0dea800397fb32227e0631246f4d2a73191Brian Carlstrom        if (cache != null) {
1084ec2d0dea800397fb32227e0631246f4d2a73191Brian Carlstrom            cache.getCache().delete();
1094ec2d0dea800397fb32227e0631246f4d2a73191Brian Carlstrom        }
11000feece22909b7dc79fc96d666d157390b93858eJesse Wilson        super.tearDown();
11151e468abf2628ce964d3657042f3ac8f2c947504Jesse Wilson    }
11251e468abf2628ce964d3657042f3ac8f2c947504Jesse Wilson
11383a47d4d0c536e06fc53eda9d5a1a5d93f9accc6Jesse Wilson    public void testRequestHeaders() throws IOException, InterruptedException {
11483a47d4d0c536e06fc53eda9d5a1a5d93f9accc6Jesse Wilson        server.enqueue(new MockResponse());
11583a47d4d0c536e06fc53eda9d5a1a5d93f9accc6Jesse Wilson        server.play();
11683a47d4d0c536e06fc53eda9d5a1a5d93f9accc6Jesse Wilson
11783a47d4d0c536e06fc53eda9d5a1a5d93f9accc6Jesse Wilson        HttpURLConnection urlConnection = (HttpURLConnection) server.getUrl("/").openConnection();
11883a47d4d0c536e06fc53eda9d5a1a5d93f9accc6Jesse Wilson        urlConnection.addRequestProperty("D", "e");
11983a47d4d0c536e06fc53eda9d5a1a5d93f9accc6Jesse Wilson        urlConnection.addRequestProperty("D", "f");
120ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson        assertEquals("f", urlConnection.getRequestProperty("D"));
121ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson        assertEquals("f", urlConnection.getRequestProperty("d"));
12283a47d4d0c536e06fc53eda9d5a1a5d93f9accc6Jesse Wilson        Map<String, List<String>> requestHeaders = urlConnection.getRequestProperties();
12383a47d4d0c536e06fc53eda9d5a1a5d93f9accc6Jesse Wilson        assertEquals(newSet("e", "f"), new HashSet<String>(requestHeaders.get("D")));
124ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson        assertEquals(newSet("e", "f"), new HashSet<String>(requestHeaders.get("d")));
12583a47d4d0c536e06fc53eda9d5a1a5d93f9accc6Jesse Wilson        try {
12683a47d4d0c536e06fc53eda9d5a1a5d93f9accc6Jesse Wilson            requestHeaders.put("G", Arrays.asList("h"));
12783a47d4d0c536e06fc53eda9d5a1a5d93f9accc6Jesse Wilson            fail("Modified an unmodifiable view.");
12883a47d4d0c536e06fc53eda9d5a1a5d93f9accc6Jesse Wilson        } catch (UnsupportedOperationException expected) {
12983a47d4d0c536e06fc53eda9d5a1a5d93f9accc6Jesse Wilson        }
13083a47d4d0c536e06fc53eda9d5a1a5d93f9accc6Jesse Wilson        try {
13183a47d4d0c536e06fc53eda9d5a1a5d93f9accc6Jesse Wilson            requestHeaders.get("D").add("i");
13283a47d4d0c536e06fc53eda9d5a1a5d93f9accc6Jesse Wilson            fail("Modified an unmodifiable view.");
13383a47d4d0c536e06fc53eda9d5a1a5d93f9accc6Jesse Wilson        } catch (UnsupportedOperationException expected) {
13483a47d4d0c536e06fc53eda9d5a1a5d93f9accc6Jesse Wilson        }
13583a47d4d0c536e06fc53eda9d5a1a5d93f9accc6Jesse Wilson        try {
13683a47d4d0c536e06fc53eda9d5a1a5d93f9accc6Jesse Wilson            urlConnection.setRequestProperty(null, "j");
13783a47d4d0c536e06fc53eda9d5a1a5d93f9accc6Jesse Wilson            fail();
13883a47d4d0c536e06fc53eda9d5a1a5d93f9accc6Jesse Wilson        } catch (NullPointerException expected) {
13983a47d4d0c536e06fc53eda9d5a1a5d93f9accc6Jesse Wilson        }
14083a47d4d0c536e06fc53eda9d5a1a5d93f9accc6Jesse Wilson        try {
14183a47d4d0c536e06fc53eda9d5a1a5d93f9accc6Jesse Wilson            urlConnection.addRequestProperty(null, "k");
14283a47d4d0c536e06fc53eda9d5a1a5d93f9accc6Jesse Wilson            fail();
14383a47d4d0c536e06fc53eda9d5a1a5d93f9accc6Jesse Wilson        } catch (NullPointerException expected) {
14483a47d4d0c536e06fc53eda9d5a1a5d93f9accc6Jesse Wilson        }
14583a47d4d0c536e06fc53eda9d5a1a5d93f9accc6Jesse Wilson        urlConnection.setRequestProperty("NullValue", null); // should fail silently!
146ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson        assertNull(urlConnection.getRequestProperty("NullValue"));
14783a47d4d0c536e06fc53eda9d5a1a5d93f9accc6Jesse Wilson        urlConnection.addRequestProperty("AnotherNullValue", null);  // should fail silently!
148ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson        assertNull(urlConnection.getRequestProperty("AnotherNullValue"));
14983a47d4d0c536e06fc53eda9d5a1a5d93f9accc6Jesse Wilson
15083a47d4d0c536e06fc53eda9d5a1a5d93f9accc6Jesse Wilson        urlConnection.getResponseCode();
15183a47d4d0c536e06fc53eda9d5a1a5d93f9accc6Jesse Wilson        RecordedRequest request = server.takeRequest();
15283a47d4d0c536e06fc53eda9d5a1a5d93f9accc6Jesse Wilson        assertContains(request.getHeaders(), "D: e");
15383a47d4d0c536e06fc53eda9d5a1a5d93f9accc6Jesse Wilson        assertContains(request.getHeaders(), "D: f");
15483a47d4d0c536e06fc53eda9d5a1a5d93f9accc6Jesse Wilson        assertContainsNoneMatching(request.getHeaders(), "NullValue.*");
15583a47d4d0c536e06fc53eda9d5a1a5d93f9accc6Jesse Wilson        assertContainsNoneMatching(request.getHeaders(), "AnotherNullValue.*");
15683a47d4d0c536e06fc53eda9d5a1a5d93f9accc6Jesse Wilson        assertContainsNoneMatching(request.getHeaders(), "G:.*");
15783a47d4d0c536e06fc53eda9d5a1a5d93f9accc6Jesse Wilson        assertContainsNoneMatching(request.getHeaders(), "null:.*");
15883a47d4d0c536e06fc53eda9d5a1a5d93f9accc6Jesse Wilson
15983a47d4d0c536e06fc53eda9d5a1a5d93f9accc6Jesse Wilson        try {
16083a47d4d0c536e06fc53eda9d5a1a5d93f9accc6Jesse Wilson            urlConnection.addRequestProperty("N", "o");
16183a47d4d0c536e06fc53eda9d5a1a5d93f9accc6Jesse Wilson            fail("Set header after connect");
16283a47d4d0c536e06fc53eda9d5a1a5d93f9accc6Jesse Wilson        } catch (IllegalStateException expected) {
16383a47d4d0c536e06fc53eda9d5a1a5d93f9accc6Jesse Wilson        }
16483a47d4d0c536e06fc53eda9d5a1a5d93f9accc6Jesse Wilson        try {
16583a47d4d0c536e06fc53eda9d5a1a5d93f9accc6Jesse Wilson            urlConnection.setRequestProperty("P", "q");
16683a47d4d0c536e06fc53eda9d5a1a5d93f9accc6Jesse Wilson            fail("Set header after connect");
16783a47d4d0c536e06fc53eda9d5a1a5d93f9accc6Jesse Wilson        } catch (IllegalStateException expected) {
16883a47d4d0c536e06fc53eda9d5a1a5d93f9accc6Jesse Wilson        }
169ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson        try {
170ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson            urlConnection.getRequestProperties();
171ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson            fail();
172ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson        } catch (IllegalStateException expected) {
173ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson        }
174ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson    }
175ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson
176ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson    public void testGetRequestPropertyReturnsLastValue() throws Exception {
177ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson        server.play();
178ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson        HttpURLConnection urlConnection = (HttpURLConnection) server.getUrl("/").openConnection();
179ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson        urlConnection.addRequestProperty("A", "value1");
180ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson        urlConnection.addRequestProperty("A", "value2");
181ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson        assertEquals("value2", urlConnection.getRequestProperty("A"));
18283a47d4d0c536e06fc53eda9d5a1a5d93f9accc6Jesse Wilson    }
18383a47d4d0c536e06fc53eda9d5a1a5d93f9accc6Jesse Wilson
18483a47d4d0c536e06fc53eda9d5a1a5d93f9accc6Jesse Wilson    public void testResponseHeaders() throws IOException, InterruptedException {
18583a47d4d0c536e06fc53eda9d5a1a5d93f9accc6Jesse Wilson        server.enqueue(new MockResponse()
18683a47d4d0c536e06fc53eda9d5a1a5d93f9accc6Jesse Wilson                .setStatus("HTTP/1.0 200 Fantastic")
18783a47d4d0c536e06fc53eda9d5a1a5d93f9accc6Jesse Wilson                .addHeader("A: c")
188ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson                .addHeader("B: d")
189ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson                .addHeader("A: e")
19083a47d4d0c536e06fc53eda9d5a1a5d93f9accc6Jesse Wilson                .setChunkedBody("ABCDE\nFGHIJ\nKLMNO\nPQR", 8));
19183a47d4d0c536e06fc53eda9d5a1a5d93f9accc6Jesse Wilson        server.play();
19283a47d4d0c536e06fc53eda9d5a1a5d93f9accc6Jesse Wilson
19383a47d4d0c536e06fc53eda9d5a1a5d93f9accc6Jesse Wilson        HttpURLConnection urlConnection = (HttpURLConnection) server.getUrl("/").openConnection();
19483a47d4d0c536e06fc53eda9d5a1a5d93f9accc6Jesse Wilson        assertEquals(200, urlConnection.getResponseCode());
19583a47d4d0c536e06fc53eda9d5a1a5d93f9accc6Jesse Wilson        assertEquals("Fantastic", urlConnection.getResponseMessage());
196c1a675c80c69decadb736b245f0366f93a94a462Jesse Wilson        assertEquals("HTTP/1.0 200 Fantastic", urlConnection.getHeaderField(null));
19783a47d4d0c536e06fc53eda9d5a1a5d93f9accc6Jesse Wilson        Map<String, List<String>> responseHeaders = urlConnection.getHeaderFields();
1988ac847a52e72f0cefbb20a6850ae04468d433a9eJesse Wilson        assertEquals(Arrays.asList("HTTP/1.0 200 Fantastic"), responseHeaders.get(null));
199ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson        assertEquals(newSet("c", "e"), new HashSet<String>(responseHeaders.get("A")));
200ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson        assertEquals(newSet("c", "e"), new HashSet<String>(responseHeaders.get("a")));
20183a47d4d0c536e06fc53eda9d5a1a5d93f9accc6Jesse Wilson        try {
20283a47d4d0c536e06fc53eda9d5a1a5d93f9accc6Jesse Wilson            responseHeaders.put("N", Arrays.asList("o"));
20383a47d4d0c536e06fc53eda9d5a1a5d93f9accc6Jesse Wilson            fail("Modified an unmodifiable view.");
20483a47d4d0c536e06fc53eda9d5a1a5d93f9accc6Jesse Wilson        } catch (UnsupportedOperationException expected) {
20583a47d4d0c536e06fc53eda9d5a1a5d93f9accc6Jesse Wilson        }
20683a47d4d0c536e06fc53eda9d5a1a5d93f9accc6Jesse Wilson        try {
207ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson            responseHeaders.get("A").add("f");
20883a47d4d0c536e06fc53eda9d5a1a5d93f9accc6Jesse Wilson            fail("Modified an unmodifiable view.");
20983a47d4d0c536e06fc53eda9d5a1a5d93f9accc6Jesse Wilson        } catch (UnsupportedOperationException expected) {
21083a47d4d0c536e06fc53eda9d5a1a5d93f9accc6Jesse Wilson        }
211ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson        assertEquals("A", urlConnection.getHeaderFieldKey(0));
212ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson        assertEquals("c", urlConnection.getHeaderField(0));
213ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson        assertEquals("B", urlConnection.getHeaderFieldKey(1));
214ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson        assertEquals("d", urlConnection.getHeaderField(1));
215ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson        assertEquals("A", urlConnection.getHeaderFieldKey(2));
216ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson        assertEquals("e", urlConnection.getHeaderField(2));
217ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson    }
218ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson
219ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson    public void testGetErrorStreamOnSuccessfulRequest() throws Exception {
220ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson        server.enqueue(new MockResponse().setBody("A"));
221ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson        server.play();
222ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson        HttpURLConnection connection = (HttpURLConnection) server.getUrl("/").openConnection();
223ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson        assertNull(connection.getErrorStream());
224ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson    }
225ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson
226ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson    public void testGetErrorStreamOnUnsuccessfulRequest() throws Exception {
227ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson        server.enqueue(new MockResponse().setResponseCode(404).setBody("A"));
228ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson        server.play();
229ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson        HttpURLConnection connection = (HttpURLConnection) server.getUrl("/").openConnection();
230ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson        assertEquals("A", readAscii(connection.getErrorStream(), Integer.MAX_VALUE));
23183a47d4d0c536e06fc53eda9d5a1a5d93f9accc6Jesse Wilson    }
23283a47d4d0c536e06fc53eda9d5a1a5d93f9accc6Jesse Wilson
233e40c9e3935a5024c0f3ebfb3f1441fcd5c48ed86Elliott Hughes    // Check that if we don't read to the end of a response, the next request on the
234e40c9e3935a5024c0f3ebfb3f1441fcd5c48ed86Elliott Hughes    // recycled connection doesn't get the unread tail of the first request's response.
235e40c9e3935a5024c0f3ebfb3f1441fcd5c48ed86Elliott Hughes    // http://code.google.com/p/android/issues/detail?id=2939
236e40c9e3935a5024c0f3ebfb3f1441fcd5c48ed86Elliott Hughes    public void test_2939() throws Exception {
237b1b5baac449d2725002338735f4db34bec8fd001Jesse Wilson        MockResponse response = new MockResponse().setChunkedBody("ABCDE\nFGHIJ\nKLMNO\nPQR", 8);
238b1b5baac449d2725002338735f4db34bec8fd001Jesse Wilson
239b1b5baac449d2725002338735f4db34bec8fd001Jesse Wilson        server.enqueue(response);
240b1b5baac449d2725002338735f4db34bec8fd001Jesse Wilson        server.enqueue(response);
241b1b5baac449d2725002338735f4db34bec8fd001Jesse Wilson        server.play();
242b1b5baac449d2725002338735f4db34bec8fd001Jesse Wilson
243c8977f474b30c5f3807398859a6b16687af6fc7bJesse Wilson        assertContent("ABCDE", server.getUrl("/").openConnection(), 5);
244c8977f474b30c5f3807398859a6b16687af6fc7bJesse Wilson        assertContent("ABCDE", server.getUrl("/").openConnection(), 5);
2458baf143a7c8921d07b54adbc66ac1e5b42de5fe6Jesse Wilson    }
2468baf143a7c8921d07b54adbc66ac1e5b42de5fe6Jesse Wilson
247977a9954414ec41256b218e6278a8544ea135d45Elliott Hughes    // Check that we recognize a few basic mime types by extension.
248977a9954414ec41256b218e6278a8544ea135d45Elliott Hughes    // http://code.google.com/p/android/issues/detail?id=10100
249977a9954414ec41256b218e6278a8544ea135d45Elliott Hughes    public void test_10100() throws Exception {
250977a9954414ec41256b218e6278a8544ea135d45Elliott Hughes        assertEquals("image/jpeg", URLConnection.guessContentTypeFromName("someFile.jpg"));
251977a9954414ec41256b218e6278a8544ea135d45Elliott Hughes        assertEquals("application/pdf", URLConnection.guessContentTypeFromName("stuff.pdf"));
252977a9954414ec41256b218e6278a8544ea135d45Elliott Hughes    }
253977a9954414ec41256b218e6278a8544ea135d45Elliott Hughes
2548baf143a7c8921d07b54adbc66ac1e5b42de5fe6Jesse Wilson    public void testConnectionsArePooled() throws Exception {
255b1b5baac449d2725002338735f4db34bec8fd001Jesse Wilson        MockResponse response = new MockResponse().setBody("ABCDEFGHIJKLMNOPQR");
256b1b5baac449d2725002338735f4db34bec8fd001Jesse Wilson
257b1b5baac449d2725002338735f4db34bec8fd001Jesse Wilson        server.enqueue(response);
258b1b5baac449d2725002338735f4db34bec8fd001Jesse Wilson        server.enqueue(response);
259b1b5baac449d2725002338735f4db34bec8fd001Jesse Wilson        server.enqueue(response);
260b1b5baac449d2725002338735f4db34bec8fd001Jesse Wilson        server.play();
261b1b5baac449d2725002338735f4db34bec8fd001Jesse Wilson
26206e15e6c528fcb773bedb43e34b0577312570927Jesse Wilson        assertContent("ABCDEFGHIJKLMNOPQR", server.getUrl("/foo").openConnection());
263c8977f474b30c5f3807398859a6b16687af6fc7bJesse Wilson        assertEquals(0, server.takeRequest().getSequenceNumber());
26406e15e6c528fcb773bedb43e34b0577312570927Jesse Wilson        assertContent("ABCDEFGHIJKLMNOPQR", server.getUrl("/bar?baz=quux").openConnection());
265c8977f474b30c5f3807398859a6b16687af6fc7bJesse Wilson        assertEquals(1, server.takeRequest().getSequenceNumber());
26606e15e6c528fcb773bedb43e34b0577312570927Jesse Wilson        assertContent("ABCDEFGHIJKLMNOPQR", server.getUrl("/z").openConnection());
267c8977f474b30c5f3807398859a6b16687af6fc7bJesse Wilson        assertEquals(2, server.takeRequest().getSequenceNumber());
268c8977f474b30c5f3807398859a6b16687af6fc7bJesse Wilson    }
269c8977f474b30c5f3807398859a6b16687af6fc7bJesse Wilson
270c8977f474b30c5f3807398859a6b16687af6fc7bJesse Wilson    public void testChunkedConnectionsArePooled() throws Exception {
271c8977f474b30c5f3807398859a6b16687af6fc7bJesse Wilson        MockResponse response = new MockResponse().setChunkedBody("ABCDEFGHIJKLMNOPQR", 5);
272c8977f474b30c5f3807398859a6b16687af6fc7bJesse Wilson
273c8977f474b30c5f3807398859a6b16687af6fc7bJesse Wilson        server.enqueue(response);
274c8977f474b30c5f3807398859a6b16687af6fc7bJesse Wilson        server.enqueue(response);
275c8977f474b30c5f3807398859a6b16687af6fc7bJesse Wilson        server.enqueue(response);
276c8977f474b30c5f3807398859a6b16687af6fc7bJesse Wilson        server.play();
277c8977f474b30c5f3807398859a6b16687af6fc7bJesse Wilson
27806e15e6c528fcb773bedb43e34b0577312570927Jesse Wilson        assertContent("ABCDEFGHIJKLMNOPQR", server.getUrl("/foo").openConnection());
279b1b5baac449d2725002338735f4db34bec8fd001Jesse Wilson        assertEquals(0, server.takeRequest().getSequenceNumber());
28006e15e6c528fcb773bedb43e34b0577312570927Jesse Wilson        assertContent("ABCDEFGHIJKLMNOPQR", server.getUrl("/bar?baz=quux").openConnection());
281b1b5baac449d2725002338735f4db34bec8fd001Jesse Wilson        assertEquals(1, server.takeRequest().getSequenceNumber());
28206e15e6c528fcb773bedb43e34b0577312570927Jesse Wilson        assertContent("ABCDEFGHIJKLMNOPQR", server.getUrl("/z").openConnection());
283b1b5baac449d2725002338735f4db34bec8fd001Jesse Wilson        assertEquals(2, server.takeRequest().getSequenceNumber());
284e40c9e3935a5024c0f3ebfb3f1441fcd5c48ed86Elliott Hughes    }
28502f0cb2eb84a112fcf644d7d1fd0b5f94ea2f03bElliott Hughes
2860613de89655e481fa610bfd4f1bcaeeae3272205Jesse Wilson    /**
2870613de89655e481fa610bfd4f1bcaeeae3272205Jesse Wilson     * Test that connections are added to the pool as soon as the response has
2880613de89655e481fa610bfd4f1bcaeeae3272205Jesse Wilson     * been consumed.
2890613de89655e481fa610bfd4f1bcaeeae3272205Jesse Wilson     */
2900613de89655e481fa610bfd4f1bcaeeae3272205Jesse Wilson    public void testConnectionsArePooledWithoutExplicitDisconnect() throws Exception {
2910613de89655e481fa610bfd4f1bcaeeae3272205Jesse Wilson        server.enqueue(new MockResponse().setBody("ABC"));
2920613de89655e481fa610bfd4f1bcaeeae3272205Jesse Wilson        server.enqueue(new MockResponse().setBody("DEF"));
2930613de89655e481fa610bfd4f1bcaeeae3272205Jesse Wilson        server.play();
2940613de89655e481fa610bfd4f1bcaeeae3272205Jesse Wilson
2950613de89655e481fa610bfd4f1bcaeeae3272205Jesse Wilson        URLConnection connection1 = server.getUrl("/").openConnection();
2960613de89655e481fa610bfd4f1bcaeeae3272205Jesse Wilson        assertEquals("ABC", readAscii(connection1.getInputStream(), Integer.MAX_VALUE));
2970613de89655e481fa610bfd4f1bcaeeae3272205Jesse Wilson        assertEquals(0, server.takeRequest().getSequenceNumber());
2980613de89655e481fa610bfd4f1bcaeeae3272205Jesse Wilson        URLConnection connection2 = server.getUrl("/").openConnection();
2990613de89655e481fa610bfd4f1bcaeeae3272205Jesse Wilson        assertEquals("DEF", readAscii(connection2.getInputStream(), Integer.MAX_VALUE));
3000613de89655e481fa610bfd4f1bcaeeae3272205Jesse Wilson        assertEquals(1, server.takeRequest().getSequenceNumber());
3010613de89655e481fa610bfd4f1bcaeeae3272205Jesse Wilson    }
3020613de89655e481fa610bfd4f1bcaeeae3272205Jesse Wilson
303e942f46f10bb9384a1b186b3d7b74f9704c57090Jesse Wilson    public void testServerClosesSocket() throws Exception {
304b2b02ac6cd42a69463fd172531aa1f9b9bb887a8Jesse Wilson        testServerClosesSocket(DISCONNECT_AT_END);
305e942f46f10bb9384a1b186b3d7b74f9704c57090Jesse Wilson    }
306e942f46f10bb9384a1b186b3d7b74f9704c57090Jesse Wilson
307e942f46f10bb9384a1b186b3d7b74f9704c57090Jesse Wilson    public void testServerShutdownInput() throws Exception {
308b2b02ac6cd42a69463fd172531aa1f9b9bb887a8Jesse Wilson        testServerClosesSocket(SHUTDOWN_INPUT_AT_END);
309e942f46f10bb9384a1b186b3d7b74f9704c57090Jesse Wilson    }
310e942f46f10bb9384a1b186b3d7b74f9704c57090Jesse Wilson
311b2b02ac6cd42a69463fd172531aa1f9b9bb887a8Jesse Wilson    private void testServerClosesSocket(SocketPolicy socketPolicy) throws Exception {
312e942f46f10bb9384a1b186b3d7b74f9704c57090Jesse Wilson        server.enqueue(new MockResponse()
313e942f46f10bb9384a1b186b3d7b74f9704c57090Jesse Wilson                .setBody("This connection won't pool properly")
314e942f46f10bb9384a1b186b3d7b74f9704c57090Jesse Wilson                .setSocketPolicy(socketPolicy));
315b2b02ac6cd42a69463fd172531aa1f9b9bb887a8Jesse Wilson        server.enqueue(new MockResponse().setBody("This comes after a busted connection"));
316e942f46f10bb9384a1b186b3d7b74f9704c57090Jesse Wilson        server.play();
317e942f46f10bb9384a1b186b3d7b74f9704c57090Jesse Wilson
318e942f46f10bb9384a1b186b3d7b74f9704c57090Jesse Wilson        assertContent("This connection won't pool properly", server.getUrl("/a").openConnection());
319e942f46f10bb9384a1b186b3d7b74f9704c57090Jesse Wilson        assertEquals(0, server.takeRequest().getSequenceNumber());
320e942f46f10bb9384a1b186b3d7b74f9704c57090Jesse Wilson        assertContent("This comes after a busted connection", server.getUrl("/b").openConnection());
321e942f46f10bb9384a1b186b3d7b74f9704c57090Jesse Wilson        // sequence number 0 means the HTTP socket connection was not reused
322e942f46f10bb9384a1b186b3d7b74f9704c57090Jesse Wilson        assertEquals(0, server.takeRequest().getSequenceNumber());
323e942f46f10bb9384a1b186b3d7b74f9704c57090Jesse Wilson    }
324e942f46f10bb9384a1b186b3d7b74f9704c57090Jesse Wilson
325b2b02ac6cd42a69463fd172531aa1f9b9bb887a8Jesse Wilson    public void testServerShutdownOutput() throws Exception {
326b2b02ac6cd42a69463fd172531aa1f9b9bb887a8Jesse Wilson        // This test causes MockWebServer to log a "connection failed" stack trace
327b2b02ac6cd42a69463fd172531aa1f9b9bb887a8Jesse Wilson        server.enqueue(new MockResponse()
328b2b02ac6cd42a69463fd172531aa1f9b9bb887a8Jesse Wilson                .setBody("Output shutdown after this response")
329b2b02ac6cd42a69463fd172531aa1f9b9bb887a8Jesse Wilson                .setSocketPolicy(SHUTDOWN_OUTPUT_AT_END));
330b2b02ac6cd42a69463fd172531aa1f9b9bb887a8Jesse Wilson        server.enqueue(new MockResponse().setBody("This response will fail to write"));
331b2b02ac6cd42a69463fd172531aa1f9b9bb887a8Jesse Wilson        server.enqueue(new MockResponse().setBody("This comes after a busted connection"));
332b2b02ac6cd42a69463fd172531aa1f9b9bb887a8Jesse Wilson        server.play();
333b2b02ac6cd42a69463fd172531aa1f9b9bb887a8Jesse Wilson
334b2b02ac6cd42a69463fd172531aa1f9b9bb887a8Jesse Wilson        assertContent("Output shutdown after this response", server.getUrl("/a").openConnection());
335b2b02ac6cd42a69463fd172531aa1f9b9bb887a8Jesse Wilson        assertEquals(0, server.takeRequest().getSequenceNumber());
336b2b02ac6cd42a69463fd172531aa1f9b9bb887a8Jesse Wilson        assertContent("This comes after a busted connection", server.getUrl("/b").openConnection());
337b2b02ac6cd42a69463fd172531aa1f9b9bb887a8Jesse Wilson        assertEquals(1, server.takeRequest().getSequenceNumber());
338b2b02ac6cd42a69463fd172531aa1f9b9bb887a8Jesse Wilson        assertEquals(0, server.takeRequest().getSequenceNumber());
339b2b02ac6cd42a69463fd172531aa1f9b9bb887a8Jesse Wilson    }
340b2b02ac6cd42a69463fd172531aa1f9b9bb887a8Jesse Wilson
341b2b02ac6cd42a69463fd172531aa1f9b9bb887a8Jesse Wilson    public void testRetryableRequestBodyAfterBrokenConnection() throws Exception {
342b2b02ac6cd42a69463fd172531aa1f9b9bb887a8Jesse Wilson        server.enqueue(new MockResponse().setBody("abc").setSocketPolicy(DISCONNECT_AT_END));
343b2b02ac6cd42a69463fd172531aa1f9b9bb887a8Jesse Wilson        server.enqueue(new MockResponse().setBody("def"));
344b2b02ac6cd42a69463fd172531aa1f9b9bb887a8Jesse Wilson        server.play();
345b2b02ac6cd42a69463fd172531aa1f9b9bb887a8Jesse Wilson
346b2b02ac6cd42a69463fd172531aa1f9b9bb887a8Jesse Wilson        assertContent("abc", server.getUrl("/a").openConnection());
347b2b02ac6cd42a69463fd172531aa1f9b9bb887a8Jesse Wilson        HttpURLConnection connection = (HttpURLConnection) server.getUrl("/b").openConnection();
348b2b02ac6cd42a69463fd172531aa1f9b9bb887a8Jesse Wilson        connection.setDoOutput(true);
349b2b02ac6cd42a69463fd172531aa1f9b9bb887a8Jesse Wilson        OutputStream out = connection.getOutputStream();
350b2b02ac6cd42a69463fd172531aa1f9b9bb887a8Jesse Wilson        out.write(new byte[] {1, 2, 3});
351b2b02ac6cd42a69463fd172531aa1f9b9bb887a8Jesse Wilson        out.close();
352b2b02ac6cd42a69463fd172531aa1f9b9bb887a8Jesse Wilson        assertContent("def", connection);
353b2b02ac6cd42a69463fd172531aa1f9b9bb887a8Jesse Wilson    }
354b2b02ac6cd42a69463fd172531aa1f9b9bb887a8Jesse Wilson
355b2b02ac6cd42a69463fd172531aa1f9b9bb887a8Jesse Wilson    public void testNonRetryableRequestBodyAfterBrokenConnection() throws Exception {
356b2b02ac6cd42a69463fd172531aa1f9b9bb887a8Jesse Wilson        server.enqueue(new MockResponse().setBody("abc").setSocketPolicy(DISCONNECT_AT_END));
357b2b02ac6cd42a69463fd172531aa1f9b9bb887a8Jesse Wilson        server.enqueue(new MockResponse().setBody("def"));
358b2b02ac6cd42a69463fd172531aa1f9b9bb887a8Jesse Wilson        server.play();
359b2b02ac6cd42a69463fd172531aa1f9b9bb887a8Jesse Wilson
360b2b02ac6cd42a69463fd172531aa1f9b9bb887a8Jesse Wilson        assertContent("abc", server.getUrl("/a").openConnection());
361b2b02ac6cd42a69463fd172531aa1f9b9bb887a8Jesse Wilson        HttpURLConnection connection = (HttpURLConnection) server.getUrl("/b").openConnection();
362b2b02ac6cd42a69463fd172531aa1f9b9bb887a8Jesse Wilson        connection.setDoOutput(true);
363b2b02ac6cd42a69463fd172531aa1f9b9bb887a8Jesse Wilson        connection.setFixedLengthStreamingMode(3);
364b2b02ac6cd42a69463fd172531aa1f9b9bb887a8Jesse Wilson        OutputStream out = connection.getOutputStream();
365b2b02ac6cd42a69463fd172531aa1f9b9bb887a8Jesse Wilson        out.write(new byte[] {1, 2, 3});
366b2b02ac6cd42a69463fd172531aa1f9b9bb887a8Jesse Wilson        out.close();
367b2b02ac6cd42a69463fd172531aa1f9b9bb887a8Jesse Wilson        try {
368b2b02ac6cd42a69463fd172531aa1f9b9bb887a8Jesse Wilson            connection.getInputStream();
369b2b02ac6cd42a69463fd172531aa1f9b9bb887a8Jesse Wilson            fail();
370b2b02ac6cd42a69463fd172531aa1f9b9bb887a8Jesse Wilson        } catch (IOException expected) {
371b2b02ac6cd42a69463fd172531aa1f9b9bb887a8Jesse Wilson        }
372b2b02ac6cd42a69463fd172531aa1f9b9bb887a8Jesse Wilson    }
373b2b02ac6cd42a69463fd172531aa1f9b9bb887a8Jesse Wilson
374b1b5baac449d2725002338735f4db34bec8fd001Jesse Wilson    enum WriteKind { BYTE_BY_BYTE, SMALL_BUFFERS, LARGE_BUFFERS }
37502f0cb2eb84a112fcf644d7d1fd0b5f94ea2f03bElliott Hughes
37602f0cb2eb84a112fcf644d7d1fd0b5f94ea2f03bElliott Hughes    public void test_chunkedUpload_byteByByte() throws Exception {
37751e468abf2628ce964d3657042f3ac8f2c947504Jesse Wilson        doUpload(TransferKind.CHUNKED, WriteKind.BYTE_BY_BYTE);
37802f0cb2eb84a112fcf644d7d1fd0b5f94ea2f03bElliott Hughes    }
37902f0cb2eb84a112fcf644d7d1fd0b5f94ea2f03bElliott Hughes
38002f0cb2eb84a112fcf644d7d1fd0b5f94ea2f03bElliott Hughes    public void test_chunkedUpload_smallBuffers() throws Exception {
38151e468abf2628ce964d3657042f3ac8f2c947504Jesse Wilson        doUpload(TransferKind.CHUNKED, WriteKind.SMALL_BUFFERS);
38202f0cb2eb84a112fcf644d7d1fd0b5f94ea2f03bElliott Hughes    }
38302f0cb2eb84a112fcf644d7d1fd0b5f94ea2f03bElliott Hughes
38402f0cb2eb84a112fcf644d7d1fd0b5f94ea2f03bElliott Hughes    public void test_chunkedUpload_largeBuffers() throws Exception {
38551e468abf2628ce964d3657042f3ac8f2c947504Jesse Wilson        doUpload(TransferKind.CHUNKED, WriteKind.LARGE_BUFFERS);
38602f0cb2eb84a112fcf644d7d1fd0b5f94ea2f03bElliott Hughes    }
38702f0cb2eb84a112fcf644d7d1fd0b5f94ea2f03bElliott Hughes
38802f0cb2eb84a112fcf644d7d1fd0b5f94ea2f03bElliott Hughes    public void test_fixedLengthUpload_byteByByte() throws Exception {
38951e468abf2628ce964d3657042f3ac8f2c947504Jesse Wilson        doUpload(TransferKind.FIXED_LENGTH, WriteKind.BYTE_BY_BYTE);
39002f0cb2eb84a112fcf644d7d1fd0b5f94ea2f03bElliott Hughes    }
39102f0cb2eb84a112fcf644d7d1fd0b5f94ea2f03bElliott Hughes
39202f0cb2eb84a112fcf644d7d1fd0b5f94ea2f03bElliott Hughes    public void test_fixedLengthUpload_smallBuffers() throws Exception {
39351e468abf2628ce964d3657042f3ac8f2c947504Jesse Wilson        doUpload(TransferKind.FIXED_LENGTH, WriteKind.SMALL_BUFFERS);
39402f0cb2eb84a112fcf644d7d1fd0b5f94ea2f03bElliott Hughes    }
39502f0cb2eb84a112fcf644d7d1fd0b5f94ea2f03bElliott Hughes
39602f0cb2eb84a112fcf644d7d1fd0b5f94ea2f03bElliott Hughes    public void test_fixedLengthUpload_largeBuffers() throws Exception {
39751e468abf2628ce964d3657042f3ac8f2c947504Jesse Wilson        doUpload(TransferKind.FIXED_LENGTH, WriteKind.LARGE_BUFFERS);
39802f0cb2eb84a112fcf644d7d1fd0b5f94ea2f03bElliott Hughes    }
39902f0cb2eb84a112fcf644d7d1fd0b5f94ea2f03bElliott Hughes
40051e468abf2628ce964d3657042f3ac8f2c947504Jesse Wilson    private void doUpload(TransferKind uploadKind, WriteKind writeKind) throws Exception {
40102f0cb2eb84a112fcf644d7d1fd0b5f94ea2f03bElliott Hughes        int n = 512*1024;
402b1b5baac449d2725002338735f4db34bec8fd001Jesse Wilson        server.setBodyLimit(0);
403b1b5baac449d2725002338735f4db34bec8fd001Jesse Wilson        server.enqueue(new MockResponse());
404b1b5baac449d2725002338735f4db34bec8fd001Jesse Wilson        server.play();
405b1b5baac449d2725002338735f4db34bec8fd001Jesse Wilson
406b1b5baac449d2725002338735f4db34bec8fd001Jesse Wilson        HttpURLConnection conn = (HttpURLConnection) server.getUrl("/").openConnection();
40702f0cb2eb84a112fcf644d7d1fd0b5f94ea2f03bElliott Hughes        conn.setDoOutput(true);
40802f0cb2eb84a112fcf644d7d1fd0b5f94ea2f03bElliott Hughes        conn.setRequestMethod("POST");
40951e468abf2628ce964d3657042f3ac8f2c947504Jesse Wilson        if (uploadKind == TransferKind.CHUNKED) {
41002f0cb2eb84a112fcf644d7d1fd0b5f94ea2f03bElliott Hughes            conn.setChunkedStreamingMode(-1);
41102f0cb2eb84a112fcf644d7d1fd0b5f94ea2f03bElliott Hughes        } else {
41202f0cb2eb84a112fcf644d7d1fd0b5f94ea2f03bElliott Hughes            conn.setFixedLengthStreamingMode(n);
41302f0cb2eb84a112fcf644d7d1fd0b5f94ea2f03bElliott Hughes        }
41402f0cb2eb84a112fcf644d7d1fd0b5f94ea2f03bElliott Hughes        OutputStream out = conn.getOutputStream();
41502f0cb2eb84a112fcf644d7d1fd0b5f94ea2f03bElliott Hughes        if (writeKind == WriteKind.BYTE_BY_BYTE) {
41602f0cb2eb84a112fcf644d7d1fd0b5f94ea2f03bElliott Hughes            for (int i = 0; i < n; ++i) {
41702f0cb2eb84a112fcf644d7d1fd0b5f94ea2f03bElliott Hughes                out.write('x');
41802f0cb2eb84a112fcf644d7d1fd0b5f94ea2f03bElliott Hughes            }
41902f0cb2eb84a112fcf644d7d1fd0b5f94ea2f03bElliott Hughes        } else {
42002f0cb2eb84a112fcf644d7d1fd0b5f94ea2f03bElliott Hughes            byte[] buf = new byte[writeKind == WriteKind.SMALL_BUFFERS ? 256 : 64*1024];
42102f0cb2eb84a112fcf644d7d1fd0b5f94ea2f03bElliott Hughes            Arrays.fill(buf, (byte) 'x');
42202f0cb2eb84a112fcf644d7d1fd0b5f94ea2f03bElliott Hughes            for (int i = 0; i < n; i += buf.length) {
42302f0cb2eb84a112fcf644d7d1fd0b5f94ea2f03bElliott Hughes                out.write(buf, 0, Math.min(buf.length, n - i));
42402f0cb2eb84a112fcf644d7d1fd0b5f94ea2f03bElliott Hughes            }
42502f0cb2eb84a112fcf644d7d1fd0b5f94ea2f03bElliott Hughes        }
42602f0cb2eb84a112fcf644d7d1fd0b5f94ea2f03bElliott Hughes        out.close();
4274cb7f05dc68abb23ae54a5891c369062185f2210Elliott Hughes        assertEquals(200, conn.getResponseCode());
428b1b5baac449d2725002338735f4db34bec8fd001Jesse Wilson        RecordedRequest request = server.takeRequest();
429b1b5baac449d2725002338735f4db34bec8fd001Jesse Wilson        assertEquals(n, request.getBodySize());
43051e468abf2628ce964d3657042f3ac8f2c947504Jesse Wilson        if (uploadKind == TransferKind.CHUNKED) {
431b1b5baac449d2725002338735f4db34bec8fd001Jesse Wilson            assertTrue(request.getChunkSizes().size() > 0);
432b1b5baac449d2725002338735f4db34bec8fd001Jesse Wilson        } else {
433b1b5baac449d2725002338735f4db34bec8fd001Jesse Wilson            assertTrue(request.getChunkSizes().isEmpty());
434b1b5baac449d2725002338735f4db34bec8fd001Jesse Wilson        }
43502f0cb2eb84a112fcf644d7d1fd0b5f94ea2f03bElliott Hughes    }
4366247987eb505a482a67f5f19678260d9e7240a5fElliott Hughes
437f14bee4dbf9f724a177a85a7b73f7b0bc6df1ec0Jesse Wilson    public void testGetResponseCodeNoResponseBody() throws Exception {
438f14bee4dbf9f724a177a85a7b73f7b0bc6df1ec0Jesse Wilson        server.enqueue(new MockResponse()
439f14bee4dbf9f724a177a85a7b73f7b0bc6df1ec0Jesse Wilson                .addHeader("abc: def"));
440f14bee4dbf9f724a177a85a7b73f7b0bc6df1ec0Jesse Wilson        server.play();
441f14bee4dbf9f724a177a85a7b73f7b0bc6df1ec0Jesse Wilson
442f14bee4dbf9f724a177a85a7b73f7b0bc6df1ec0Jesse Wilson        URL url = server.getUrl("/");
443f14bee4dbf9f724a177a85a7b73f7b0bc6df1ec0Jesse Wilson        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
444f14bee4dbf9f724a177a85a7b73f7b0bc6df1ec0Jesse Wilson        conn.setDoInput(false);
445f14bee4dbf9f724a177a85a7b73f7b0bc6df1ec0Jesse Wilson        assertEquals("def", conn.getHeaderField("abc"));
446f14bee4dbf9f724a177a85a7b73f7b0bc6df1ec0Jesse Wilson        assertEquals(200, conn.getResponseCode());
447f14bee4dbf9f724a177a85a7b73f7b0bc6df1ec0Jesse Wilson        try {
448f14bee4dbf9f724a177a85a7b73f7b0bc6df1ec0Jesse Wilson            conn.getInputStream();
449f14bee4dbf9f724a177a85a7b73f7b0bc6df1ec0Jesse Wilson            fail();
450f14bee4dbf9f724a177a85a7b73f7b0bc6df1ec0Jesse Wilson        } catch (ProtocolException expected) {
451f14bee4dbf9f724a177a85a7b73f7b0bc6df1ec0Jesse Wilson        }
452f14bee4dbf9f724a177a85a7b73f7b0bc6df1ec0Jesse Wilson    }
453f14bee4dbf9f724a177a85a7b73f7b0bc6df1ec0Jesse Wilson
45460476787f0e0f052366d8031c74e507ffd3d16a3Jesse Wilson    public void testConnectViaHttps() throws IOException, InterruptedException {
45560476787f0e0f052366d8031c74e507ffd3d16a3Jesse Wilson        TestSSLContext testSSLContext = TestSSLContext.create();
45660476787f0e0f052366d8031c74e507ffd3d16a3Jesse Wilson
457059dbc04218144f985b20a228bbe98139d400d0cBrian Carlstrom        server.useHttps(testSSLContext.serverContext.getSocketFactory(), false);
458c0372d90016d241ac979faa6fa1731f30b6f2a03Jesse Wilson        server.enqueue(new MockResponse().setBody("this response comes via HTTPS"));
45960476787f0e0f052366d8031c74e507ffd3d16a3Jesse Wilson        server.play();
46060476787f0e0f052366d8031c74e507ffd3d16a3Jesse Wilson
461096aac7b8a607d3da237900f52cab1c5066bf992Jesse Wilson        HttpsURLConnection connection = (HttpsURLConnection) server.getUrl("/foo").openConnection();
4624559b1d37edcb5d7f1da086cf2e3290388d74f46Brian Carlstrom        connection.setSSLSocketFactory(testSSLContext.clientContext.getSocketFactory());
46360476787f0e0f052366d8031c74e507ffd3d16a3Jesse Wilson
464c8977f474b30c5f3807398859a6b16687af6fc7bJesse Wilson        assertContent("this response comes via HTTPS", connection);
46560476787f0e0f052366d8031c74e507ffd3d16a3Jesse Wilson
46660476787f0e0f052366d8031c74e507ffd3d16a3Jesse Wilson        RecordedRequest request = server.takeRequest();
46760476787f0e0f052366d8031c74e507ffd3d16a3Jesse Wilson        assertEquals("GET /foo HTTP/1.1", request.getRequestLine());
4683d74b4bec8543e6e3f89eafe3afe0925f3a69f01Brian Carlstrom        assertEquals("TLSv1", request.getSslProtocol());
46960476787f0e0f052366d8031c74e507ffd3d16a3Jesse Wilson    }
47060476787f0e0f052366d8031c74e507ffd3d16a3Jesse Wilson
471096aac7b8a607d3da237900f52cab1c5066bf992Jesse Wilson    public void testConnectViaHttpsReusingConnections() throws IOException, InterruptedException {
472096aac7b8a607d3da237900f52cab1c5066bf992Jesse Wilson        TestSSLContext testSSLContext = TestSSLContext.create();
473fa5e8dfe3c7ed144b0fbe69091628dedd6a3b961Jesse Wilson        SSLSocketFactory clientSocketFactory = testSSLContext.clientContext.getSocketFactory();
474096aac7b8a607d3da237900f52cab1c5066bf992Jesse Wilson
475059dbc04218144f985b20a228bbe98139d400d0cBrian Carlstrom        server.useHttps(testSSLContext.serverContext.getSocketFactory(), false);
476096aac7b8a607d3da237900f52cab1c5066bf992Jesse Wilson        server.enqueue(new MockResponse().setBody("this response comes via HTTPS"));
477096aac7b8a607d3da237900f52cab1c5066bf992Jesse Wilson        server.enqueue(new MockResponse().setBody("another response via HTTPS"));
478096aac7b8a607d3da237900f52cab1c5066bf992Jesse Wilson        server.play();
479096aac7b8a607d3da237900f52cab1c5066bf992Jesse Wilson
480b7155fd57239e986bbaba254a91aeb9600d60305Jesse Wilson        HttpsURLConnection connection = (HttpsURLConnection) server.getUrl("/").openConnection();
481fa5e8dfe3c7ed144b0fbe69091628dedd6a3b961Jesse Wilson        connection.setSSLSocketFactory(clientSocketFactory);
482b7155fd57239e986bbaba254a91aeb9600d60305Jesse Wilson        assertContent("this response comes via HTTPS", connection);
483b7155fd57239e986bbaba254a91aeb9600d60305Jesse Wilson
484b7155fd57239e986bbaba254a91aeb9600d60305Jesse Wilson        connection = (HttpsURLConnection) server.getUrl("/").openConnection();
485fa5e8dfe3c7ed144b0fbe69091628dedd6a3b961Jesse Wilson        connection.setSSLSocketFactory(clientSocketFactory);
486b7155fd57239e986bbaba254a91aeb9600d60305Jesse Wilson        assertContent("another response via HTTPS", connection);
487b7155fd57239e986bbaba254a91aeb9600d60305Jesse Wilson
488b7155fd57239e986bbaba254a91aeb9600d60305Jesse Wilson        assertEquals(0, server.takeRequest().getSequenceNumber());
489b7155fd57239e986bbaba254a91aeb9600d60305Jesse Wilson        assertEquals(1, server.takeRequest().getSequenceNumber());
490b7155fd57239e986bbaba254a91aeb9600d60305Jesse Wilson    }
491b7155fd57239e986bbaba254a91aeb9600d60305Jesse Wilson
4928116f7e97e00d223e7fbe5c950c9a5e3277de124Jesse Wilson    public void testConnectViaHttpsReusingConnectionsDifferentFactories()
493b7155fd57239e986bbaba254a91aeb9600d60305Jesse Wilson            throws IOException, InterruptedException {
494b7155fd57239e986bbaba254a91aeb9600d60305Jesse Wilson        TestSSLContext testSSLContext = TestSSLContext.create();
495b7155fd57239e986bbaba254a91aeb9600d60305Jesse Wilson
496b7155fd57239e986bbaba254a91aeb9600d60305Jesse Wilson        server.useHttps(testSSLContext.serverContext.getSocketFactory(), false);
497b7155fd57239e986bbaba254a91aeb9600d60305Jesse Wilson        server.enqueue(new MockResponse().setBody("this response comes via HTTPS"));
498b7155fd57239e986bbaba254a91aeb9600d60305Jesse Wilson        server.enqueue(new MockResponse().setBody("another response via HTTPS"));
499b7155fd57239e986bbaba254a91aeb9600d60305Jesse Wilson        server.play();
500b7155fd57239e986bbaba254a91aeb9600d60305Jesse Wilson
501096aac7b8a607d3da237900f52cab1c5066bf992Jesse Wilson        // install a custom SSL socket factory so the server can be authorized
502096aac7b8a607d3da237900f52cab1c5066bf992Jesse Wilson        HttpsURLConnection connection = (HttpsURLConnection) server.getUrl("/").openConnection();
503059dbc04218144f985b20a228bbe98139d400d0cBrian Carlstrom        connection.setSSLSocketFactory(testSSLContext.clientContext.getSocketFactory());
504096aac7b8a607d3da237900f52cab1c5066bf992Jesse Wilson        assertContent("this response comes via HTTPS", connection);
505096aac7b8a607d3da237900f52cab1c5066bf992Jesse Wilson
506096aac7b8a607d3da237900f52cab1c5066bf992Jesse Wilson        connection = (HttpsURLConnection) server.getUrl("/").openConnection();
507096aac7b8a607d3da237900f52cab1c5066bf992Jesse Wilson        try {
508096aac7b8a607d3da237900f52cab1c5066bf992Jesse Wilson            readAscii(connection.getInputStream(), Integer.MAX_VALUE);
509b7155fd57239e986bbaba254a91aeb9600d60305Jesse Wilson            fail("without an SSL socket factory, the connection should fail");
510096aac7b8a607d3da237900f52cab1c5066bf992Jesse Wilson        } catch (SSLException expected) {
511096aac7b8a607d3da237900f52cab1c5066bf992Jesse Wilson        }
512096aac7b8a607d3da237900f52cab1c5066bf992Jesse Wilson    }
513096aac7b8a607d3da237900f52cab1c5066bf992Jesse Wilson
5144559b1d37edcb5d7f1da086cf2e3290388d74f46Brian Carlstrom    public void testConnectViaHttpsWithSSLFallback() throws IOException, InterruptedException {
5154559b1d37edcb5d7f1da086cf2e3290388d74f46Brian Carlstrom        TestSSLContext testSSLContext = TestSSLContext.create();
5164559b1d37edcb5d7f1da086cf2e3290388d74f46Brian Carlstrom
5174559b1d37edcb5d7f1da086cf2e3290388d74f46Brian Carlstrom        server.useHttps(testSSLContext.serverContext.getSocketFactory(), false);
518e942f46f10bb9384a1b186b3d7b74f9704c57090Jesse Wilson        server.enqueue(new MockResponse().setSocketPolicy(DISCONNECT_AT_START));
5194559b1d37edcb5d7f1da086cf2e3290388d74f46Brian Carlstrom        server.enqueue(new MockResponse().setBody("this response comes via SSL"));
5204559b1d37edcb5d7f1da086cf2e3290388d74f46Brian Carlstrom        server.play();
5214559b1d37edcb5d7f1da086cf2e3290388d74f46Brian Carlstrom
5224559b1d37edcb5d7f1da086cf2e3290388d74f46Brian Carlstrom        HttpsURLConnection connection = (HttpsURLConnection) server.getUrl("/foo").openConnection();
5234559b1d37edcb5d7f1da086cf2e3290388d74f46Brian Carlstrom        connection.setSSLSocketFactory(testSSLContext.clientContext.getSocketFactory());
5244559b1d37edcb5d7f1da086cf2e3290388d74f46Brian Carlstrom
5254559b1d37edcb5d7f1da086cf2e3290388d74f46Brian Carlstrom        assertContent("this response comes via SSL", connection);
5264559b1d37edcb5d7f1da086cf2e3290388d74f46Brian Carlstrom
5274559b1d37edcb5d7f1da086cf2e3290388d74f46Brian Carlstrom        RecordedRequest request = server.takeRequest();
5284559b1d37edcb5d7f1da086cf2e3290388d74f46Brian Carlstrom        assertEquals("GET /foo HTTP/1.1", request.getRequestLine());
5294559b1d37edcb5d7f1da086cf2e3290388d74f46Brian Carlstrom    }
5304559b1d37edcb5d7f1da086cf2e3290388d74f46Brian Carlstrom
5312915378e253f08e47fe5a9bfd026cd1ca7c6c351Brian Carlstrom    /**
5322915378e253f08e47fe5a9bfd026cd1ca7c6c351Brian Carlstrom     * Verify that we don't retry connections on certificate verification errors.
5332915378e253f08e47fe5a9bfd026cd1ca7c6c351Brian Carlstrom     *
5342915378e253f08e47fe5a9bfd026cd1ca7c6c351Brian Carlstrom     * http://code.google.com/p/android/issues/detail?id=13178
5352915378e253f08e47fe5a9bfd026cd1ca7c6c351Brian Carlstrom     */
5362915378e253f08e47fe5a9bfd026cd1ca7c6c351Brian Carlstrom    public void testConnectViaHttpsToUntrustedServer() throws IOException, InterruptedException {
5372915378e253f08e47fe5a9bfd026cd1ca7c6c351Brian Carlstrom        TestSSLContext testSSLContext = TestSSLContext.create(TestKeyStore.getClientCA2(),
5382915378e253f08e47fe5a9bfd026cd1ca7c6c351Brian Carlstrom                                                              TestKeyStore.getServer());
5392915378e253f08e47fe5a9bfd026cd1ca7c6c351Brian Carlstrom
5402915378e253f08e47fe5a9bfd026cd1ca7c6c351Brian Carlstrom        server.useHttps(testSSLContext.serverContext.getSocketFactory(), false);
5412915378e253f08e47fe5a9bfd026cd1ca7c6c351Brian Carlstrom        server.enqueue(new MockResponse()); // unused
5422915378e253f08e47fe5a9bfd026cd1ca7c6c351Brian Carlstrom        server.play();
5432915378e253f08e47fe5a9bfd026cd1ca7c6c351Brian Carlstrom
5442915378e253f08e47fe5a9bfd026cd1ca7c6c351Brian Carlstrom        HttpsURLConnection connection = (HttpsURLConnection) server.getUrl("/foo").openConnection();
5452915378e253f08e47fe5a9bfd026cd1ca7c6c351Brian Carlstrom        connection.setSSLSocketFactory(testSSLContext.clientContext.getSocketFactory());
5462915378e253f08e47fe5a9bfd026cd1ca7c6c351Brian Carlstrom        try {
5472915378e253f08e47fe5a9bfd026cd1ca7c6c351Brian Carlstrom            connection.getInputStream();
5482915378e253f08e47fe5a9bfd026cd1ca7c6c351Brian Carlstrom            fail();
5492915378e253f08e47fe5a9bfd026cd1ca7c6c351Brian Carlstrom        } catch (SSLHandshakeException expected) {
5502915378e253f08e47fe5a9bfd026cd1ca7c6c351Brian Carlstrom            assertTrue(expected.getCause() instanceof CertificateException);
5512915378e253f08e47fe5a9bfd026cd1ca7c6c351Brian Carlstrom        }
5522915378e253f08e47fe5a9bfd026cd1ca7c6c351Brian Carlstrom        assertEquals(0, server.getRequestCount());
5532915378e253f08e47fe5a9bfd026cd1ca7c6c351Brian Carlstrom    }
5542915378e253f08e47fe5a9bfd026cd1ca7c6c351Brian Carlstrom
555984fcff696380abd6ea14e80030f9fd2d09dbad0Jesse Wilson    public void testConnectViaProxyUsingProxyArg() throws Exception {
556984fcff696380abd6ea14e80030f9fd2d09dbad0Jesse Wilson        testConnectViaProxy(ProxyConfig.CREATE_ARG);
557984fcff696380abd6ea14e80030f9fd2d09dbad0Jesse Wilson    }
558984fcff696380abd6ea14e80030f9fd2d09dbad0Jesse Wilson
559984fcff696380abd6ea14e80030f9fd2d09dbad0Jesse Wilson    public void testConnectViaProxyUsingProxySystemProperty() throws Exception {
560984fcff696380abd6ea14e80030f9fd2d09dbad0Jesse Wilson        testConnectViaProxy(ProxyConfig.PROXY_SYSTEM_PROPERTY);
561984fcff696380abd6ea14e80030f9fd2d09dbad0Jesse Wilson    }
562984fcff696380abd6ea14e80030f9fd2d09dbad0Jesse Wilson
563984fcff696380abd6ea14e80030f9fd2d09dbad0Jesse Wilson    public void testConnectViaProxyUsingHttpProxySystemProperty() throws Exception {
564984fcff696380abd6ea14e80030f9fd2d09dbad0Jesse Wilson        testConnectViaProxy(ProxyConfig.HTTP_PROXY_SYSTEM_PROPERTY);
565984fcff696380abd6ea14e80030f9fd2d09dbad0Jesse Wilson    }
566984fcff696380abd6ea14e80030f9fd2d09dbad0Jesse Wilson
567984fcff696380abd6ea14e80030f9fd2d09dbad0Jesse Wilson    private void testConnectViaProxy(ProxyConfig proxyConfig) throws Exception {
568c0372d90016d241ac979faa6fa1731f30b6f2a03Jesse Wilson        MockResponse mockResponse = new MockResponse().setBody("this response comes via a proxy");
56951e468abf2628ce964d3657042f3ac8f2c947504Jesse Wilson        server.enqueue(mockResponse);
57051e468abf2628ce964d3657042f3ac8f2c947504Jesse Wilson        server.play();
57160476787f0e0f052366d8031c74e507ffd3d16a3Jesse Wilson
572984fcff696380abd6ea14e80030f9fd2d09dbad0Jesse Wilson        URL url = new URL("http://android.com/foo");
573984fcff696380abd6ea14e80030f9fd2d09dbad0Jesse Wilson        HttpURLConnection connection = proxyConfig.connect(server, url);
574c8977f474b30c5f3807398859a6b16687af6fc7bJesse Wilson        assertContent("this response comes via a proxy", connection);
57560476787f0e0f052366d8031c74e507ffd3d16a3Jesse Wilson
57651e468abf2628ce964d3657042f3ac8f2c947504Jesse Wilson        RecordedRequest request = server.takeRequest();
57760476787f0e0f052366d8031c74e507ffd3d16a3Jesse Wilson        assertEquals("GET http://android.com/foo HTTP/1.1", request.getRequestLine());
57860476787f0e0f052366d8031c74e507ffd3d16a3Jesse Wilson        assertContains(request.getHeaders(), "Host: android.com");
57960476787f0e0f052366d8031c74e507ffd3d16a3Jesse Wilson    }
58060476787f0e0f052366d8031c74e507ffd3d16a3Jesse Wilson
581c8977f474b30c5f3807398859a6b16687af6fc7bJesse Wilson    public void testContentDisagreesWithContentLengthHeader() throws IOException {
582c8977f474b30c5f3807398859a6b16687af6fc7bJesse Wilson        server.enqueue(new MockResponse()
583c8977f474b30c5f3807398859a6b16687af6fc7bJesse Wilson                .setBody("abc\r\nYOU SHOULD NOT SEE THIS")
584c8977f474b30c5f3807398859a6b16687af6fc7bJesse Wilson                .clearHeaders()
585c8977f474b30c5f3807398859a6b16687af6fc7bJesse Wilson                .addHeader("Content-Length: 3"));
586c8977f474b30c5f3807398859a6b16687af6fc7bJesse Wilson        server.play();
587c8977f474b30c5f3807398859a6b16687af6fc7bJesse Wilson
588c8977f474b30c5f3807398859a6b16687af6fc7bJesse Wilson        assertContent("abc", server.getUrl("/").openConnection());
589c8977f474b30c5f3807398859a6b16687af6fc7bJesse Wilson    }
590c8977f474b30c5f3807398859a6b16687af6fc7bJesse Wilson
591c8977f474b30c5f3807398859a6b16687af6fc7bJesse Wilson    public void testContentDisagreesWithChunkedHeader() throws IOException {
592c8977f474b30c5f3807398859a6b16687af6fc7bJesse Wilson        MockResponse mockResponse = new MockResponse();
593c8977f474b30c5f3807398859a6b16687af6fc7bJesse Wilson        mockResponse.setChunkedBody("abc", 3);
594c8977f474b30c5f3807398859a6b16687af6fc7bJesse Wilson        ByteArrayOutputStream bytesOut = new ByteArrayOutputStream();
595c8977f474b30c5f3807398859a6b16687af6fc7bJesse Wilson        bytesOut.write(mockResponse.getBody());
596c8977f474b30c5f3807398859a6b16687af6fc7bJesse Wilson        bytesOut.write("\r\nYOU SHOULD NOT SEE THIS".getBytes());
597c8977f474b30c5f3807398859a6b16687af6fc7bJesse Wilson        mockResponse.setBody(bytesOut.toByteArray());
598c8977f474b30c5f3807398859a6b16687af6fc7bJesse Wilson        mockResponse.clearHeaders();
599c8977f474b30c5f3807398859a6b16687af6fc7bJesse Wilson        mockResponse.addHeader("Transfer-encoding: chunked");
600c8977f474b30c5f3807398859a6b16687af6fc7bJesse Wilson
601c8977f474b30c5f3807398859a6b16687af6fc7bJesse Wilson        server.enqueue(mockResponse);
602c8977f474b30c5f3807398859a6b16687af6fc7bJesse Wilson        server.play();
603c8977f474b30c5f3807398859a6b16687af6fc7bJesse Wilson
604c8977f474b30c5f3807398859a6b16687af6fc7bJesse Wilson        assertContent("abc", server.getUrl("/").openConnection());
605c8977f474b30c5f3807398859a6b16687af6fc7bJesse Wilson    }
606c8977f474b30c5f3807398859a6b16687af6fc7bJesse Wilson
607f02c695ed03e708623d9365dec26d533356ef2d0Brian Carlstrom    public void testConnectViaHttpProxyToHttpsUsingProxyArgWithNoProxy() throws Exception {
608f02c695ed03e708623d9365dec26d533356ef2d0Brian Carlstrom        testConnectViaDirectProxyToHttps(ProxyConfig.NO_PROXY);
609f02c695ed03e708623d9365dec26d533356ef2d0Brian Carlstrom    }
610f02c695ed03e708623d9365dec26d533356ef2d0Brian Carlstrom
611f02c695ed03e708623d9365dec26d533356ef2d0Brian Carlstrom    public void testConnectViaHttpProxyToHttpsUsingHttpProxySystemProperty() throws Exception {
612f02c695ed03e708623d9365dec26d533356ef2d0Brian Carlstrom        // https should not use http proxy
613f02c695ed03e708623d9365dec26d533356ef2d0Brian Carlstrom        testConnectViaDirectProxyToHttps(ProxyConfig.HTTP_PROXY_SYSTEM_PROPERTY);
614f02c695ed03e708623d9365dec26d533356ef2d0Brian Carlstrom    }
615f02c695ed03e708623d9365dec26d533356ef2d0Brian Carlstrom
616f02c695ed03e708623d9365dec26d533356ef2d0Brian Carlstrom    private void testConnectViaDirectProxyToHttps(ProxyConfig proxyConfig) throws Exception {
617f02c695ed03e708623d9365dec26d533356ef2d0Brian Carlstrom        TestSSLContext testSSLContext = TestSSLContext.create();
618f02c695ed03e708623d9365dec26d533356ef2d0Brian Carlstrom
619f02c695ed03e708623d9365dec26d533356ef2d0Brian Carlstrom        server.useHttps(testSSLContext.serverContext.getSocketFactory(), false);
620f02c695ed03e708623d9365dec26d533356ef2d0Brian Carlstrom        server.enqueue(new MockResponse().setBody("this response comes via HTTPS"));
621f02c695ed03e708623d9365dec26d533356ef2d0Brian Carlstrom        server.play();
622f02c695ed03e708623d9365dec26d533356ef2d0Brian Carlstrom
623f02c695ed03e708623d9365dec26d533356ef2d0Brian Carlstrom        URL url = server.getUrl("/foo");
624f02c695ed03e708623d9365dec26d533356ef2d0Brian Carlstrom        HttpsURLConnection connection = (HttpsURLConnection) proxyConfig.connect(server, url);
625f02c695ed03e708623d9365dec26d533356ef2d0Brian Carlstrom        connection.setSSLSocketFactory(testSSLContext.clientContext.getSocketFactory());
626f02c695ed03e708623d9365dec26d533356ef2d0Brian Carlstrom
627f02c695ed03e708623d9365dec26d533356ef2d0Brian Carlstrom        assertContent("this response comes via HTTPS", connection);
628f02c695ed03e708623d9365dec26d533356ef2d0Brian Carlstrom
629f02c695ed03e708623d9365dec26d533356ef2d0Brian Carlstrom        RecordedRequest request = server.takeRequest();
630f02c695ed03e708623d9365dec26d533356ef2d0Brian Carlstrom        assertEquals("GET /foo HTTP/1.1", request.getRequestLine());
631f02c695ed03e708623d9365dec26d533356ef2d0Brian Carlstrom    }
632f02c695ed03e708623d9365dec26d533356ef2d0Brian Carlstrom
633f02c695ed03e708623d9365dec26d533356ef2d0Brian Carlstrom
634984fcff696380abd6ea14e80030f9fd2d09dbad0Jesse Wilson    public void testConnectViaHttpProxyToHttpsUsingProxyArg() throws Exception {
635984fcff696380abd6ea14e80030f9fd2d09dbad0Jesse Wilson        testConnectViaHttpProxyToHttps(ProxyConfig.CREATE_ARG);
636984fcff696380abd6ea14e80030f9fd2d09dbad0Jesse Wilson    }
637984fcff696380abd6ea14e80030f9fd2d09dbad0Jesse Wilson
638984fcff696380abd6ea14e80030f9fd2d09dbad0Jesse Wilson    /**
639984fcff696380abd6ea14e80030f9fd2d09dbad0Jesse Wilson     * We weren't honoring all of the appropriate proxy system properties when
640984fcff696380abd6ea14e80030f9fd2d09dbad0Jesse Wilson     * connecting via HTTPS. http://b/3097518
641984fcff696380abd6ea14e80030f9fd2d09dbad0Jesse Wilson     */
642984fcff696380abd6ea14e80030f9fd2d09dbad0Jesse Wilson    public void testConnectViaHttpProxyToHttpsUsingProxySystemProperty() throws Exception {
643984fcff696380abd6ea14e80030f9fd2d09dbad0Jesse Wilson        testConnectViaHttpProxyToHttps(ProxyConfig.PROXY_SYSTEM_PROPERTY);
644984fcff696380abd6ea14e80030f9fd2d09dbad0Jesse Wilson    }
645984fcff696380abd6ea14e80030f9fd2d09dbad0Jesse Wilson
646984fcff696380abd6ea14e80030f9fd2d09dbad0Jesse Wilson    public void testConnectViaHttpProxyToHttpsUsingHttpsProxySystemProperty() throws Exception {
647984fcff696380abd6ea14e80030f9fd2d09dbad0Jesse Wilson        testConnectViaHttpProxyToHttps(ProxyConfig.HTTPS_PROXY_SYSTEM_PROPERTY);
648984fcff696380abd6ea14e80030f9fd2d09dbad0Jesse Wilson    }
649984fcff696380abd6ea14e80030f9fd2d09dbad0Jesse Wilson
650984fcff696380abd6ea14e80030f9fd2d09dbad0Jesse Wilson    /**
651984fcff696380abd6ea14e80030f9fd2d09dbad0Jesse Wilson     * We were verifying the wrong hostname when connecting to an HTTPS site
652984fcff696380abd6ea14e80030f9fd2d09dbad0Jesse Wilson     * through a proxy. http://b/3097277
653984fcff696380abd6ea14e80030f9fd2d09dbad0Jesse Wilson     */
654984fcff696380abd6ea14e80030f9fd2d09dbad0Jesse Wilson    private void testConnectViaHttpProxyToHttps(ProxyConfig proxyConfig) throws Exception {
65560476787f0e0f052366d8031c74e507ffd3d16a3Jesse Wilson        TestSSLContext testSSLContext = TestSSLContext.create();
656984fcff696380abd6ea14e80030f9fd2d09dbad0Jesse Wilson        RecordingHostnameVerifier hostnameVerifier = new RecordingHostnameVerifier();
65760476787f0e0f052366d8031c74e507ffd3d16a3Jesse Wilson
658059dbc04218144f985b20a228bbe98139d400d0cBrian Carlstrom        server.useHttps(testSSLContext.serverContext.getSocketFactory(), true);
659c996149b500fc4825156106554457fe2394ae087Jesse Wilson        server.enqueue(new MockResponse()
660c996149b500fc4825156106554457fe2394ae087Jesse Wilson                .setSocketPolicy(SocketPolicy.UPGRADE_TO_SSL_AT_END)
661c996149b500fc4825156106554457fe2394ae087Jesse Wilson                .clearHeaders());
662c0372d90016d241ac979faa6fa1731f30b6f2a03Jesse Wilson        server.enqueue(new MockResponse().setBody("this response comes via a secure proxy"));
66351e468abf2628ce964d3657042f3ac8f2c947504Jesse Wilson        server.play();
66460476787f0e0f052366d8031c74e507ffd3d16a3Jesse Wilson
66560476787f0e0f052366d8031c74e507ffd3d16a3Jesse Wilson        URL url = new URL("https://android.com/foo");
666984fcff696380abd6ea14e80030f9fd2d09dbad0Jesse Wilson        HttpsURLConnection connection = (HttpsURLConnection) proxyConfig.connect(server, url);
667059dbc04218144f985b20a228bbe98139d400d0cBrian Carlstrom        connection.setSSLSocketFactory(testSSLContext.clientContext.getSocketFactory());
668984fcff696380abd6ea14e80030f9fd2d09dbad0Jesse Wilson        connection.setHostnameVerifier(hostnameVerifier);
66960476787f0e0f052366d8031c74e507ffd3d16a3Jesse Wilson
670c8977f474b30c5f3807398859a6b16687af6fc7bJesse Wilson        assertContent("this response comes via a secure proxy", connection);
67160476787f0e0f052366d8031c74e507ffd3d16a3Jesse Wilson
67251e468abf2628ce964d3657042f3ac8f2c947504Jesse Wilson        RecordedRequest connect = server.takeRequest();
67360476787f0e0f052366d8031c74e507ffd3d16a3Jesse Wilson        assertEquals("Connect line failure on proxy",
67460476787f0e0f052366d8031c74e507ffd3d16a3Jesse Wilson                "CONNECT android.com:443 HTTP/1.1", connect.getRequestLine());
67560476787f0e0f052366d8031c74e507ffd3d16a3Jesse Wilson        assertContains(connect.getHeaders(), "Host: android.com");
67660476787f0e0f052366d8031c74e507ffd3d16a3Jesse Wilson
67751e468abf2628ce964d3657042f3ac8f2c947504Jesse Wilson        RecordedRequest get = server.takeRequest();
67860476787f0e0f052366d8031c74e507ffd3d16a3Jesse Wilson        assertEquals("GET /foo HTTP/1.1", get.getRequestLine());
67960476787f0e0f052366d8031c74e507ffd3d16a3Jesse Wilson        assertContains(get.getHeaders(), "Host: android.com");
680984fcff696380abd6ea14e80030f9fd2d09dbad0Jesse Wilson        assertEquals(Arrays.asList("verify android.com"), hostnameVerifier.calls);
68160476787f0e0f052366d8031c74e507ffd3d16a3Jesse Wilson    }
68260476787f0e0f052366d8031c74e507ffd3d16a3Jesse Wilson
6834ec2d0dea800397fb32227e0631246f4d2a73191Brian Carlstrom
6844ec2d0dea800397fb32227e0631246f4d2a73191Brian Carlstrom    /**
6854ec2d0dea800397fb32227e0631246f4d2a73191Brian Carlstrom     * Tolerate bad https proxy response when using HttpResponseCache. http://b/6754912
6864ec2d0dea800397fb32227e0631246f4d2a73191Brian Carlstrom     */
6874ec2d0dea800397fb32227e0631246f4d2a73191Brian Carlstrom    public void testConnectViaHttpProxyToHttpsUsingBadProxyAndHttpResponseCache() throws Exception {
6884ec2d0dea800397fb32227e0631246f4d2a73191Brian Carlstrom        ProxyConfig proxyConfig = ProxyConfig.PROXY_SYSTEM_PROPERTY;
6894ec2d0dea800397fb32227e0631246f4d2a73191Brian Carlstrom
6904ec2d0dea800397fb32227e0631246f4d2a73191Brian Carlstrom        TestSSLContext testSSLContext = TestSSLContext.create();
6914ec2d0dea800397fb32227e0631246f4d2a73191Brian Carlstrom
6924ec2d0dea800397fb32227e0631246f4d2a73191Brian Carlstrom        initResponseCache();
6934ec2d0dea800397fb32227e0631246f4d2a73191Brian Carlstrom
6944ec2d0dea800397fb32227e0631246f4d2a73191Brian Carlstrom        server.useHttps(testSSLContext.serverContext.getSocketFactory(), true);
6954ec2d0dea800397fb32227e0631246f4d2a73191Brian Carlstrom        server.enqueue(new MockResponse()
6964ec2d0dea800397fb32227e0631246f4d2a73191Brian Carlstrom                .setSocketPolicy(SocketPolicy.UPGRADE_TO_SSL_AT_END)
6974ec2d0dea800397fb32227e0631246f4d2a73191Brian Carlstrom                .clearHeaders()
6984ec2d0dea800397fb32227e0631246f4d2a73191Brian Carlstrom                .setBody("bogus proxy connect response content")); // Key to reproducing b/6754912
6994ec2d0dea800397fb32227e0631246f4d2a73191Brian Carlstrom        server.play();
7004ec2d0dea800397fb32227e0631246f4d2a73191Brian Carlstrom
7014ec2d0dea800397fb32227e0631246f4d2a73191Brian Carlstrom        URL url = new URL("https://android.com/foo");
7024ec2d0dea800397fb32227e0631246f4d2a73191Brian Carlstrom        HttpsURLConnection connection = (HttpsURLConnection) proxyConfig.connect(server, url);
7034ec2d0dea800397fb32227e0631246f4d2a73191Brian Carlstrom        connection.setSSLSocketFactory(testSSLContext.clientContext.getSocketFactory());
7044ec2d0dea800397fb32227e0631246f4d2a73191Brian Carlstrom
7054ec2d0dea800397fb32227e0631246f4d2a73191Brian Carlstrom        try {
7064ec2d0dea800397fb32227e0631246f4d2a73191Brian Carlstrom            connection.connect();
7074ec2d0dea800397fb32227e0631246f4d2a73191Brian Carlstrom            fail();
7084ec2d0dea800397fb32227e0631246f4d2a73191Brian Carlstrom        } catch (IOException expected) {
7094ec2d0dea800397fb32227e0631246f4d2a73191Brian Carlstrom            // Thrown when the connect causes SSLSocket.startHandshake() to throw
7104ec2d0dea800397fb32227e0631246f4d2a73191Brian Carlstrom            // when it sees the "bogus proxy connect response content"
7114ec2d0dea800397fb32227e0631246f4d2a73191Brian Carlstrom            // instead of a ServerHello handshake message.
7124ec2d0dea800397fb32227e0631246f4d2a73191Brian Carlstrom        }
7134ec2d0dea800397fb32227e0631246f4d2a73191Brian Carlstrom
7144ec2d0dea800397fb32227e0631246f4d2a73191Brian Carlstrom        RecordedRequest connect = server.takeRequest();
7154ec2d0dea800397fb32227e0631246f4d2a73191Brian Carlstrom        assertEquals("Connect line failure on proxy",
7164ec2d0dea800397fb32227e0631246f4d2a73191Brian Carlstrom                "CONNECT android.com:443 HTTP/1.1", connect.getRequestLine());
7174ec2d0dea800397fb32227e0631246f4d2a73191Brian Carlstrom        assertContains(connect.getHeaders(), "Host: android.com");
7184ec2d0dea800397fb32227e0631246f4d2a73191Brian Carlstrom    }
7194ec2d0dea800397fb32227e0631246f4d2a73191Brian Carlstrom
7204ec2d0dea800397fb32227e0631246f4d2a73191Brian Carlstrom    private void initResponseCache() throws IOException {
7214ec2d0dea800397fb32227e0631246f4d2a73191Brian Carlstrom        String tmp = System.getProperty("java.io.tmpdir");
7224ec2d0dea800397fb32227e0631246f4d2a73191Brian Carlstrom        File cacheDir = new File(tmp, "HttpCache-" + UUID.randomUUID());
7234ec2d0dea800397fb32227e0631246f4d2a73191Brian Carlstrom        cache = new HttpResponseCache(cacheDir, Integer.MAX_VALUE);
7244ec2d0dea800397fb32227e0631246f4d2a73191Brian Carlstrom        ResponseCache.setDefault(cache);
7254ec2d0dea800397fb32227e0631246f4d2a73191Brian Carlstrom    }
7264ec2d0dea800397fb32227e0631246f4d2a73191Brian Carlstrom
727d4bddd7d1fb7b1b7f0836648228235c6e4b56a18Jesse Wilson    /**
728d4bddd7d1fb7b1b7f0836648228235c6e4b56a18Jesse Wilson     * Test which headers are sent unencrypted to the HTTP proxy.
729d4bddd7d1fb7b1b7f0836648228235c6e4b56a18Jesse Wilson     */
730d4bddd7d1fb7b1b7f0836648228235c6e4b56a18Jesse Wilson    public void testProxyConnectIncludesProxyHeadersOnly()
731d4bddd7d1fb7b1b7f0836648228235c6e4b56a18Jesse Wilson            throws IOException, InterruptedException {
732984fcff696380abd6ea14e80030f9fd2d09dbad0Jesse Wilson        RecordingHostnameVerifier hostnameVerifier = new RecordingHostnameVerifier();
733d4bddd7d1fb7b1b7f0836648228235c6e4b56a18Jesse Wilson        TestSSLContext testSSLContext = TestSSLContext.create();
734d4bddd7d1fb7b1b7f0836648228235c6e4b56a18Jesse Wilson
735d4bddd7d1fb7b1b7f0836648228235c6e4b56a18Jesse Wilson        server.useHttps(testSSLContext.serverContext.getSocketFactory(), true);
736c996149b500fc4825156106554457fe2394ae087Jesse Wilson        server.enqueue(new MockResponse()
737c996149b500fc4825156106554457fe2394ae087Jesse Wilson                .setSocketPolicy(SocketPolicy.UPGRADE_TO_SSL_AT_END)
738c996149b500fc4825156106554457fe2394ae087Jesse Wilson                .clearHeaders());
739d4bddd7d1fb7b1b7f0836648228235c6e4b56a18Jesse Wilson        server.enqueue(new MockResponse().setBody("encrypted response from the origin server"));
740d4bddd7d1fb7b1b7f0836648228235c6e4b56a18Jesse Wilson        server.play();
741d4bddd7d1fb7b1b7f0836648228235c6e4b56a18Jesse Wilson
742d4bddd7d1fb7b1b7f0836648228235c6e4b56a18Jesse Wilson        URL url = new URL("https://android.com/foo");
743d4bddd7d1fb7b1b7f0836648228235c6e4b56a18Jesse Wilson        HttpsURLConnection connection = (HttpsURLConnection) url.openConnection(
744d4bddd7d1fb7b1b7f0836648228235c6e4b56a18Jesse Wilson                server.toProxyAddress());
745d4bddd7d1fb7b1b7f0836648228235c6e4b56a18Jesse Wilson        connection.addRequestProperty("Private", "Secret");
746d4bddd7d1fb7b1b7f0836648228235c6e4b56a18Jesse Wilson        connection.addRequestProperty("Proxy-Authorization", "bar");
747d4bddd7d1fb7b1b7f0836648228235c6e4b56a18Jesse Wilson        connection.addRequestProperty("User-Agent", "baz");
748d4bddd7d1fb7b1b7f0836648228235c6e4b56a18Jesse Wilson        connection.setSSLSocketFactory(testSSLContext.clientContext.getSocketFactory());
749984fcff696380abd6ea14e80030f9fd2d09dbad0Jesse Wilson        connection.setHostnameVerifier(hostnameVerifier);
750d4bddd7d1fb7b1b7f0836648228235c6e4b56a18Jesse Wilson        assertContent("encrypted response from the origin server", connection);
751d4bddd7d1fb7b1b7f0836648228235c6e4b56a18Jesse Wilson
752d4bddd7d1fb7b1b7f0836648228235c6e4b56a18Jesse Wilson        RecordedRequest connect = server.takeRequest();
753d4bddd7d1fb7b1b7f0836648228235c6e4b56a18Jesse Wilson        assertContainsNoneMatching(connect.getHeaders(), "Private.*");
754d4bddd7d1fb7b1b7f0836648228235c6e4b56a18Jesse Wilson        assertContains(connect.getHeaders(), "Proxy-Authorization: bar");
755d4bddd7d1fb7b1b7f0836648228235c6e4b56a18Jesse Wilson        assertContains(connect.getHeaders(), "User-Agent: baz");
756d4bddd7d1fb7b1b7f0836648228235c6e4b56a18Jesse Wilson        assertContains(connect.getHeaders(), "Host: android.com");
757d4bddd7d1fb7b1b7f0836648228235c6e4b56a18Jesse Wilson        assertContains(connect.getHeaders(), "Proxy-Connection: Keep-Alive");
758d4bddd7d1fb7b1b7f0836648228235c6e4b56a18Jesse Wilson
759d4bddd7d1fb7b1b7f0836648228235c6e4b56a18Jesse Wilson        RecordedRequest get = server.takeRequest();
760d4bddd7d1fb7b1b7f0836648228235c6e4b56a18Jesse Wilson        assertContains(get.getHeaders(), "Private: Secret");
761984fcff696380abd6ea14e80030f9fd2d09dbad0Jesse Wilson        assertEquals(Arrays.asList("verify android.com"), hostnameVerifier.calls);
762d4bddd7d1fb7b1b7f0836648228235c6e4b56a18Jesse Wilson    }
763d4bddd7d1fb7b1b7f0836648228235c6e4b56a18Jesse Wilson
764c996149b500fc4825156106554457fe2394ae087Jesse Wilson    public void testProxyAuthenticateOnConnect() throws Exception {
7655757cb35ad2e58d7accb7f5d3db6f2d5e72f097dJesse Wilson        Authenticator.setDefault(new SimpleAuthenticator());
766c996149b500fc4825156106554457fe2394ae087Jesse Wilson        TestSSLContext testSSLContext = TestSSLContext.create();
767c996149b500fc4825156106554457fe2394ae087Jesse Wilson        server.useHttps(testSSLContext.serverContext.getSocketFactory(), true);
768c996149b500fc4825156106554457fe2394ae087Jesse Wilson        server.enqueue(new MockResponse()
769c996149b500fc4825156106554457fe2394ae087Jesse Wilson                .setResponseCode(407)
770c996149b500fc4825156106554457fe2394ae087Jesse Wilson                .addHeader("Proxy-Authenticate: Basic realm=\"localhost\""));
771c996149b500fc4825156106554457fe2394ae087Jesse Wilson        server.enqueue(new MockResponse()
772c996149b500fc4825156106554457fe2394ae087Jesse Wilson                .setSocketPolicy(SocketPolicy.UPGRADE_TO_SSL_AT_END)
773c996149b500fc4825156106554457fe2394ae087Jesse Wilson                .clearHeaders());
774c996149b500fc4825156106554457fe2394ae087Jesse Wilson        server.enqueue(new MockResponse().setBody("A"));
775c996149b500fc4825156106554457fe2394ae087Jesse Wilson        server.play();
776c996149b500fc4825156106554457fe2394ae087Jesse Wilson
777c996149b500fc4825156106554457fe2394ae087Jesse Wilson        URL url = new URL("https://android.com/foo");
778c996149b500fc4825156106554457fe2394ae087Jesse Wilson        HttpsURLConnection connection = (HttpsURLConnection) url.openConnection(
779c996149b500fc4825156106554457fe2394ae087Jesse Wilson                server.toProxyAddress());
780c996149b500fc4825156106554457fe2394ae087Jesse Wilson        connection.setSSLSocketFactory(testSSLContext.clientContext.getSocketFactory());
781c996149b500fc4825156106554457fe2394ae087Jesse Wilson        connection.setHostnameVerifier(new RecordingHostnameVerifier());
782c996149b500fc4825156106554457fe2394ae087Jesse Wilson        assertContent("A", connection);
783c996149b500fc4825156106554457fe2394ae087Jesse Wilson
784c996149b500fc4825156106554457fe2394ae087Jesse Wilson        RecordedRequest connect1 = server.takeRequest();
785c996149b500fc4825156106554457fe2394ae087Jesse Wilson        assertEquals("CONNECT android.com:443 HTTP/1.1", connect1.getRequestLine());
786c996149b500fc4825156106554457fe2394ae087Jesse Wilson        assertContainsNoneMatching(connect1.getHeaders(), "Proxy\\-Authorization.*");
787c996149b500fc4825156106554457fe2394ae087Jesse Wilson
788c996149b500fc4825156106554457fe2394ae087Jesse Wilson        RecordedRequest connect2 = server.takeRequest();
789c996149b500fc4825156106554457fe2394ae087Jesse Wilson        assertEquals("CONNECT android.com:443 HTTP/1.1", connect2.getRequestLine());
7905757cb35ad2e58d7accb7f5d3db6f2d5e72f097dJesse Wilson        assertContains(connect2.getHeaders(), "Proxy-Authorization: Basic "
7915757cb35ad2e58d7accb7f5d3db6f2d5e72f097dJesse Wilson                + SimpleAuthenticator.BASE_64_CREDENTIALS);
792c996149b500fc4825156106554457fe2394ae087Jesse Wilson
793c996149b500fc4825156106554457fe2394ae087Jesse Wilson        RecordedRequest get = server.takeRequest();
794c996149b500fc4825156106554457fe2394ae087Jesse Wilson        assertEquals("GET /foo HTTP/1.1", get.getRequestLine());
795c996149b500fc4825156106554457fe2394ae087Jesse Wilson        assertContainsNoneMatching(get.getHeaders(), "Proxy\\-Authorization.*");
796c996149b500fc4825156106554457fe2394ae087Jesse Wilson    }
797c996149b500fc4825156106554457fe2394ae087Jesse Wilson
798b11e44a402eb0f9c5da1f7482fc1eabdd9adff47Jesse Wilson    // Don't disconnect after building a tunnel with CONNECT
799b11e44a402eb0f9c5da1f7482fc1eabdd9adff47Jesse Wilson    // http://code.google.com/p/android/issues/detail?id=37221
800b11e44a402eb0f9c5da1f7482fc1eabdd9adff47Jesse Wilson    public void testProxyWithConnectionClose() throws IOException {
801b11e44a402eb0f9c5da1f7482fc1eabdd9adff47Jesse Wilson        TestSSLContext testSSLContext = TestSSLContext.create();
802b11e44a402eb0f9c5da1f7482fc1eabdd9adff47Jesse Wilson        server.useHttps(testSSLContext.serverContext.getSocketFactory(), true);
803b11e44a402eb0f9c5da1f7482fc1eabdd9adff47Jesse Wilson        server.enqueue(new MockResponse()
804b11e44a402eb0f9c5da1f7482fc1eabdd9adff47Jesse Wilson                .setSocketPolicy(SocketPolicy.UPGRADE_TO_SSL_AT_END)
805b11e44a402eb0f9c5da1f7482fc1eabdd9adff47Jesse Wilson                .clearHeaders());
806b11e44a402eb0f9c5da1f7482fc1eabdd9adff47Jesse Wilson        server.enqueue(new MockResponse().setBody("this response comes via a proxy"));
807b11e44a402eb0f9c5da1f7482fc1eabdd9adff47Jesse Wilson        server.play();
808b11e44a402eb0f9c5da1f7482fc1eabdd9adff47Jesse Wilson
809b11e44a402eb0f9c5da1f7482fc1eabdd9adff47Jesse Wilson        URL url = new URL("https://android.com/foo");
810b11e44a402eb0f9c5da1f7482fc1eabdd9adff47Jesse Wilson        HttpsURLConnection connection = (HttpsURLConnection) url.openConnection(
811b11e44a402eb0f9c5da1f7482fc1eabdd9adff47Jesse Wilson                server.toProxyAddress());
812b11e44a402eb0f9c5da1f7482fc1eabdd9adff47Jesse Wilson        connection.setRequestProperty("Connection", "close");
813b11e44a402eb0f9c5da1f7482fc1eabdd9adff47Jesse Wilson        connection.setSSLSocketFactory(testSSLContext.clientContext.getSocketFactory());
814b11e44a402eb0f9c5da1f7482fc1eabdd9adff47Jesse Wilson        connection.setHostnameVerifier(new RecordingHostnameVerifier());
815b11e44a402eb0f9c5da1f7482fc1eabdd9adff47Jesse Wilson
816b11e44a402eb0f9c5da1f7482fc1eabdd9adff47Jesse Wilson        assertContent("this response comes via a proxy", connection);
817b11e44a402eb0f9c5da1f7482fc1eabdd9adff47Jesse Wilson    }
818b11e44a402eb0f9c5da1f7482fc1eabdd9adff47Jesse Wilson
819d4bddd7d1fb7b1b7f0836648228235c6e4b56a18Jesse Wilson    public void testDisconnectedConnection() throws IOException {
820d4bddd7d1fb7b1b7f0836648228235c6e4b56a18Jesse Wilson        server.enqueue(new MockResponse().setBody("ABCDEFGHIJKLMNOPQR"));
821d4bddd7d1fb7b1b7f0836648228235c6e4b56a18Jesse Wilson        server.play();
822d4bddd7d1fb7b1b7f0836648228235c6e4b56a18Jesse Wilson
823d4bddd7d1fb7b1b7f0836648228235c6e4b56a18Jesse Wilson        HttpURLConnection connection = (HttpURLConnection) server.getUrl("/").openConnection();
824d4bddd7d1fb7b1b7f0836648228235c6e4b56a18Jesse Wilson        InputStream in = connection.getInputStream();
825d4bddd7d1fb7b1b7f0836648228235c6e4b56a18Jesse Wilson        assertEquals('A', (char) in.read());
826d4bddd7d1fb7b1b7f0836648228235c6e4b56a18Jesse Wilson        connection.disconnect();
827d4bddd7d1fb7b1b7f0836648228235c6e4b56a18Jesse Wilson        try {
828d4bddd7d1fb7b1b7f0836648228235c6e4b56a18Jesse Wilson            in.read();
829d4bddd7d1fb7b1b7f0836648228235c6e4b56a18Jesse Wilson            fail("Expected a connection closed exception");
830d4bddd7d1fb7b1b7f0836648228235c6e4b56a18Jesse Wilson        } catch (IOException expected) {
831d4bddd7d1fb7b1b7f0836648228235c6e4b56a18Jesse Wilson        }
832d4bddd7d1fb7b1b7f0836648228235c6e4b56a18Jesse Wilson    }
833d4bddd7d1fb7b1b7f0836648228235c6e4b56a18Jesse Wilson
834d742d7fc7f0593eb8c6e4ac9dd4c0f6a80374e46Jesse Wilson    public void testDisconnectBeforeConnect() throws IOException {
835d742d7fc7f0593eb8c6e4ac9dd4c0f6a80374e46Jesse Wilson        server.enqueue(new MockResponse().setBody("A"));
836d742d7fc7f0593eb8c6e4ac9dd4c0f6a80374e46Jesse Wilson        server.play();
837d742d7fc7f0593eb8c6e4ac9dd4c0f6a80374e46Jesse Wilson
838d742d7fc7f0593eb8c6e4ac9dd4c0f6a80374e46Jesse Wilson        HttpURLConnection connection = (HttpURLConnection) server.getUrl("/").openConnection();
839d742d7fc7f0593eb8c6e4ac9dd4c0f6a80374e46Jesse Wilson        connection.disconnect();
840d742d7fc7f0593eb8c6e4ac9dd4c0f6a80374e46Jesse Wilson
841d742d7fc7f0593eb8c6e4ac9dd4c0f6a80374e46Jesse Wilson        assertContent("A", connection);
842d742d7fc7f0593eb8c6e4ac9dd4c0f6a80374e46Jesse Wilson        assertEquals(200, connection.getResponseCode());
843d742d7fc7f0593eb8c6e4ac9dd4c0f6a80374e46Jesse Wilson    }
844d742d7fc7f0593eb8c6e4ac9dd4c0f6a80374e46Jesse Wilson
8458155888a2c4e7cc28596deec28433e1984cfaf11Brian Carlstrom    public void testDisconnectAfterOnlyResponseCodeCausesNoCloseGuardWarning() throws IOException {
8468155888a2c4e7cc28596deec28433e1984cfaf11Brian Carlstrom        CloseGuardGuard guard = new CloseGuardGuard();
8478155888a2c4e7cc28596deec28433e1984cfaf11Brian Carlstrom        try {
8488155888a2c4e7cc28596deec28433e1984cfaf11Brian Carlstrom            server.enqueue(new MockResponse()
8498155888a2c4e7cc28596deec28433e1984cfaf11Brian Carlstrom                           .setBody(gzip("ABCABCABC".getBytes("UTF-8")))
8508155888a2c4e7cc28596deec28433e1984cfaf11Brian Carlstrom                           .addHeader("Content-Encoding: gzip"));
8518155888a2c4e7cc28596deec28433e1984cfaf11Brian Carlstrom            server.play();
8528155888a2c4e7cc28596deec28433e1984cfaf11Brian Carlstrom
8538155888a2c4e7cc28596deec28433e1984cfaf11Brian Carlstrom            HttpURLConnection connection = (HttpURLConnection) server.getUrl("/").openConnection();
8548155888a2c4e7cc28596deec28433e1984cfaf11Brian Carlstrom            assertEquals(200, connection.getResponseCode());
8558155888a2c4e7cc28596deec28433e1984cfaf11Brian Carlstrom            connection.disconnect();
8568155888a2c4e7cc28596deec28433e1984cfaf11Brian Carlstrom            connection = null;
8578155888a2c4e7cc28596deec28433e1984cfaf11Brian Carlstrom            assertFalse(guard.wasCloseGuardCalled());
8588155888a2c4e7cc28596deec28433e1984cfaf11Brian Carlstrom        } finally {
8598155888a2c4e7cc28596deec28433e1984cfaf11Brian Carlstrom            guard.close();
8608155888a2c4e7cc28596deec28433e1984cfaf11Brian Carlstrom        }
8618155888a2c4e7cc28596deec28433e1984cfaf11Brian Carlstrom    }
8628155888a2c4e7cc28596deec28433e1984cfaf11Brian Carlstrom
8638155888a2c4e7cc28596deec28433e1984cfaf11Brian Carlstrom    public static class CloseGuardGuard implements Closeable, CloseGuard.Reporter  {
8648155888a2c4e7cc28596deec28433e1984cfaf11Brian Carlstrom        private final CloseGuard.Reporter oldReporter = CloseGuard.getReporter();
8658155888a2c4e7cc28596deec28433e1984cfaf11Brian Carlstrom
8668155888a2c4e7cc28596deec28433e1984cfaf11Brian Carlstrom        private AtomicBoolean closeGuardCalled = new AtomicBoolean();
8678155888a2c4e7cc28596deec28433e1984cfaf11Brian Carlstrom
8688155888a2c4e7cc28596deec28433e1984cfaf11Brian Carlstrom        public CloseGuardGuard() {
8698155888a2c4e7cc28596deec28433e1984cfaf11Brian Carlstrom            CloseGuard.setReporter(this);
8708155888a2c4e7cc28596deec28433e1984cfaf11Brian Carlstrom        }
8718155888a2c4e7cc28596deec28433e1984cfaf11Brian Carlstrom
8728155888a2c4e7cc28596deec28433e1984cfaf11Brian Carlstrom        @Override public void report(String message, Throwable allocationSite) {
8738155888a2c4e7cc28596deec28433e1984cfaf11Brian Carlstrom            oldReporter.report(message, allocationSite);
8748155888a2c4e7cc28596deec28433e1984cfaf11Brian Carlstrom            closeGuardCalled.set(true);
8758155888a2c4e7cc28596deec28433e1984cfaf11Brian Carlstrom        }
8768155888a2c4e7cc28596deec28433e1984cfaf11Brian Carlstrom
8778155888a2c4e7cc28596deec28433e1984cfaf11Brian Carlstrom        public boolean wasCloseGuardCalled() {
8783edd28a92fc86a1260347d0995e65a815d73bbbeMattias Petersson            FinalizationTester.induceFinalization();
8798155888a2c4e7cc28596deec28433e1984cfaf11Brian Carlstrom            close();
8808155888a2c4e7cc28596deec28433e1984cfaf11Brian Carlstrom            return closeGuardCalled.get();
8818155888a2c4e7cc28596deec28433e1984cfaf11Brian Carlstrom        }
8828155888a2c4e7cc28596deec28433e1984cfaf11Brian Carlstrom
8838155888a2c4e7cc28596deec28433e1984cfaf11Brian Carlstrom        @Override public void close() {
8848155888a2c4e7cc28596deec28433e1984cfaf11Brian Carlstrom            CloseGuard.setReporter(oldReporter);
8858155888a2c4e7cc28596deec28433e1984cfaf11Brian Carlstrom        }
8868155888a2c4e7cc28596deec28433e1984cfaf11Brian Carlstrom
8878155888a2c4e7cc28596deec28433e1984cfaf11Brian Carlstrom    }
8888155888a2c4e7cc28596deec28433e1984cfaf11Brian Carlstrom
889d742d7fc7f0593eb8c6e4ac9dd4c0f6a80374e46Jesse Wilson    public void testDefaultRequestProperty() throws Exception {
890d742d7fc7f0593eb8c6e4ac9dd4c0f6a80374e46Jesse Wilson        URLConnection.setDefaultRequestProperty("X-testSetDefaultRequestProperty", "A");
891d742d7fc7f0593eb8c6e4ac9dd4c0f6a80374e46Jesse Wilson        assertNull(URLConnection.getDefaultRequestProperty("X-setDefaultRequestProperty"));
892d742d7fc7f0593eb8c6e4ac9dd4c0f6a80374e46Jesse Wilson    }
893d742d7fc7f0593eb8c6e4ac9dd4c0f6a80374e46Jesse Wilson
89451e468abf2628ce964d3657042f3ac8f2c947504Jesse Wilson    /**
89551e468abf2628ce964d3657042f3ac8f2c947504Jesse Wilson     * Reads {@code count} characters from the stream. If the stream is
89651e468abf2628ce964d3657042f3ac8f2c947504Jesse Wilson     * exhausted before {@code count} characters can be read, the remaining
89751e468abf2628ce964d3657042f3ac8f2c947504Jesse Wilson     * characters are returned and the stream is closed.
89851e468abf2628ce964d3657042f3ac8f2c947504Jesse Wilson     */
89951e468abf2628ce964d3657042f3ac8f2c947504Jesse Wilson    private String readAscii(InputStream in, int count) throws IOException {
90051e468abf2628ce964d3657042f3ac8f2c947504Jesse Wilson        StringBuilder result = new StringBuilder();
90151e468abf2628ce964d3657042f3ac8f2c947504Jesse Wilson        for (int i = 0; i < count; i++) {
90251e468abf2628ce964d3657042f3ac8f2c947504Jesse Wilson            int value = in.read();
90351e468abf2628ce964d3657042f3ac8f2c947504Jesse Wilson            if (value == -1) {
90451e468abf2628ce964d3657042f3ac8f2c947504Jesse Wilson                in.close();
90551e468abf2628ce964d3657042f3ac8f2c947504Jesse Wilson                break;
90651e468abf2628ce964d3657042f3ac8f2c947504Jesse Wilson            }
90751e468abf2628ce964d3657042f3ac8f2c947504Jesse Wilson            result.append((char) value);
90851e468abf2628ce964d3657042f3ac8f2c947504Jesse Wilson        }
90951e468abf2628ce964d3657042f3ac8f2c947504Jesse Wilson        return result.toString();
91051e468abf2628ce964d3657042f3ac8f2c947504Jesse Wilson    }
91151e468abf2628ce964d3657042f3ac8f2c947504Jesse Wilson
91251e468abf2628ce964d3657042f3ac8f2c947504Jesse Wilson    public void testMarkAndResetWithContentLengthHeader() throws IOException {
91351e468abf2628ce964d3657042f3ac8f2c947504Jesse Wilson        testMarkAndReset(TransferKind.FIXED_LENGTH);
91451e468abf2628ce964d3657042f3ac8f2c947504Jesse Wilson    }
91551e468abf2628ce964d3657042f3ac8f2c947504Jesse Wilson
91651e468abf2628ce964d3657042f3ac8f2c947504Jesse Wilson    public void testMarkAndResetWithChunkedEncoding() throws IOException {
91751e468abf2628ce964d3657042f3ac8f2c947504Jesse Wilson        testMarkAndReset(TransferKind.CHUNKED);
91851e468abf2628ce964d3657042f3ac8f2c947504Jesse Wilson    }
91951e468abf2628ce964d3657042f3ac8f2c947504Jesse Wilson
92051e468abf2628ce964d3657042f3ac8f2c947504Jesse Wilson    public void testMarkAndResetWithNoLengthHeaders() throws IOException {
92151e468abf2628ce964d3657042f3ac8f2c947504Jesse Wilson        testMarkAndReset(TransferKind.END_OF_STREAM);
92251e468abf2628ce964d3657042f3ac8f2c947504Jesse Wilson    }
92351e468abf2628ce964d3657042f3ac8f2c947504Jesse Wilson
9240c2fd828abec671333b8b88281825fd27a783723Jesse Wilson    private void testMarkAndReset(TransferKind transferKind) throws IOException {
92551e468abf2628ce964d3657042f3ac8f2c947504Jesse Wilson        MockResponse response = new MockResponse();
92651e468abf2628ce964d3657042f3ac8f2c947504Jesse Wilson        transferKind.setBody(response, "ABCDEFGHIJKLMNOPQRSTUVWXYZ", 1024);
92751e468abf2628ce964d3657042f3ac8f2c947504Jesse Wilson        server.enqueue(response);
928953df613522e12a418cb7cb73248594d6c9f53d4Jesse Wilson        server.enqueue(response);
92951e468abf2628ce964d3657042f3ac8f2c947504Jesse Wilson        server.play();
93051e468abf2628ce964d3657042f3ac8f2c947504Jesse Wilson
93151e468abf2628ce964d3657042f3ac8f2c947504Jesse Wilson        InputStream in = server.getUrl("/").openConnection().getInputStream();
93251e468abf2628ce964d3657042f3ac8f2c947504Jesse Wilson        assertFalse("This implementation claims to support mark().", in.markSupported());
93351e468abf2628ce964d3657042f3ac8f2c947504Jesse Wilson        in.mark(5);
93451e468abf2628ce964d3657042f3ac8f2c947504Jesse Wilson        assertEquals("ABCDE", readAscii(in, 5));
93551e468abf2628ce964d3657042f3ac8f2c947504Jesse Wilson        try {
93651e468abf2628ce964d3657042f3ac8f2c947504Jesse Wilson            in.reset();
93751e468abf2628ce964d3657042f3ac8f2c947504Jesse Wilson            fail();
93851e468abf2628ce964d3657042f3ac8f2c947504Jesse Wilson        } catch (IOException expected) {
93951e468abf2628ce964d3657042f3ac8f2c947504Jesse Wilson        }
94051e468abf2628ce964d3657042f3ac8f2c947504Jesse Wilson        assertEquals("FGHIJKLMNOPQRSTUVWXYZ", readAscii(in, Integer.MAX_VALUE));
94151e468abf2628ce964d3657042f3ac8f2c947504Jesse Wilson        assertContent("ABCDEFGHIJKLMNOPQRSTUVWXYZ", server.getUrl("/").openConnection());
94251e468abf2628ce964d3657042f3ac8f2c947504Jesse Wilson    }
94351e468abf2628ce964d3657042f3ac8f2c947504Jesse Wilson
94451e468abf2628ce964d3657042f3ac8f2c947504Jesse Wilson    /**
94551e468abf2628ce964d3657042f3ac8f2c947504Jesse Wilson     * We've had a bug where we forget the HTTP response when we see response
94651e468abf2628ce964d3657042f3ac8f2c947504Jesse Wilson     * code 401. This causes a new HTTP request to be issued for every call into
94751e468abf2628ce964d3657042f3ac8f2c947504Jesse Wilson     * the URLConnection.
94851e468abf2628ce964d3657042f3ac8f2c947504Jesse Wilson     */
94951e468abf2628ce964d3657042f3ac8f2c947504Jesse Wilson    public void testUnauthorizedResponseHandling() throws IOException {
95051e468abf2628ce964d3657042f3ac8f2c947504Jesse Wilson        MockResponse response = new MockResponse()
9515757cb35ad2e58d7accb7f5d3db6f2d5e72f097dJesse Wilson                .addHeader("WWW-Authenticate: Basic realm=\"protected area\"")
95251e468abf2628ce964d3657042f3ac8f2c947504Jesse Wilson                .setResponseCode(401) // UNAUTHORIZED
95351e468abf2628ce964d3657042f3ac8f2c947504Jesse Wilson                .setBody("Unauthorized");
95451e468abf2628ce964d3657042f3ac8f2c947504Jesse Wilson        server.enqueue(response);
95551e468abf2628ce964d3657042f3ac8f2c947504Jesse Wilson        server.enqueue(response);
95651e468abf2628ce964d3657042f3ac8f2c947504Jesse Wilson        server.enqueue(response);
95751e468abf2628ce964d3657042f3ac8f2c947504Jesse Wilson        server.play();
95851e468abf2628ce964d3657042f3ac8f2c947504Jesse Wilson
95951e468abf2628ce964d3657042f3ac8f2c947504Jesse Wilson        URL url = server.getUrl("/");
96051e468abf2628ce964d3657042f3ac8f2c947504Jesse Wilson        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
96151e468abf2628ce964d3657042f3ac8f2c947504Jesse Wilson
96251e468abf2628ce964d3657042f3ac8f2c947504Jesse Wilson        assertEquals(401, conn.getResponseCode());
96351e468abf2628ce964d3657042f3ac8f2c947504Jesse Wilson        assertEquals(401, conn.getResponseCode());
96451e468abf2628ce964d3657042f3ac8f2c947504Jesse Wilson        assertEquals(401, conn.getResponseCode());
96551e468abf2628ce964d3657042f3ac8f2c947504Jesse Wilson        assertEquals(1, server.getRequestCount());
96651e468abf2628ce964d3657042f3ac8f2c947504Jesse Wilson    }
96751e468abf2628ce964d3657042f3ac8f2c947504Jesse Wilson
9686906b0c12dcf3216883d0373973a252812a20d32Jesse Wilson    public void testNonHexChunkSize() throws IOException {
9696906b0c12dcf3216883d0373973a252812a20d32Jesse Wilson        server.enqueue(new MockResponse()
9706906b0c12dcf3216883d0373973a252812a20d32Jesse Wilson                .setBody("5\r\nABCDE\r\nG\r\nFGHIJKLMNOPQRSTU\r\n0\r\n\r\n")
9716906b0c12dcf3216883d0373973a252812a20d32Jesse Wilson                .clearHeaders()
9726906b0c12dcf3216883d0373973a252812a20d32Jesse Wilson                .addHeader("Transfer-encoding: chunked"));
9736906b0c12dcf3216883d0373973a252812a20d32Jesse Wilson        server.play();
9746906b0c12dcf3216883d0373973a252812a20d32Jesse Wilson
9756906b0c12dcf3216883d0373973a252812a20d32Jesse Wilson        URLConnection connection = server.getUrl("/").openConnection();
9766906b0c12dcf3216883d0373973a252812a20d32Jesse Wilson        try {
9776906b0c12dcf3216883d0373973a252812a20d32Jesse Wilson            readAscii(connection.getInputStream(), Integer.MAX_VALUE);
9786906b0c12dcf3216883d0373973a252812a20d32Jesse Wilson            fail();
9796906b0c12dcf3216883d0373973a252812a20d32Jesse Wilson        } catch (IOException e) {
9806906b0c12dcf3216883d0373973a252812a20d32Jesse Wilson        }
9816906b0c12dcf3216883d0373973a252812a20d32Jesse Wilson    }
9826906b0c12dcf3216883d0373973a252812a20d32Jesse Wilson
9836906b0c12dcf3216883d0373973a252812a20d32Jesse Wilson    public void testMissingChunkBody() throws IOException {
9846906b0c12dcf3216883d0373973a252812a20d32Jesse Wilson        server.enqueue(new MockResponse()
9856906b0c12dcf3216883d0373973a252812a20d32Jesse Wilson                .setBody("5")
9866906b0c12dcf3216883d0373973a252812a20d32Jesse Wilson                .clearHeaders()
9876906b0c12dcf3216883d0373973a252812a20d32Jesse Wilson                .addHeader("Transfer-encoding: chunked")
988e942f46f10bb9384a1b186b3d7b74f9704c57090Jesse Wilson                .setSocketPolicy(DISCONNECT_AT_END));
9896906b0c12dcf3216883d0373973a252812a20d32Jesse Wilson        server.play();
9906906b0c12dcf3216883d0373973a252812a20d32Jesse Wilson
9916906b0c12dcf3216883d0373973a252812a20d32Jesse Wilson        URLConnection connection = server.getUrl("/").openConnection();
9926906b0c12dcf3216883d0373973a252812a20d32Jesse Wilson        try {
9936906b0c12dcf3216883d0373973a252812a20d32Jesse Wilson            readAscii(connection.getInputStream(), Integer.MAX_VALUE);
9946906b0c12dcf3216883d0373973a252812a20d32Jesse Wilson            fail();
9956906b0c12dcf3216883d0373973a252812a20d32Jesse Wilson        } catch (IOException e) {
9966906b0c12dcf3216883d0373973a252812a20d32Jesse Wilson        }
9976906b0c12dcf3216883d0373973a252812a20d32Jesse Wilson    }
9986906b0c12dcf3216883d0373973a252812a20d32Jesse Wilson
99950ae32218918eae80298bd1ab8e4f588bbbabdb2Jesse Wilson    /**
100050ae32218918eae80298bd1ab8e4f588bbbabdb2Jesse Wilson     * This test checks whether connections are gzipped by default. This
100150ae32218918eae80298bd1ab8e4f588bbbabdb2Jesse Wilson     * behavior in not required by the API, so a failure of this test does not
100250ae32218918eae80298bd1ab8e4f588bbbabdb2Jesse Wilson     * imply a bug in the implementation.
100350ae32218918eae80298bd1ab8e4f588bbbabdb2Jesse Wilson     */
100450ae32218918eae80298bd1ab8e4f588bbbabdb2Jesse Wilson    public void testGzipEncodingEnabledByDefault() throws IOException, InterruptedException {
100550ae32218918eae80298bd1ab8e4f588bbbabdb2Jesse Wilson        server.enqueue(new MockResponse()
100650ae32218918eae80298bd1ab8e4f588bbbabdb2Jesse Wilson                .setBody(gzip("ABCABCABC".getBytes("UTF-8")))
100750ae32218918eae80298bd1ab8e4f588bbbabdb2Jesse Wilson                .addHeader("Content-Encoding: gzip"));
100850ae32218918eae80298bd1ab8e4f588bbbabdb2Jesse Wilson        server.play();
100950ae32218918eae80298bd1ab8e4f588bbbabdb2Jesse Wilson
101050ae32218918eae80298bd1ab8e4f588bbbabdb2Jesse Wilson        URLConnection connection = server.getUrl("/").openConnection();
101150ae32218918eae80298bd1ab8e4f588bbbabdb2Jesse Wilson        assertEquals("ABCABCABC", readAscii(connection.getInputStream(), Integer.MAX_VALUE));
10128116f7e97e00d223e7fbe5c950c9a5e3277de124Jesse Wilson        assertNull(connection.getContentEncoding());
10136d41a7cc3cb4cc684c8bece69ddc55954812ad6eNarayan Kamath        assertEquals(-1, connection.getContentLength());
101450ae32218918eae80298bd1ab8e4f588bbbabdb2Jesse Wilson
101550ae32218918eae80298bd1ab8e4f588bbbabdb2Jesse Wilson        RecordedRequest request = server.takeRequest();
101650ae32218918eae80298bd1ab8e4f588bbbabdb2Jesse Wilson        assertContains(request.getHeaders(), "Accept-Encoding: gzip");
101750ae32218918eae80298bd1ab8e4f588bbbabdb2Jesse Wilson    }
101850ae32218918eae80298bd1ab8e4f588bbbabdb2Jesse Wilson
1019deb236fb06f2a14861e7d40dea959f181cd5cf28Jesse Wilson    public void testClientConfiguredGzipContentEncoding() throws Exception {
10206d41a7cc3cb4cc684c8bece69ddc55954812ad6eNarayan Kamath        byte[] bodyBytes = gzip("ABCDEFGHIJKLMNOPQRSTUVWXYZ".getBytes("UTF-8"));
1021deb236fb06f2a14861e7d40dea959f181cd5cf28Jesse Wilson        server.enqueue(new MockResponse()
10226d41a7cc3cb4cc684c8bece69ddc55954812ad6eNarayan Kamath                .setBody(bodyBytes)
10236d41a7cc3cb4cc684c8bece69ddc55954812ad6eNarayan Kamath                .addHeader("Content-Encoding: gzip")
10246d41a7cc3cb4cc684c8bece69ddc55954812ad6eNarayan Kamath                .addHeader("Content-Length: " + bodyBytes.length));
1025deb236fb06f2a14861e7d40dea959f181cd5cf28Jesse Wilson        server.play();
1026deb236fb06f2a14861e7d40dea959f181cd5cf28Jesse Wilson
1027deb236fb06f2a14861e7d40dea959f181cd5cf28Jesse Wilson        URLConnection connection = server.getUrl("/").openConnection();
1028deb236fb06f2a14861e7d40dea959f181cd5cf28Jesse Wilson        connection.addRequestProperty("Accept-Encoding", "gzip");
1029deb236fb06f2a14861e7d40dea959f181cd5cf28Jesse Wilson        InputStream gunzippedIn = new GZIPInputStream(connection.getInputStream());
1030deb236fb06f2a14861e7d40dea959f181cd5cf28Jesse Wilson        assertEquals("ABCDEFGHIJKLMNOPQRSTUVWXYZ", readAscii(gunzippedIn, Integer.MAX_VALUE));
10316d41a7cc3cb4cc684c8bece69ddc55954812ad6eNarayan Kamath        assertEquals(bodyBytes.length, connection.getContentLength());
1032deb236fb06f2a14861e7d40dea959f181cd5cf28Jesse Wilson
1033deb236fb06f2a14861e7d40dea959f181cd5cf28Jesse Wilson        RecordedRequest request = server.takeRequest();
1034deb236fb06f2a14861e7d40dea959f181cd5cf28Jesse Wilson        assertContains(request.getHeaders(), "Accept-Encoding: gzip");
1035deb236fb06f2a14861e7d40dea959f181cd5cf28Jesse Wilson    }
1036deb236fb06f2a14861e7d40dea959f181cd5cf28Jesse Wilson
1037deb236fb06f2a14861e7d40dea959f181cd5cf28Jesse Wilson    public void testGzipAndConnectionReuseWithFixedLength() throws Exception {
1038deb236fb06f2a14861e7d40dea959f181cd5cf28Jesse Wilson        testClientConfiguredGzipContentEncodingAndConnectionReuse(TransferKind.FIXED_LENGTH);
1039deb236fb06f2a14861e7d40dea959f181cd5cf28Jesse Wilson    }
1040deb236fb06f2a14861e7d40dea959f181cd5cf28Jesse Wilson
1041deb236fb06f2a14861e7d40dea959f181cd5cf28Jesse Wilson    public void testGzipAndConnectionReuseWithChunkedEncoding() throws Exception {
1042deb236fb06f2a14861e7d40dea959f181cd5cf28Jesse Wilson        testClientConfiguredGzipContentEncodingAndConnectionReuse(TransferKind.CHUNKED);
1043deb236fb06f2a14861e7d40dea959f181cd5cf28Jesse Wilson    }
1044deb236fb06f2a14861e7d40dea959f181cd5cf28Jesse Wilson
104550ae32218918eae80298bd1ab8e4f588bbbabdb2Jesse Wilson    public void testClientConfiguredCustomContentEncoding() throws Exception {
104650ae32218918eae80298bd1ab8e4f588bbbabdb2Jesse Wilson        server.enqueue(new MockResponse()
104750ae32218918eae80298bd1ab8e4f588bbbabdb2Jesse Wilson                .setBody("ABCDE")
104850ae32218918eae80298bd1ab8e4f588bbbabdb2Jesse Wilson                .addHeader("Content-Encoding: custom"));
104950ae32218918eae80298bd1ab8e4f588bbbabdb2Jesse Wilson        server.play();
105050ae32218918eae80298bd1ab8e4f588bbbabdb2Jesse Wilson
105150ae32218918eae80298bd1ab8e4f588bbbabdb2Jesse Wilson        URLConnection connection = server.getUrl("/").openConnection();
105250ae32218918eae80298bd1ab8e4f588bbbabdb2Jesse Wilson        connection.addRequestProperty("Accept-Encoding", "custom");
105350ae32218918eae80298bd1ab8e4f588bbbabdb2Jesse Wilson        assertEquals("ABCDE", readAscii(connection.getInputStream(), Integer.MAX_VALUE));
105450ae32218918eae80298bd1ab8e4f588bbbabdb2Jesse Wilson
105550ae32218918eae80298bd1ab8e4f588bbbabdb2Jesse Wilson        RecordedRequest request = server.takeRequest();
105650ae32218918eae80298bd1ab8e4f588bbbabdb2Jesse Wilson        assertContains(request.getHeaders(), "Accept-Encoding: custom");
105750ae32218918eae80298bd1ab8e4f588bbbabdb2Jesse Wilson    }
105850ae32218918eae80298bd1ab8e4f588bbbabdb2Jesse Wilson
1059deb236fb06f2a14861e7d40dea959f181cd5cf28Jesse Wilson    /**
1060deb236fb06f2a14861e7d40dea959f181cd5cf28Jesse Wilson     * Test a bug where gzip input streams weren't exhausting the input stream,
1061deb236fb06f2a14861e7d40dea959f181cd5cf28Jesse Wilson     * which corrupted the request that followed.
1062deb236fb06f2a14861e7d40dea959f181cd5cf28Jesse Wilson     * http://code.google.com/p/android/issues/detail?id=7059
1063deb236fb06f2a14861e7d40dea959f181cd5cf28Jesse Wilson     */
1064deb236fb06f2a14861e7d40dea959f181cd5cf28Jesse Wilson    private void testClientConfiguredGzipContentEncodingAndConnectionReuse(
1065deb236fb06f2a14861e7d40dea959f181cd5cf28Jesse Wilson            TransferKind transferKind) throws Exception {
1066deb236fb06f2a14861e7d40dea959f181cd5cf28Jesse Wilson        MockResponse responseOne = new MockResponse();
1067deb236fb06f2a14861e7d40dea959f181cd5cf28Jesse Wilson        responseOne.addHeader("Content-Encoding: gzip");
1068deb236fb06f2a14861e7d40dea959f181cd5cf28Jesse Wilson        transferKind.setBody(responseOne, gzip("one (gzipped)".getBytes("UTF-8")), 5);
1069deb236fb06f2a14861e7d40dea959f181cd5cf28Jesse Wilson        server.enqueue(responseOne);
1070deb236fb06f2a14861e7d40dea959f181cd5cf28Jesse Wilson        MockResponse responseTwo = new MockResponse();
1071deb236fb06f2a14861e7d40dea959f181cd5cf28Jesse Wilson        transferKind.setBody(responseTwo, "two (identity)", 5);
1072deb236fb06f2a14861e7d40dea959f181cd5cf28Jesse Wilson        server.enqueue(responseTwo);
1073deb236fb06f2a14861e7d40dea959f181cd5cf28Jesse Wilson        server.play();
1074deb236fb06f2a14861e7d40dea959f181cd5cf28Jesse Wilson
1075deb236fb06f2a14861e7d40dea959f181cd5cf28Jesse Wilson        URLConnection connection = server.getUrl("/").openConnection();
1076deb236fb06f2a14861e7d40dea959f181cd5cf28Jesse Wilson        connection.addRequestProperty("Accept-Encoding", "gzip");
1077deb236fb06f2a14861e7d40dea959f181cd5cf28Jesse Wilson        InputStream gunzippedIn = new GZIPInputStream(connection.getInputStream());
1078deb236fb06f2a14861e7d40dea959f181cd5cf28Jesse Wilson        assertEquals("one (gzipped)", readAscii(gunzippedIn, Integer.MAX_VALUE));
1079deb236fb06f2a14861e7d40dea959f181cd5cf28Jesse Wilson        assertEquals(0, server.takeRequest().getSequenceNumber());
1080deb236fb06f2a14861e7d40dea959f181cd5cf28Jesse Wilson
1081deb236fb06f2a14861e7d40dea959f181cd5cf28Jesse Wilson        connection = server.getUrl("/").openConnection();
1082deb236fb06f2a14861e7d40dea959f181cd5cf28Jesse Wilson        assertEquals("two (identity)", readAscii(connection.getInputStream(), Integer.MAX_VALUE));
1083deb236fb06f2a14861e7d40dea959f181cd5cf28Jesse Wilson        assertEquals(1, server.takeRequest().getSequenceNumber());
1084deb236fb06f2a14861e7d40dea959f181cd5cf28Jesse Wilson    }
1085deb236fb06f2a14861e7d40dea959f181cd5cf28Jesse Wilson
1086deb236fb06f2a14861e7d40dea959f181cd5cf28Jesse Wilson    /**
1087df29c7dc69965462cd19de8910b04c8cb463e57fJesse Wilson     * Test that HEAD requests don't have a body regardless of the response
1088df29c7dc69965462cd19de8910b04c8cb463e57fJesse Wilson     * headers. http://code.google.com/p/android/issues/detail?id=24672
1089df29c7dc69965462cd19de8910b04c8cb463e57fJesse Wilson     */
1090df29c7dc69965462cd19de8910b04c8cb463e57fJesse Wilson    public void testHeadAndContentLength() throws Exception {
1091df29c7dc69965462cd19de8910b04c8cb463e57fJesse Wilson        server.enqueue(new MockResponse()
1092df29c7dc69965462cd19de8910b04c8cb463e57fJesse Wilson                .clearHeaders()
1093df29c7dc69965462cd19de8910b04c8cb463e57fJesse Wilson                .addHeader("Content-Length: 100"));
1094df29c7dc69965462cd19de8910b04c8cb463e57fJesse Wilson        server.enqueue(new MockResponse().setBody("A"));
1095df29c7dc69965462cd19de8910b04c8cb463e57fJesse Wilson        server.play();
1096df29c7dc69965462cd19de8910b04c8cb463e57fJesse Wilson
1097df29c7dc69965462cd19de8910b04c8cb463e57fJesse Wilson        HttpURLConnection connection1 = (HttpURLConnection) server.getUrl("/").openConnection();
1098df29c7dc69965462cd19de8910b04c8cb463e57fJesse Wilson        connection1.setRequestMethod("HEAD");
1099df29c7dc69965462cd19de8910b04c8cb463e57fJesse Wilson        assertEquals("100", connection1.getHeaderField("Content-Length"));
1100df29c7dc69965462cd19de8910b04c8cb463e57fJesse Wilson        assertContent("", connection1);
1101df29c7dc69965462cd19de8910b04c8cb463e57fJesse Wilson
1102df29c7dc69965462cd19de8910b04c8cb463e57fJesse Wilson        HttpURLConnection connection2 = (HttpURLConnection) server.getUrl("/").openConnection();
1103df29c7dc69965462cd19de8910b04c8cb463e57fJesse Wilson        assertEquals("A", readAscii(connection2.getInputStream(), Integer.MAX_VALUE));
1104df29c7dc69965462cd19de8910b04c8cb463e57fJesse Wilson
1105df29c7dc69965462cd19de8910b04c8cb463e57fJesse Wilson        assertEquals(0, server.takeRequest().getSequenceNumber());
1106df29c7dc69965462cd19de8910b04c8cb463e57fJesse Wilson        assertEquals(1, server.takeRequest().getSequenceNumber());
1107df29c7dc69965462cd19de8910b04c8cb463e57fJesse Wilson    }
1108df29c7dc69965462cd19de8910b04c8cb463e57fJesse Wilson
1109df29c7dc69965462cd19de8910b04c8cb463e57fJesse Wilson    /**
1110ffd579b668428272b78f5c6c64f9c89766f37c1aJesse Wilson     * Obnoxiously test that the chunk sizes transmitted exactly equal the
1111ffd579b668428272b78f5c6c64f9c89766f37c1aJesse Wilson     * requested data+chunk header size. Although setChunkedStreamingMode()
1112ffd579b668428272b78f5c6c64f9c89766f37c1aJesse Wilson     * isn't specific about whether the size applies to the data or the
1113ffd579b668428272b78f5c6c64f9c89766f37c1aJesse Wilson     * complete chunk, the RI interprets it as a complete chunk.
1114ffd579b668428272b78f5c6c64f9c89766f37c1aJesse Wilson     */
1115ffd579b668428272b78f5c6c64f9c89766f37c1aJesse Wilson    public void testSetChunkedStreamingMode() throws IOException, InterruptedException {
1116ffd579b668428272b78f5c6c64f9c89766f37c1aJesse Wilson        server.enqueue(new MockResponse());
1117ffd579b668428272b78f5c6c64f9c89766f37c1aJesse Wilson        server.play();
1118ffd579b668428272b78f5c6c64f9c89766f37c1aJesse Wilson
1119ffd579b668428272b78f5c6c64f9c89766f37c1aJesse Wilson        HttpURLConnection urlConnection = (HttpURLConnection) server.getUrl("/").openConnection();
1120ffd579b668428272b78f5c6c64f9c89766f37c1aJesse Wilson        urlConnection.setChunkedStreamingMode(8);
1121ffd579b668428272b78f5c6c64f9c89766f37c1aJesse Wilson        urlConnection.setDoOutput(true);
1122ffd579b668428272b78f5c6c64f9c89766f37c1aJesse Wilson        OutputStream outputStream = urlConnection.getOutputStream();
1123ffd579b668428272b78f5c6c64f9c89766f37c1aJesse Wilson        outputStream.write("ABCDEFGHIJKLMNOPQ".getBytes("US-ASCII"));
1124ffd579b668428272b78f5c6c64f9c89766f37c1aJesse Wilson        assertEquals(200, urlConnection.getResponseCode());
1125ffd579b668428272b78f5c6c64f9c89766f37c1aJesse Wilson
1126ffd579b668428272b78f5c6c64f9c89766f37c1aJesse Wilson        RecordedRequest request = server.takeRequest();
1127ffd579b668428272b78f5c6c64f9c89766f37c1aJesse Wilson        assertEquals("ABCDEFGHIJKLMNOPQ", new String(request.getBody(), "US-ASCII"));
1128ffd579b668428272b78f5c6c64f9c89766f37c1aJesse Wilson        assertEquals(Arrays.asList(3, 3, 3, 3, 3, 2), request.getChunkSizes());
1129ffd579b668428272b78f5c6c64f9c89766f37c1aJesse Wilson    }
1130ffd579b668428272b78f5c6c64f9c89766f37c1aJesse Wilson
1131ffd579b668428272b78f5c6c64f9c89766f37c1aJesse Wilson    public void testAuthenticateWithFixedLengthStreaming() throws Exception {
1132ffd579b668428272b78f5c6c64f9c89766f37c1aJesse Wilson        testAuthenticateWithStreamingPost(StreamingMode.FIXED_LENGTH);
1133ffd579b668428272b78f5c6c64f9c89766f37c1aJesse Wilson    }
1134ffd579b668428272b78f5c6c64f9c89766f37c1aJesse Wilson
1135ffd579b668428272b78f5c6c64f9c89766f37c1aJesse Wilson    public void testAuthenticateWithChunkedStreaming() throws Exception {
1136ffd579b668428272b78f5c6c64f9c89766f37c1aJesse Wilson        testAuthenticateWithStreamingPost(StreamingMode.CHUNKED);
1137ffd579b668428272b78f5c6c64f9c89766f37c1aJesse Wilson    }
1138ffd579b668428272b78f5c6c64f9c89766f37c1aJesse Wilson
1139ffd579b668428272b78f5c6c64f9c89766f37c1aJesse Wilson    private void testAuthenticateWithStreamingPost(StreamingMode streamingMode) throws Exception {
1140ffd579b668428272b78f5c6c64f9c89766f37c1aJesse Wilson        MockResponse pleaseAuthenticate = new MockResponse()
1141ffd579b668428272b78f5c6c64f9c89766f37c1aJesse Wilson                .setResponseCode(401)
1142ffd579b668428272b78f5c6c64f9c89766f37c1aJesse Wilson                .addHeader("WWW-Authenticate: Basic realm=\"protected area\"")
1143ffd579b668428272b78f5c6c64f9c89766f37c1aJesse Wilson                .setBody("Please authenticate.");
1144ffd579b668428272b78f5c6c64f9c89766f37c1aJesse Wilson        server.enqueue(pleaseAuthenticate);
1145ffd579b668428272b78f5c6c64f9c89766f37c1aJesse Wilson        server.play();
1146ffd579b668428272b78f5c6c64f9c89766f37c1aJesse Wilson
11475757cb35ad2e58d7accb7f5d3db6f2d5e72f097dJesse Wilson        Authenticator.setDefault(new SimpleAuthenticator());
1148ffd579b668428272b78f5c6c64f9c89766f37c1aJesse Wilson        HttpURLConnection connection = (HttpURLConnection) server.getUrl("/").openConnection();
1149ffd579b668428272b78f5c6c64f9c89766f37c1aJesse Wilson        connection.setDoOutput(true);
1150ffd579b668428272b78f5c6c64f9c89766f37c1aJesse Wilson        byte[] requestBody = { 'A', 'B', 'C', 'D' };
1151ffd579b668428272b78f5c6c64f9c89766f37c1aJesse Wilson        if (streamingMode == StreamingMode.FIXED_LENGTH) {
1152ffd579b668428272b78f5c6c64f9c89766f37c1aJesse Wilson            connection.setFixedLengthStreamingMode(requestBody.length);
1153ffd579b668428272b78f5c6c64f9c89766f37c1aJesse Wilson        } else if (streamingMode == StreamingMode.CHUNKED) {
1154ffd579b668428272b78f5c6c64f9c89766f37c1aJesse Wilson            connection.setChunkedStreamingMode(0);
1155ffd579b668428272b78f5c6c64f9c89766f37c1aJesse Wilson        }
1156ffd579b668428272b78f5c6c64f9c89766f37c1aJesse Wilson        OutputStream outputStream = connection.getOutputStream();
1157ffd579b668428272b78f5c6c64f9c89766f37c1aJesse Wilson        outputStream.write(requestBody);
1158ffd579b668428272b78f5c6c64f9c89766f37c1aJesse Wilson        outputStream.close();
1159ffd579b668428272b78f5c6c64f9c89766f37c1aJesse Wilson        try {
1160ffd579b668428272b78f5c6c64f9c89766f37c1aJesse Wilson            connection.getInputStream();
1161ffd579b668428272b78f5c6c64f9c89766f37c1aJesse Wilson            fail();
1162ffd579b668428272b78f5c6c64f9c89766f37c1aJesse Wilson        } catch (HttpRetryException expected) {
1163ffd579b668428272b78f5c6c64f9c89766f37c1aJesse Wilson        }
1164ffd579b668428272b78f5c6c64f9c89766f37c1aJesse Wilson
1165ffd579b668428272b78f5c6c64f9c89766f37c1aJesse Wilson        // no authorization header for the request...
1166ffd579b668428272b78f5c6c64f9c89766f37c1aJesse Wilson        RecordedRequest request = server.takeRequest();
1167ffd579b668428272b78f5c6c64f9c89766f37c1aJesse Wilson        assertContainsNoneMatching(request.getHeaders(), "Authorization: Basic .*");
1168ffd579b668428272b78f5c6c64f9c89766f37c1aJesse Wilson        assertEquals(Arrays.toString(requestBody), Arrays.toString(request.getBody()));
1169ffd579b668428272b78f5c6c64f9c89766f37c1aJesse Wilson    }
1170ffd579b668428272b78f5c6c64f9c89766f37c1aJesse Wilson
1171ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson    public void testSetValidRequestMethod() throws Exception {
1172ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson        server.play();
1173ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson        assertValidRequestMethod("GET");
1174ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson        assertValidRequestMethod("DELETE");
1175ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson        assertValidRequestMethod("HEAD");
1176ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson        assertValidRequestMethod("OPTIONS");
1177ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson        assertValidRequestMethod("POST");
1178ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson        assertValidRequestMethod("PUT");
1179ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson        assertValidRequestMethod("TRACE");
1180ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson    }
1181ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson
1182ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson    private void assertValidRequestMethod(String requestMethod) throws Exception {
1183ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson        HttpURLConnection connection = (HttpURLConnection) server.getUrl("/").openConnection();
1184ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson        connection.setRequestMethod(requestMethod);
1185ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson        assertEquals(requestMethod, connection.getRequestMethod());
1186ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson    }
1187ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson
1188ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson    public void testSetInvalidRequestMethodLowercase() throws Exception {
1189ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson        server.play();
1190ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson        assertInvalidRequestMethod("get");
1191ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson    }
1192ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson
1193ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson    public void testSetInvalidRequestMethodConnect() throws Exception {
1194ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson        server.play();
1195ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson        assertInvalidRequestMethod("CONNECT");
1196ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson    }
1197ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson
1198ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson    private void assertInvalidRequestMethod(String requestMethod) throws Exception {
1199ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson        HttpURLConnection connection = (HttpURLConnection) server.getUrl("/").openConnection();
1200ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson        try {
1201ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson            connection.setRequestMethod(requestMethod);
1202ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson            fail();
1203ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson        } catch (ProtocolException expected) {
1204ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson        }
1205ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson    }
1206ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson
1207ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson    public void testCannotSetNegativeFixedLengthStreamingMode() throws Exception {
1208ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson        server.play();
1209ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson        HttpURLConnection connection = (HttpURLConnection) server.getUrl("/").openConnection();
1210ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson        try {
1211ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson            connection.setFixedLengthStreamingMode(-2);
1212ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson            fail();
1213ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson        } catch (IllegalArgumentException expected) {
1214ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson        }
1215ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson    }
1216ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson
1217ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson    public void testCanSetNegativeChunkedStreamingMode() throws Exception {
1218ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson        server.play();
1219ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson        HttpURLConnection connection = (HttpURLConnection) server.getUrl("/").openConnection();
1220ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson        connection.setChunkedStreamingMode(-2);
1221ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson    }
1222ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson
1223ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson    public void testCannotSetFixedLengthStreamingModeAfterConnect() throws Exception {
1224ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson        server.enqueue(new MockResponse().setBody("A"));
1225ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson        server.play();
1226ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson        HttpURLConnection connection = (HttpURLConnection) server.getUrl("/").openConnection();
1227ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson        assertEquals("A", readAscii(connection.getInputStream(), Integer.MAX_VALUE));
1228ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson        try {
1229ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson            connection.setFixedLengthStreamingMode(1);
1230ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson            fail();
1231ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson        } catch (IllegalStateException expected) {
1232ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson        }
1233ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson    }
1234ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson
1235ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson    public void testCannotSetChunkedStreamingModeAfterConnect() throws Exception {
1236ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson        server.enqueue(new MockResponse().setBody("A"));
1237ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson        server.play();
1238ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson        HttpURLConnection connection = (HttpURLConnection) server.getUrl("/").openConnection();
1239ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson        assertEquals("A", readAscii(connection.getInputStream(), Integer.MAX_VALUE));
1240ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson        try {
1241ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson            connection.setChunkedStreamingMode(1);
1242ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson            fail();
1243ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson        } catch (IllegalStateException expected) {
1244ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson        }
1245ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson    }
1246ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson
1247ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson    public void testCannotSetFixedLengthStreamingModeAfterChunkedStreamingMode() throws Exception {
1248ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson        server.play();
1249ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson        HttpURLConnection connection = (HttpURLConnection) server.getUrl("/").openConnection();
1250ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson        connection.setChunkedStreamingMode(1);
1251ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson        try {
1252ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson            connection.setFixedLengthStreamingMode(1);
1253ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson            fail();
1254ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson        } catch (IllegalStateException expected) {
1255ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson        }
1256ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson    }
1257ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson
1258ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson    public void testCannotSetChunkedStreamingModeAfterFixedLengthStreamingMode() throws Exception {
1259ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson        server.play();
1260ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson        HttpURLConnection connection = (HttpURLConnection) server.getUrl("/").openConnection();
1261ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson        connection.setFixedLengthStreamingMode(1);
1262ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson        try {
1263ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson            connection.setChunkedStreamingMode(1);
1264ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson            fail();
1265ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson        } catch (IllegalStateException expected) {
1266ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson        }
1267ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson    }
1268ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson
126935eef71e8ce721c4199c525890ecc1a263054596Jesse Wilson    public void testSecureFixedLengthStreaming() throws Exception {
127035eef71e8ce721c4199c525890ecc1a263054596Jesse Wilson        testSecureStreamingPost(StreamingMode.FIXED_LENGTH);
127135eef71e8ce721c4199c525890ecc1a263054596Jesse Wilson    }
127235eef71e8ce721c4199c525890ecc1a263054596Jesse Wilson
127335eef71e8ce721c4199c525890ecc1a263054596Jesse Wilson    public void testSecureChunkedStreaming() throws Exception {
127435eef71e8ce721c4199c525890ecc1a263054596Jesse Wilson        testSecureStreamingPost(StreamingMode.CHUNKED);
127535eef71e8ce721c4199c525890ecc1a263054596Jesse Wilson    }
127635eef71e8ce721c4199c525890ecc1a263054596Jesse Wilson
127735eef71e8ce721c4199c525890ecc1a263054596Jesse Wilson    /**
127835eef71e8ce721c4199c525890ecc1a263054596Jesse Wilson     * Users have reported problems using HTTPS with streaming request bodies.
127935eef71e8ce721c4199c525890ecc1a263054596Jesse Wilson     * http://code.google.com/p/android/issues/detail?id=12860
128035eef71e8ce721c4199c525890ecc1a263054596Jesse Wilson     */
128135eef71e8ce721c4199c525890ecc1a263054596Jesse Wilson    private void testSecureStreamingPost(StreamingMode streamingMode) throws Exception {
128235eef71e8ce721c4199c525890ecc1a263054596Jesse Wilson        TestSSLContext testSSLContext = TestSSLContext.create();
128335eef71e8ce721c4199c525890ecc1a263054596Jesse Wilson        server.useHttps(testSSLContext.serverContext.getSocketFactory(), false);
128435eef71e8ce721c4199c525890ecc1a263054596Jesse Wilson        server.enqueue(new MockResponse().setBody("Success!"));
128535eef71e8ce721c4199c525890ecc1a263054596Jesse Wilson        server.play();
128635eef71e8ce721c4199c525890ecc1a263054596Jesse Wilson
128735eef71e8ce721c4199c525890ecc1a263054596Jesse Wilson        HttpsURLConnection connection = (HttpsURLConnection) server.getUrl("/").openConnection();
128835eef71e8ce721c4199c525890ecc1a263054596Jesse Wilson        connection.setSSLSocketFactory(testSSLContext.clientContext.getSocketFactory());
128935eef71e8ce721c4199c525890ecc1a263054596Jesse Wilson        connection.setDoOutput(true);
129035eef71e8ce721c4199c525890ecc1a263054596Jesse Wilson        byte[] requestBody = { 'A', 'B', 'C', 'D' };
129135eef71e8ce721c4199c525890ecc1a263054596Jesse Wilson        if (streamingMode == StreamingMode.FIXED_LENGTH) {
129235eef71e8ce721c4199c525890ecc1a263054596Jesse Wilson            connection.setFixedLengthStreamingMode(requestBody.length);
129335eef71e8ce721c4199c525890ecc1a263054596Jesse Wilson        } else if (streamingMode == StreamingMode.CHUNKED) {
129435eef71e8ce721c4199c525890ecc1a263054596Jesse Wilson            connection.setChunkedStreamingMode(0);
129535eef71e8ce721c4199c525890ecc1a263054596Jesse Wilson        }
129635eef71e8ce721c4199c525890ecc1a263054596Jesse Wilson        OutputStream outputStream = connection.getOutputStream();
129735eef71e8ce721c4199c525890ecc1a263054596Jesse Wilson        outputStream.write(requestBody);
129835eef71e8ce721c4199c525890ecc1a263054596Jesse Wilson        outputStream.close();
129935eef71e8ce721c4199c525890ecc1a263054596Jesse Wilson        assertEquals("Success!", readAscii(connection.getInputStream(), Integer.MAX_VALUE));
130035eef71e8ce721c4199c525890ecc1a263054596Jesse Wilson
130135eef71e8ce721c4199c525890ecc1a263054596Jesse Wilson        RecordedRequest request = server.takeRequest();
130235eef71e8ce721c4199c525890ecc1a263054596Jesse Wilson        assertEquals("POST / HTTP/1.1", request.getRequestLine());
130335eef71e8ce721c4199c525890ecc1a263054596Jesse Wilson        if (streamingMode == StreamingMode.FIXED_LENGTH) {
130435eef71e8ce721c4199c525890ecc1a263054596Jesse Wilson            assertEquals(Collections.<Integer>emptyList(), request.getChunkSizes());
130535eef71e8ce721c4199c525890ecc1a263054596Jesse Wilson        } else if (streamingMode == StreamingMode.CHUNKED) {
130635eef71e8ce721c4199c525890ecc1a263054596Jesse Wilson            assertEquals(Arrays.asList(4), request.getChunkSizes());
130735eef71e8ce721c4199c525890ecc1a263054596Jesse Wilson        }
130835eef71e8ce721c4199c525890ecc1a263054596Jesse Wilson        assertEquals(Arrays.toString(requestBody), Arrays.toString(request.getBody()));
130935eef71e8ce721c4199c525890ecc1a263054596Jesse Wilson    }
131035eef71e8ce721c4199c525890ecc1a263054596Jesse Wilson
1311ffd579b668428272b78f5c6c64f9c89766f37c1aJesse Wilson    enum StreamingMode {
1312ffd579b668428272b78f5c6c64f9c89766f37c1aJesse Wilson        FIXED_LENGTH, CHUNKED
1313ffd579b668428272b78f5c6c64f9c89766f37c1aJesse Wilson    }
1314ffd579b668428272b78f5c6c64f9c89766f37c1aJesse Wilson
1315ffd579b668428272b78f5c6c64f9c89766f37c1aJesse Wilson    public void testAuthenticateWithPost() throws Exception {
1316ffd579b668428272b78f5c6c64f9c89766f37c1aJesse Wilson        MockResponse pleaseAuthenticate = new MockResponse()
1317ffd579b668428272b78f5c6c64f9c89766f37c1aJesse Wilson                .setResponseCode(401)
1318ffd579b668428272b78f5c6c64f9c89766f37c1aJesse Wilson                .addHeader("WWW-Authenticate: Basic realm=\"protected area\"")
1319ffd579b668428272b78f5c6c64f9c89766f37c1aJesse Wilson                .setBody("Please authenticate.");
1320ffd579b668428272b78f5c6c64f9c89766f37c1aJesse Wilson        // fail auth three times...
1321ffd579b668428272b78f5c6c64f9c89766f37c1aJesse Wilson        server.enqueue(pleaseAuthenticate);
1322ffd579b668428272b78f5c6c64f9c89766f37c1aJesse Wilson        server.enqueue(pleaseAuthenticate);
1323ffd579b668428272b78f5c6c64f9c89766f37c1aJesse Wilson        server.enqueue(pleaseAuthenticate);
1324ffd579b668428272b78f5c6c64f9c89766f37c1aJesse Wilson        // ...then succeed the fourth time
1325ffd579b668428272b78f5c6c64f9c89766f37c1aJesse Wilson        server.enqueue(new MockResponse().setBody("Successful auth!"));
1326ffd579b668428272b78f5c6c64f9c89766f37c1aJesse Wilson        server.play();
1327ffd579b668428272b78f5c6c64f9c89766f37c1aJesse Wilson
13285757cb35ad2e58d7accb7f5d3db6f2d5e72f097dJesse Wilson        Authenticator.setDefault(new SimpleAuthenticator());
1329ffd579b668428272b78f5c6c64f9c89766f37c1aJesse Wilson        HttpURLConnection connection = (HttpURLConnection) server.getUrl("/").openConnection();
1330ffd579b668428272b78f5c6c64f9c89766f37c1aJesse Wilson        connection.setDoOutput(true);
1331ffd579b668428272b78f5c6c64f9c89766f37c1aJesse Wilson        byte[] requestBody = { 'A', 'B', 'C', 'D' };
1332ffd579b668428272b78f5c6c64f9c89766f37c1aJesse Wilson        OutputStream outputStream = connection.getOutputStream();
1333ffd579b668428272b78f5c6c64f9c89766f37c1aJesse Wilson        outputStream.write(requestBody);
1334ffd579b668428272b78f5c6c64f9c89766f37c1aJesse Wilson        outputStream.close();
1335ffd579b668428272b78f5c6c64f9c89766f37c1aJesse Wilson        assertEquals("Successful auth!", readAscii(connection.getInputStream(), Integer.MAX_VALUE));
1336ffd579b668428272b78f5c6c64f9c89766f37c1aJesse Wilson
1337ffd579b668428272b78f5c6c64f9c89766f37c1aJesse Wilson        // no authorization header for the first request...
1338ffd579b668428272b78f5c6c64f9c89766f37c1aJesse Wilson        RecordedRequest request = server.takeRequest();
13395757cb35ad2e58d7accb7f5d3db6f2d5e72f097dJesse Wilson        assertContainsNoneMatching(request.getHeaders(), "Authorization: .*");
1340ffd579b668428272b78f5c6c64f9c89766f37c1aJesse Wilson
1341da289bcd0a9e207cc03c752f7c21c9004056e179Jesse Wilson        // ...but the three requests that follow include an authorization header
1342ffd579b668428272b78f5c6c64f9c89766f37c1aJesse Wilson        for (int i = 0; i < 3; i++) {
1343ffd579b668428272b78f5c6c64f9c89766f37c1aJesse Wilson            request = server.takeRequest();
1344ffd579b668428272b78f5c6c64f9c89766f37c1aJesse Wilson            assertEquals("POST / HTTP/1.1", request.getRequestLine());
13455757cb35ad2e58d7accb7f5d3db6f2d5e72f097dJesse Wilson            assertContains(request.getHeaders(), "Authorization: Basic "
13465757cb35ad2e58d7accb7f5d3db6f2d5e72f097dJesse Wilson                    + SimpleAuthenticator.BASE_64_CREDENTIALS);
1347ffd579b668428272b78f5c6c64f9c89766f37c1aJesse Wilson            assertEquals(Arrays.toString(requestBody), Arrays.toString(request.getBody()));
1348ffd579b668428272b78f5c6c64f9c89766f37c1aJesse Wilson        }
1349ffd579b668428272b78f5c6c64f9c89766f37c1aJesse Wilson    }
1350ffd579b668428272b78f5c6c64f9c89766f37c1aJesse Wilson
1351ffd579b668428272b78f5c6c64f9c89766f37c1aJesse Wilson    public void testAuthenticateWithGet() throws Exception {
1352ffd579b668428272b78f5c6c64f9c89766f37c1aJesse Wilson        MockResponse pleaseAuthenticate = new MockResponse()
1353ffd579b668428272b78f5c6c64f9c89766f37c1aJesse Wilson                .setResponseCode(401)
1354ffd579b668428272b78f5c6c64f9c89766f37c1aJesse Wilson                .addHeader("WWW-Authenticate: Basic realm=\"protected area\"")
1355ffd579b668428272b78f5c6c64f9c89766f37c1aJesse Wilson                .setBody("Please authenticate.");
1356ffd579b668428272b78f5c6c64f9c89766f37c1aJesse Wilson        // fail auth three times...
1357ffd579b668428272b78f5c6c64f9c89766f37c1aJesse Wilson        server.enqueue(pleaseAuthenticate);
1358ffd579b668428272b78f5c6c64f9c89766f37c1aJesse Wilson        server.enqueue(pleaseAuthenticate);
1359ffd579b668428272b78f5c6c64f9c89766f37c1aJesse Wilson        server.enqueue(pleaseAuthenticate);
1360ffd579b668428272b78f5c6c64f9c89766f37c1aJesse Wilson        // ...then succeed the fourth time
1361ffd579b668428272b78f5c6c64f9c89766f37c1aJesse Wilson        server.enqueue(new MockResponse().setBody("Successful auth!"));
1362ffd579b668428272b78f5c6c64f9c89766f37c1aJesse Wilson        server.play();
1363ffd579b668428272b78f5c6c64f9c89766f37c1aJesse Wilson
13645757cb35ad2e58d7accb7f5d3db6f2d5e72f097dJesse Wilson        SimpleAuthenticator authenticator = new SimpleAuthenticator();
13655757cb35ad2e58d7accb7f5d3db6f2d5e72f097dJesse Wilson        Authenticator.setDefault(authenticator);
1366ffd579b668428272b78f5c6c64f9c89766f37c1aJesse Wilson        HttpURLConnection connection = (HttpURLConnection) server.getUrl("/").openConnection();
1367ffd579b668428272b78f5c6c64f9c89766f37c1aJesse Wilson        assertEquals("Successful auth!", readAscii(connection.getInputStream(), Integer.MAX_VALUE));
13685757cb35ad2e58d7accb7f5d3db6f2d5e72f097dJesse Wilson        assertEquals(Authenticator.RequestorType.SERVER, authenticator.requestorType);
13695757cb35ad2e58d7accb7f5d3db6f2d5e72f097dJesse Wilson        assertEquals(server.getPort(), authenticator.requestingPort);
13705757cb35ad2e58d7accb7f5d3db6f2d5e72f097dJesse Wilson        assertEquals(InetAddress.getByName(server.getHostName()), authenticator.requestingSite);
13715757cb35ad2e58d7accb7f5d3db6f2d5e72f097dJesse Wilson        assertEquals("protected area", authenticator.requestingPrompt);
13725757cb35ad2e58d7accb7f5d3db6f2d5e72f097dJesse Wilson        assertEquals("http", authenticator.requestingProtocol);
13735757cb35ad2e58d7accb7f5d3db6f2d5e72f097dJesse Wilson        assertEquals("Basic", authenticator.requestingScheme);
1374ffd579b668428272b78f5c6c64f9c89766f37c1aJesse Wilson
1375ffd579b668428272b78f5c6c64f9c89766f37c1aJesse Wilson        // no authorization header for the first request...
1376ffd579b668428272b78f5c6c64f9c89766f37c1aJesse Wilson        RecordedRequest request = server.takeRequest();
13775757cb35ad2e58d7accb7f5d3db6f2d5e72f097dJesse Wilson        assertContainsNoneMatching(request.getHeaders(), "Authorization: .*");
1378ffd579b668428272b78f5c6c64f9c89766f37c1aJesse Wilson
1379ffd579b668428272b78f5c6c64f9c89766f37c1aJesse Wilson        // ...but the three requests that follow requests include an authorization header
1380ffd579b668428272b78f5c6c64f9c89766f37c1aJesse Wilson        for (int i = 0; i < 3; i++) {
1381ffd579b668428272b78f5c6c64f9c89766f37c1aJesse Wilson            request = server.takeRequest();
1382ffd579b668428272b78f5c6c64f9c89766f37c1aJesse Wilson            assertEquals("GET / HTTP/1.1", request.getRequestLine());
13835757cb35ad2e58d7accb7f5d3db6f2d5e72f097dJesse Wilson            assertContains(request.getHeaders(), "Authorization: Basic "
13845757cb35ad2e58d7accb7f5d3db6f2d5e72f097dJesse Wilson                    + SimpleAuthenticator.BASE_64_CREDENTIALS);
1385ffd579b668428272b78f5c6c64f9c89766f37c1aJesse Wilson        }
1386ffd579b668428272b78f5c6c64f9c89766f37c1aJesse Wilson    }
1387ffd579b668428272b78f5c6c64f9c89766f37c1aJesse Wilson
13885757cb35ad2e58d7accb7f5d3db6f2d5e72f097dJesse Wilson    // http://code.google.com/p/android/issues/detail?id=19081
13895757cb35ad2e58d7accb7f5d3db6f2d5e72f097dJesse Wilson    public void testAuthenticateWithCommaSeparatedAuthenticationMethods() throws Exception {
13905757cb35ad2e58d7accb7f5d3db6f2d5e72f097dJesse Wilson        server.enqueue(new MockResponse()
13915757cb35ad2e58d7accb7f5d3db6f2d5e72f097dJesse Wilson                .setResponseCode(401)
13925757cb35ad2e58d7accb7f5d3db6f2d5e72f097dJesse Wilson                .addHeader("WWW-Authenticate: Scheme1 realm=\"a\", Scheme2 realm=\"b\", "
13935757cb35ad2e58d7accb7f5d3db6f2d5e72f097dJesse Wilson                        + "Scheme3 realm=\"c\"")
13945757cb35ad2e58d7accb7f5d3db6f2d5e72f097dJesse Wilson                .setBody("Please authenticate."));
13955757cb35ad2e58d7accb7f5d3db6f2d5e72f097dJesse Wilson        server.enqueue(new MockResponse().setBody("Successful auth!"));
13965757cb35ad2e58d7accb7f5d3db6f2d5e72f097dJesse Wilson        server.play();
13975757cb35ad2e58d7accb7f5d3db6f2d5e72f097dJesse Wilson
13985757cb35ad2e58d7accb7f5d3db6f2d5e72f097dJesse Wilson        SimpleAuthenticator authenticator = new SimpleAuthenticator();
13995757cb35ad2e58d7accb7f5d3db6f2d5e72f097dJesse Wilson        authenticator.expectedPrompt = "b";
14005757cb35ad2e58d7accb7f5d3db6f2d5e72f097dJesse Wilson        Authenticator.setDefault(authenticator);
14015757cb35ad2e58d7accb7f5d3db6f2d5e72f097dJesse Wilson        HttpURLConnection connection = (HttpURLConnection) server.getUrl("/").openConnection();
14025757cb35ad2e58d7accb7f5d3db6f2d5e72f097dJesse Wilson        assertEquals("Successful auth!", readAscii(connection.getInputStream(), Integer.MAX_VALUE));
14035757cb35ad2e58d7accb7f5d3db6f2d5e72f097dJesse Wilson
14045757cb35ad2e58d7accb7f5d3db6f2d5e72f097dJesse Wilson        assertContainsNoneMatching(server.takeRequest().getHeaders(), "Authorization: .*");
14055757cb35ad2e58d7accb7f5d3db6f2d5e72f097dJesse Wilson        assertContains(server.takeRequest().getHeaders(),
14065757cb35ad2e58d7accb7f5d3db6f2d5e72f097dJesse Wilson                "Authorization: Scheme2 " + SimpleAuthenticator.BASE_64_CREDENTIALS);
14075757cb35ad2e58d7accb7f5d3db6f2d5e72f097dJesse Wilson        assertEquals("Scheme2", authenticator.requestingScheme);
14085757cb35ad2e58d7accb7f5d3db6f2d5e72f097dJesse Wilson    }
14095757cb35ad2e58d7accb7f5d3db6f2d5e72f097dJesse Wilson
14105757cb35ad2e58d7accb7f5d3db6f2d5e72f097dJesse Wilson    public void testAuthenticateWithMultipleAuthenticationHeaders() throws Exception {
14115757cb35ad2e58d7accb7f5d3db6f2d5e72f097dJesse Wilson        server.enqueue(new MockResponse()
14125757cb35ad2e58d7accb7f5d3db6f2d5e72f097dJesse Wilson                .setResponseCode(401)
14135757cb35ad2e58d7accb7f5d3db6f2d5e72f097dJesse Wilson                .addHeader("WWW-Authenticate: Scheme1 realm=\"a\"")
14145757cb35ad2e58d7accb7f5d3db6f2d5e72f097dJesse Wilson                .addHeader("WWW-Authenticate: Scheme2 realm=\"b\"")
14155757cb35ad2e58d7accb7f5d3db6f2d5e72f097dJesse Wilson                .addHeader("WWW-Authenticate: Scheme3 realm=\"c\"")
14165757cb35ad2e58d7accb7f5d3db6f2d5e72f097dJesse Wilson                .setBody("Please authenticate."));
14175757cb35ad2e58d7accb7f5d3db6f2d5e72f097dJesse Wilson        server.enqueue(new MockResponse().setBody("Successful auth!"));
14185757cb35ad2e58d7accb7f5d3db6f2d5e72f097dJesse Wilson        server.play();
14195757cb35ad2e58d7accb7f5d3db6f2d5e72f097dJesse Wilson
14205757cb35ad2e58d7accb7f5d3db6f2d5e72f097dJesse Wilson        SimpleAuthenticator authenticator = new SimpleAuthenticator();
14215757cb35ad2e58d7accb7f5d3db6f2d5e72f097dJesse Wilson        authenticator.expectedPrompt = "b";
14225757cb35ad2e58d7accb7f5d3db6f2d5e72f097dJesse Wilson        Authenticator.setDefault(authenticator);
14235757cb35ad2e58d7accb7f5d3db6f2d5e72f097dJesse Wilson        HttpURLConnection connection = (HttpURLConnection) server.getUrl("/").openConnection();
14245757cb35ad2e58d7accb7f5d3db6f2d5e72f097dJesse Wilson        assertEquals("Successful auth!", readAscii(connection.getInputStream(), Integer.MAX_VALUE));
14255757cb35ad2e58d7accb7f5d3db6f2d5e72f097dJesse Wilson
14265757cb35ad2e58d7accb7f5d3db6f2d5e72f097dJesse Wilson        assertContainsNoneMatching(server.takeRequest().getHeaders(), "Authorization: .*");
14275757cb35ad2e58d7accb7f5d3db6f2d5e72f097dJesse Wilson        assertContains(server.takeRequest().getHeaders(),
14285757cb35ad2e58d7accb7f5d3db6f2d5e72f097dJesse Wilson                "Authorization: Scheme2 " + SimpleAuthenticator.BASE_64_CREDENTIALS);
14295757cb35ad2e58d7accb7f5d3db6f2d5e72f097dJesse Wilson        assertEquals("Scheme2", authenticator.requestingScheme);
14305757cb35ad2e58d7accb7f5d3db6f2d5e72f097dJesse Wilson    }
14315757cb35ad2e58d7accb7f5d3db6f2d5e72f097dJesse Wilson
1432c0372d90016d241ac979faa6fa1731f30b6f2a03Jesse Wilson    public void testRedirectedWithChunkedEncoding() throws Exception {
1433c0372d90016d241ac979faa6fa1731f30b6f2a03Jesse Wilson        testRedirected(TransferKind.CHUNKED, true);
1434c0372d90016d241ac979faa6fa1731f30b6f2a03Jesse Wilson    }
1435c0372d90016d241ac979faa6fa1731f30b6f2a03Jesse Wilson
1436c0372d90016d241ac979faa6fa1731f30b6f2a03Jesse Wilson    public void testRedirectedWithContentLengthHeader() throws Exception {
1437c0372d90016d241ac979faa6fa1731f30b6f2a03Jesse Wilson        testRedirected(TransferKind.FIXED_LENGTH, true);
1438c0372d90016d241ac979faa6fa1731f30b6f2a03Jesse Wilson    }
1439c0372d90016d241ac979faa6fa1731f30b6f2a03Jesse Wilson
1440c0372d90016d241ac979faa6fa1731f30b6f2a03Jesse Wilson    public void testRedirectedWithNoLengthHeaders() throws Exception {
1441c0372d90016d241ac979faa6fa1731f30b6f2a03Jesse Wilson        testRedirected(TransferKind.END_OF_STREAM, false);
1442c0372d90016d241ac979faa6fa1731f30b6f2a03Jesse Wilson    }
1443c0372d90016d241ac979faa6fa1731f30b6f2a03Jesse Wilson
1444c0372d90016d241ac979faa6fa1731f30b6f2a03Jesse Wilson    private void testRedirected(TransferKind transferKind, boolean reuse) throws Exception {
1445c0372d90016d241ac979faa6fa1731f30b6f2a03Jesse Wilson        MockResponse response = new MockResponse()
1446c0372d90016d241ac979faa6fa1731f30b6f2a03Jesse Wilson                .setResponseCode(HttpURLConnection.HTTP_MOVED_TEMP)
1447c0372d90016d241ac979faa6fa1731f30b6f2a03Jesse Wilson                .addHeader("Location: /foo");
1448c0372d90016d241ac979faa6fa1731f30b6f2a03Jesse Wilson        transferKind.setBody(response, "This page has moved!", 10);
1449c0372d90016d241ac979faa6fa1731f30b6f2a03Jesse Wilson        server.enqueue(response);
1450c0372d90016d241ac979faa6fa1731f30b6f2a03Jesse Wilson        server.enqueue(new MockResponse().setBody("This is the new location!"));
1451c0372d90016d241ac979faa6fa1731f30b6f2a03Jesse Wilson        server.play();
1452c0372d90016d241ac979faa6fa1731f30b6f2a03Jesse Wilson
1453c0372d90016d241ac979faa6fa1731f30b6f2a03Jesse Wilson        URLConnection connection = server.getUrl("/").openConnection();
1454c0372d90016d241ac979faa6fa1731f30b6f2a03Jesse Wilson        assertEquals("This is the new location!",
1455c0372d90016d241ac979faa6fa1731f30b6f2a03Jesse Wilson                readAscii(connection.getInputStream(), Integer.MAX_VALUE));
1456c0372d90016d241ac979faa6fa1731f30b6f2a03Jesse Wilson
1457c0372d90016d241ac979faa6fa1731f30b6f2a03Jesse Wilson        RecordedRequest first = server.takeRequest();
1458c0372d90016d241ac979faa6fa1731f30b6f2a03Jesse Wilson        assertEquals("GET / HTTP/1.1", first.getRequestLine());
1459c0372d90016d241ac979faa6fa1731f30b6f2a03Jesse Wilson        RecordedRequest retry = server.takeRequest();
1460c0372d90016d241ac979faa6fa1731f30b6f2a03Jesse Wilson        assertEquals("GET /foo HTTP/1.1", retry.getRequestLine());
1461c0372d90016d241ac979faa6fa1731f30b6f2a03Jesse Wilson        if (reuse) {
1462c0372d90016d241ac979faa6fa1731f30b6f2a03Jesse Wilson            assertEquals("Expected connection reuse", 1, retry.getSequenceNumber());
1463c0372d90016d241ac979faa6fa1731f30b6f2a03Jesse Wilson        }
1464c0372d90016d241ac979faa6fa1731f30b6f2a03Jesse Wilson    }
1465c0372d90016d241ac979faa6fa1731f30b6f2a03Jesse Wilson
1466c0372d90016d241ac979faa6fa1731f30b6f2a03Jesse Wilson    public void testRedirectedOnHttps() throws IOException, InterruptedException {
1467c0372d90016d241ac979faa6fa1731f30b6f2a03Jesse Wilson        TestSSLContext testSSLContext = TestSSLContext.create();
1468059dbc04218144f985b20a228bbe98139d400d0cBrian Carlstrom        server.useHttps(testSSLContext.serverContext.getSocketFactory(), false);
1469c0372d90016d241ac979faa6fa1731f30b6f2a03Jesse Wilson        server.enqueue(new MockResponse()
1470c0372d90016d241ac979faa6fa1731f30b6f2a03Jesse Wilson                .setResponseCode(HttpURLConnection.HTTP_MOVED_TEMP)
1471c0372d90016d241ac979faa6fa1731f30b6f2a03Jesse Wilson                .addHeader("Location: /foo")
1472c0372d90016d241ac979faa6fa1731f30b6f2a03Jesse Wilson                .setBody("This page has moved!"));
1473c0372d90016d241ac979faa6fa1731f30b6f2a03Jesse Wilson        server.enqueue(new MockResponse().setBody("This is the new location!"));
1474c0372d90016d241ac979faa6fa1731f30b6f2a03Jesse Wilson        server.play();
1475c0372d90016d241ac979faa6fa1731f30b6f2a03Jesse Wilson
1476c0372d90016d241ac979faa6fa1731f30b6f2a03Jesse Wilson        HttpsURLConnection connection = (HttpsURLConnection) server.getUrl("/").openConnection();
1477059dbc04218144f985b20a228bbe98139d400d0cBrian Carlstrom        connection.setSSLSocketFactory(testSSLContext.clientContext.getSocketFactory());
1478c0372d90016d241ac979faa6fa1731f30b6f2a03Jesse Wilson        assertEquals("This is the new location!",
1479c0372d90016d241ac979faa6fa1731f30b6f2a03Jesse Wilson                readAscii(connection.getInputStream(), Integer.MAX_VALUE));
1480c0372d90016d241ac979faa6fa1731f30b6f2a03Jesse Wilson
1481c0372d90016d241ac979faa6fa1731f30b6f2a03Jesse Wilson        RecordedRequest first = server.takeRequest();
1482c0372d90016d241ac979faa6fa1731f30b6f2a03Jesse Wilson        assertEquals("GET / HTTP/1.1", first.getRequestLine());
1483c0372d90016d241ac979faa6fa1731f30b6f2a03Jesse Wilson        RecordedRequest retry = server.takeRequest();
1484c0372d90016d241ac979faa6fa1731f30b6f2a03Jesse Wilson        assertEquals("GET /foo HTTP/1.1", retry.getRequestLine());
1485c0372d90016d241ac979faa6fa1731f30b6f2a03Jesse Wilson        assertEquals("Expected connection reuse", 1, retry.getSequenceNumber());
1486c0372d90016d241ac979faa6fa1731f30b6f2a03Jesse Wilson    }
1487c0372d90016d241ac979faa6fa1731f30b6f2a03Jesse Wilson
1488c0372d90016d241ac979faa6fa1731f30b6f2a03Jesse Wilson    public void testNotRedirectedFromHttpsToHttp() throws IOException, InterruptedException {
1489c0372d90016d241ac979faa6fa1731f30b6f2a03Jesse Wilson        TestSSLContext testSSLContext = TestSSLContext.create();
1490059dbc04218144f985b20a228bbe98139d400d0cBrian Carlstrom        server.useHttps(testSSLContext.serverContext.getSocketFactory(), false);
1491c0372d90016d241ac979faa6fa1731f30b6f2a03Jesse Wilson        server.enqueue(new MockResponse()
1492c0372d90016d241ac979faa6fa1731f30b6f2a03Jesse Wilson                .setResponseCode(HttpURLConnection.HTTP_MOVED_TEMP)
1493c0372d90016d241ac979faa6fa1731f30b6f2a03Jesse Wilson                .addHeader("Location: http://anyhost/foo")
1494c0372d90016d241ac979faa6fa1731f30b6f2a03Jesse Wilson                .setBody("This page has moved!"));
1495c0372d90016d241ac979faa6fa1731f30b6f2a03Jesse Wilson        server.play();
1496c0372d90016d241ac979faa6fa1731f30b6f2a03Jesse Wilson
1497c0372d90016d241ac979faa6fa1731f30b6f2a03Jesse Wilson        HttpsURLConnection connection = (HttpsURLConnection) server.getUrl("/").openConnection();
1498059dbc04218144f985b20a228bbe98139d400d0cBrian Carlstrom        connection.setSSLSocketFactory(testSSLContext.clientContext.getSocketFactory());
1499c0372d90016d241ac979faa6fa1731f30b6f2a03Jesse Wilson        assertEquals("This page has moved!",
1500c0372d90016d241ac979faa6fa1731f30b6f2a03Jesse Wilson                readAscii(connection.getInputStream(), Integer.MAX_VALUE));
1501c0372d90016d241ac979faa6fa1731f30b6f2a03Jesse Wilson    }
1502c0372d90016d241ac979faa6fa1731f30b6f2a03Jesse Wilson
1503c0372d90016d241ac979faa6fa1731f30b6f2a03Jesse Wilson    public void testNotRedirectedFromHttpToHttps() throws IOException, InterruptedException {
1504c0372d90016d241ac979faa6fa1731f30b6f2a03Jesse Wilson        server.enqueue(new MockResponse()
1505c0372d90016d241ac979faa6fa1731f30b6f2a03Jesse Wilson                .setResponseCode(HttpURLConnection.HTTP_MOVED_TEMP)
1506c0372d90016d241ac979faa6fa1731f30b6f2a03Jesse Wilson                .addHeader("Location: https://anyhost/foo")
1507c0372d90016d241ac979faa6fa1731f30b6f2a03Jesse Wilson                .setBody("This page has moved!"));
1508c0372d90016d241ac979faa6fa1731f30b6f2a03Jesse Wilson        server.play();
1509c0372d90016d241ac979faa6fa1731f30b6f2a03Jesse Wilson
1510c0372d90016d241ac979faa6fa1731f30b6f2a03Jesse Wilson        HttpURLConnection connection = (HttpURLConnection) server.getUrl("/").openConnection();
1511c0372d90016d241ac979faa6fa1731f30b6f2a03Jesse Wilson        assertEquals("This page has moved!",
1512c0372d90016d241ac979faa6fa1731f30b6f2a03Jesse Wilson                readAscii(connection.getInputStream(), Integer.MAX_VALUE));
1513c0372d90016d241ac979faa6fa1731f30b6f2a03Jesse Wilson    }
1514c0372d90016d241ac979faa6fa1731f30b6f2a03Jesse Wilson
1515c0372d90016d241ac979faa6fa1731f30b6f2a03Jesse Wilson    public void testRedirectToAnotherOriginServer() throws Exception {
1516c0372d90016d241ac979faa6fa1731f30b6f2a03Jesse Wilson        MockWebServer server2 = new MockWebServer();
1517c0372d90016d241ac979faa6fa1731f30b6f2a03Jesse Wilson        server2.enqueue(new MockResponse().setBody("This is the 2nd server!"));
1518c0372d90016d241ac979faa6fa1731f30b6f2a03Jesse Wilson        server2.play();
1519c0372d90016d241ac979faa6fa1731f30b6f2a03Jesse Wilson
1520c0372d90016d241ac979faa6fa1731f30b6f2a03Jesse Wilson        server.enqueue(new MockResponse()
1521c0372d90016d241ac979faa6fa1731f30b6f2a03Jesse Wilson                .setResponseCode(HttpURLConnection.HTTP_MOVED_TEMP)
1522c0372d90016d241ac979faa6fa1731f30b6f2a03Jesse Wilson                .addHeader("Location: " + server2.getUrl("/").toString())
1523c0372d90016d241ac979faa6fa1731f30b6f2a03Jesse Wilson                .setBody("This page has moved!"));
1524c0372d90016d241ac979faa6fa1731f30b6f2a03Jesse Wilson        server.enqueue(new MockResponse().setBody("This is the first server again!"));
1525c0372d90016d241ac979faa6fa1731f30b6f2a03Jesse Wilson        server.play();
1526c0372d90016d241ac979faa6fa1731f30b6f2a03Jesse Wilson
1527c0372d90016d241ac979faa6fa1731f30b6f2a03Jesse Wilson        URLConnection connection = server.getUrl("/").openConnection();
1528c0372d90016d241ac979faa6fa1731f30b6f2a03Jesse Wilson        assertEquals("This is the 2nd server!",
1529c0372d90016d241ac979faa6fa1731f30b6f2a03Jesse Wilson                readAscii(connection.getInputStream(), Integer.MAX_VALUE));
1530c0372d90016d241ac979faa6fa1731f30b6f2a03Jesse Wilson        assertEquals(server2.getUrl("/"), connection.getURL());
1531c0372d90016d241ac979faa6fa1731f30b6f2a03Jesse Wilson
1532c0372d90016d241ac979faa6fa1731f30b6f2a03Jesse Wilson        // make sure the first server was careful to recycle the connection
1533c0372d90016d241ac979faa6fa1731f30b6f2a03Jesse Wilson        assertEquals("This is the first server again!",
1534c0372d90016d241ac979faa6fa1731f30b6f2a03Jesse Wilson                readAscii(server.getUrl("/").openStream(), Integer.MAX_VALUE));
1535c0372d90016d241ac979faa6fa1731f30b6f2a03Jesse Wilson
1536c0372d90016d241ac979faa6fa1731f30b6f2a03Jesse Wilson        RecordedRequest first = server.takeRequest();
15370c2fd828abec671333b8b88281825fd27a783723Jesse Wilson        assertContains(first.getHeaders(), "Host: " + hostName + ":" + server.getPort());
1538c0372d90016d241ac979faa6fa1731f30b6f2a03Jesse Wilson        RecordedRequest second = server2.takeRequest();
15390c2fd828abec671333b8b88281825fd27a783723Jesse Wilson        assertContains(second.getHeaders(), "Host: " + hostName + ":" + server2.getPort());
1540c0372d90016d241ac979faa6fa1731f30b6f2a03Jesse Wilson        RecordedRequest third = server.takeRequest();
1541c0372d90016d241ac979faa6fa1731f30b6f2a03Jesse Wilson        assertEquals("Expected connection reuse", 1, third.getSequenceNumber());
1542c0372d90016d241ac979faa6fa1731f30b6f2a03Jesse Wilson
1543c0372d90016d241ac979faa6fa1731f30b6f2a03Jesse Wilson        server2.shutdown();
1544c0372d90016d241ac979faa6fa1731f30b6f2a03Jesse Wilson    }
1545c0372d90016d241ac979faa6fa1731f30b6f2a03Jesse Wilson
1546d742d7fc7f0593eb8c6e4ac9dd4c0f6a80374e46Jesse Wilson    public void testResponse300MultipleChoiceWithPost() throws Exception {
1547d742d7fc7f0593eb8c6e4ac9dd4c0f6a80374e46Jesse Wilson        // Chrome doesn't follow the redirect, but Firefox and the RI both do
1548d742d7fc7f0593eb8c6e4ac9dd4c0f6a80374e46Jesse Wilson        testResponseRedirectedWithPost(HttpURLConnection.HTTP_MULT_CHOICE);
1549d742d7fc7f0593eb8c6e4ac9dd4c0f6a80374e46Jesse Wilson    }
1550d742d7fc7f0593eb8c6e4ac9dd4c0f6a80374e46Jesse Wilson
1551d742d7fc7f0593eb8c6e4ac9dd4c0f6a80374e46Jesse Wilson    public void testResponse301MovedPermanentlyWithPost() throws Exception {
1552d742d7fc7f0593eb8c6e4ac9dd4c0f6a80374e46Jesse Wilson        testResponseRedirectedWithPost(HttpURLConnection.HTTP_MOVED_PERM);
1553d742d7fc7f0593eb8c6e4ac9dd4c0f6a80374e46Jesse Wilson    }
1554d742d7fc7f0593eb8c6e4ac9dd4c0f6a80374e46Jesse Wilson
1555d742d7fc7f0593eb8c6e4ac9dd4c0f6a80374e46Jesse Wilson    public void testResponse302MovedTemporarilyWithPost() throws Exception {
1556d742d7fc7f0593eb8c6e4ac9dd4c0f6a80374e46Jesse Wilson        testResponseRedirectedWithPost(HttpURLConnection.HTTP_MOVED_TEMP);
1557d742d7fc7f0593eb8c6e4ac9dd4c0f6a80374e46Jesse Wilson    }
1558d742d7fc7f0593eb8c6e4ac9dd4c0f6a80374e46Jesse Wilson
1559d742d7fc7f0593eb8c6e4ac9dd4c0f6a80374e46Jesse Wilson    public void testResponse303SeeOtherWithPost() throws Exception {
1560d742d7fc7f0593eb8c6e4ac9dd4c0f6a80374e46Jesse Wilson        testResponseRedirectedWithPost(HttpURLConnection.HTTP_SEE_OTHER);
1561d742d7fc7f0593eb8c6e4ac9dd4c0f6a80374e46Jesse Wilson    }
1562d742d7fc7f0593eb8c6e4ac9dd4c0f6a80374e46Jesse Wilson
1563d742d7fc7f0593eb8c6e4ac9dd4c0f6a80374e46Jesse Wilson    private void testResponseRedirectedWithPost(int redirectCode) throws Exception {
1564d742d7fc7f0593eb8c6e4ac9dd4c0f6a80374e46Jesse Wilson        server.enqueue(new MockResponse()
1565d742d7fc7f0593eb8c6e4ac9dd4c0f6a80374e46Jesse Wilson                .setResponseCode(redirectCode)
1566d742d7fc7f0593eb8c6e4ac9dd4c0f6a80374e46Jesse Wilson                .addHeader("Location: /page2")
1567d742d7fc7f0593eb8c6e4ac9dd4c0f6a80374e46Jesse Wilson                .setBody("This page has moved!"));
1568d742d7fc7f0593eb8c6e4ac9dd4c0f6a80374e46Jesse Wilson        server.enqueue(new MockResponse().setBody("Page 2"));
1569d742d7fc7f0593eb8c6e4ac9dd4c0f6a80374e46Jesse Wilson        server.play();
1570d742d7fc7f0593eb8c6e4ac9dd4c0f6a80374e46Jesse Wilson
1571d742d7fc7f0593eb8c6e4ac9dd4c0f6a80374e46Jesse Wilson        HttpURLConnection connection = (HttpURLConnection) server.getUrl("/page1").openConnection();
1572d742d7fc7f0593eb8c6e4ac9dd4c0f6a80374e46Jesse Wilson        connection.setDoOutput(true);
1573d742d7fc7f0593eb8c6e4ac9dd4c0f6a80374e46Jesse Wilson        byte[] requestBody = { 'A', 'B', 'C', 'D' };
1574d742d7fc7f0593eb8c6e4ac9dd4c0f6a80374e46Jesse Wilson        OutputStream outputStream = connection.getOutputStream();
1575d742d7fc7f0593eb8c6e4ac9dd4c0f6a80374e46Jesse Wilson        outputStream.write(requestBody);
1576d742d7fc7f0593eb8c6e4ac9dd4c0f6a80374e46Jesse Wilson        outputStream.close();
1577d742d7fc7f0593eb8c6e4ac9dd4c0f6a80374e46Jesse Wilson        assertEquals("Page 2", readAscii(connection.getInputStream(), Integer.MAX_VALUE));
1578d742d7fc7f0593eb8c6e4ac9dd4c0f6a80374e46Jesse Wilson        assertTrue(connection.getDoOutput());
1579d742d7fc7f0593eb8c6e4ac9dd4c0f6a80374e46Jesse Wilson
1580d742d7fc7f0593eb8c6e4ac9dd4c0f6a80374e46Jesse Wilson        RecordedRequest page1 = server.takeRequest();
1581d742d7fc7f0593eb8c6e4ac9dd4c0f6a80374e46Jesse Wilson        assertEquals("POST /page1 HTTP/1.1", page1.getRequestLine());
1582d742d7fc7f0593eb8c6e4ac9dd4c0f6a80374e46Jesse Wilson        assertEquals(Arrays.toString(requestBody), Arrays.toString(page1.getBody()));
1583d742d7fc7f0593eb8c6e4ac9dd4c0f6a80374e46Jesse Wilson
1584d742d7fc7f0593eb8c6e4ac9dd4c0f6a80374e46Jesse Wilson        RecordedRequest page2 = server.takeRequest();
1585d742d7fc7f0593eb8c6e4ac9dd4c0f6a80374e46Jesse Wilson        assertEquals("GET /page2 HTTP/1.1", page2.getRequestLine());
1586d742d7fc7f0593eb8c6e4ac9dd4c0f6a80374e46Jesse Wilson    }
1587d742d7fc7f0593eb8c6e4ac9dd4c0f6a80374e46Jesse Wilson
1588d742d7fc7f0593eb8c6e4ac9dd4c0f6a80374e46Jesse Wilson    public void testResponse305UseProxy() throws Exception {
1589d742d7fc7f0593eb8c6e4ac9dd4c0f6a80374e46Jesse Wilson        server.play();
1590d742d7fc7f0593eb8c6e4ac9dd4c0f6a80374e46Jesse Wilson        server.enqueue(new MockResponse()
1591d742d7fc7f0593eb8c6e4ac9dd4c0f6a80374e46Jesse Wilson                .setResponseCode(HttpURLConnection.HTTP_USE_PROXY)
1592d742d7fc7f0593eb8c6e4ac9dd4c0f6a80374e46Jesse Wilson                .addHeader("Location: " + server.getUrl("/"))
1593d742d7fc7f0593eb8c6e4ac9dd4c0f6a80374e46Jesse Wilson                .setBody("This page has moved!"));
1594d742d7fc7f0593eb8c6e4ac9dd4c0f6a80374e46Jesse Wilson        server.enqueue(new MockResponse().setBody("Proxy Response"));
1595d742d7fc7f0593eb8c6e4ac9dd4c0f6a80374e46Jesse Wilson
1596d742d7fc7f0593eb8c6e4ac9dd4c0f6a80374e46Jesse Wilson        HttpURLConnection connection = (HttpURLConnection) server.getUrl("/foo").openConnection();
1597d742d7fc7f0593eb8c6e4ac9dd4c0f6a80374e46Jesse Wilson        // Fails on the RI, which gets "Proxy Response"
1598d742d7fc7f0593eb8c6e4ac9dd4c0f6a80374e46Jesse Wilson        assertEquals("This page has moved!",
1599d742d7fc7f0593eb8c6e4ac9dd4c0f6a80374e46Jesse Wilson                readAscii(connection.getInputStream(), Integer.MAX_VALUE));
1600d742d7fc7f0593eb8c6e4ac9dd4c0f6a80374e46Jesse Wilson
1601d742d7fc7f0593eb8c6e4ac9dd4c0f6a80374e46Jesse Wilson        RecordedRequest page1 = server.takeRequest();
1602d742d7fc7f0593eb8c6e4ac9dd4c0f6a80374e46Jesse Wilson        assertEquals("GET /foo HTTP/1.1", page1.getRequestLine());
1603d742d7fc7f0593eb8c6e4ac9dd4c0f6a80374e46Jesse Wilson        assertEquals(1, server.getRequestCount());
1604d742d7fc7f0593eb8c6e4ac9dd4c0f6a80374e46Jesse Wilson    }
1605d742d7fc7f0593eb8c6e4ac9dd4c0f6a80374e46Jesse Wilson
1606c0372d90016d241ac979faa6fa1731f30b6f2a03Jesse Wilson    public void testHttpsWithCustomTrustManager() throws Exception {
1607c0372d90016d241ac979faa6fa1731f30b6f2a03Jesse Wilson        RecordingHostnameVerifier hostnameVerifier = new RecordingHostnameVerifier();
1608c0372d90016d241ac979faa6fa1731f30b6f2a03Jesse Wilson        RecordingTrustManager trustManager = new RecordingTrustManager();
1609c0372d90016d241ac979faa6fa1731f30b6f2a03Jesse Wilson        SSLContext sc = SSLContext.getInstance("TLS");
1610c0372d90016d241ac979faa6fa1731f30b6f2a03Jesse Wilson        sc.init(null, new TrustManager[] { trustManager }, new java.security.SecureRandom());
1611c0372d90016d241ac979faa6fa1731f30b6f2a03Jesse Wilson
1612c0372d90016d241ac979faa6fa1731f30b6f2a03Jesse Wilson        HostnameVerifier defaultHostnameVerifier = HttpsURLConnection.getDefaultHostnameVerifier();
1613c0372d90016d241ac979faa6fa1731f30b6f2a03Jesse Wilson        HttpsURLConnection.setDefaultHostnameVerifier(hostnameVerifier);
1614c0372d90016d241ac979faa6fa1731f30b6f2a03Jesse Wilson        SSLSocketFactory defaultSSLSocketFactory = HttpsURLConnection.getDefaultSSLSocketFactory();
1615c0372d90016d241ac979faa6fa1731f30b6f2a03Jesse Wilson        HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
1616c0372d90016d241ac979faa6fa1731f30b6f2a03Jesse Wilson        try {
1617c0372d90016d241ac979faa6fa1731f30b6f2a03Jesse Wilson            TestSSLContext testSSLContext = TestSSLContext.create();
1618059dbc04218144f985b20a228bbe98139d400d0cBrian Carlstrom            server.useHttps(testSSLContext.serverContext.getSocketFactory(), false);
1619c0372d90016d241ac979faa6fa1731f30b6f2a03Jesse Wilson            server.enqueue(new MockResponse().setBody("ABC"));
1620c0372d90016d241ac979faa6fa1731f30b6f2a03Jesse Wilson            server.enqueue(new MockResponse().setBody("DEF"));
1621c0372d90016d241ac979faa6fa1731f30b6f2a03Jesse Wilson            server.enqueue(new MockResponse().setBody("GHI"));
1622c0372d90016d241ac979faa6fa1731f30b6f2a03Jesse Wilson            server.play();
1623c0372d90016d241ac979faa6fa1731f30b6f2a03Jesse Wilson
1624c0372d90016d241ac979faa6fa1731f30b6f2a03Jesse Wilson            URL url = server.getUrl("/");
1625c0372d90016d241ac979faa6fa1731f30b6f2a03Jesse Wilson            assertEquals("ABC", readAscii(url.openStream(), Integer.MAX_VALUE));
1626c0372d90016d241ac979faa6fa1731f30b6f2a03Jesse Wilson            assertEquals("DEF", readAscii(url.openStream(), Integer.MAX_VALUE));
1627c0372d90016d241ac979faa6fa1731f30b6f2a03Jesse Wilson            assertEquals("GHI", readAscii(url.openStream(), Integer.MAX_VALUE));
1628c0372d90016d241ac979faa6fa1731f30b6f2a03Jesse Wilson
16290c2fd828abec671333b8b88281825fd27a783723Jesse Wilson            assertEquals(Arrays.asList("verify " + hostName), hostnameVerifier.calls);
16304559b1d37edcb5d7f1da086cf2e3290388d74f46Brian Carlstrom            assertEquals(Arrays.asList("checkServerTrusted ["
16310c2fd828abec671333b8b88281825fd27a783723Jesse Wilson                    + "CN=" + hostName + " 1, "
1632b7f4d6c3968c372767b2510f38a3d506067aced6Jesse Wilson                    + "CN=Test Intermediate Certificate Authority 1, "
1633b7f4d6c3968c372767b2510f38a3d506067aced6Jesse Wilson                    + "CN=Test Root Certificate Authority 1"
1634b7f4d6c3968c372767b2510f38a3d506067aced6Jesse Wilson                    + "] RSA"),
1635c0372d90016d241ac979faa6fa1731f30b6f2a03Jesse Wilson                    trustManager.calls);
1636c0372d90016d241ac979faa6fa1731f30b6f2a03Jesse Wilson        } finally {
1637c0372d90016d241ac979faa6fa1731f30b6f2a03Jesse Wilson            HttpsURLConnection.setDefaultHostnameVerifier(defaultHostnameVerifier);
1638c0372d90016d241ac979faa6fa1731f30b6f2a03Jesse Wilson            HttpsURLConnection.setDefaultSSLSocketFactory(defaultSSLSocketFactory);
1639c0372d90016d241ac979faa6fa1731f30b6f2a03Jesse Wilson        }
1640c0372d90016d241ac979faa6fa1731f30b6f2a03Jesse Wilson    }
1641c0372d90016d241ac979faa6fa1731f30b6f2a03Jesse Wilson
16422d9fa917aae6a6da38e9d1eda05841ffdf8855bbJesse Wilson    /**
16432d9fa917aae6a6da38e9d1eda05841ffdf8855bbJesse Wilson     * Test that the timeout period is honored. The timeout may be doubled!
16442d9fa917aae6a6da38e9d1eda05841ffdf8855bbJesse Wilson     * HttpURLConnection will wait the full timeout for each of the server's IP
16452d9fa917aae6a6da38e9d1eda05841ffdf8855bbJesse Wilson     * addresses. This is typically one IPv4 address and one IPv6 address.
16462d9fa917aae6a6da38e9d1eda05841ffdf8855bbJesse Wilson     */
1647eafede536f2059bb6c869e7a5f07fd7ad9758e28Jesse Wilson    public void testConnectTimeouts() throws IOException {
16480e1afa1091f74a6228c01d8c7a8eebf001efdc57Elliott Hughes        StuckServer ss = new StuckServer(false);
16495fc5dde4c719c1dfdac46b67d5d2e4884d07721eElliott Hughes        int serverPort = ss.getLocalPort();
1650f02c695ed03e708623d9365dec26d533356ef2d0Brian Carlstrom        URLConnection urlConnection = new URL("http://localhost:" + serverPort).openConnection();
1651b7f4d6c3968c372767b2510f38a3d506067aced6Jesse Wilson        int timeout = 1000;
1652b7f4d6c3968c372767b2510f38a3d506067aced6Jesse Wilson        urlConnection.setConnectTimeout(timeout);
1653b7f4d6c3968c372767b2510f38a3d506067aced6Jesse Wilson        long start = System.currentTimeMillis();
1654eafede536f2059bb6c869e7a5f07fd7ad9758e28Jesse Wilson        try {
1655eafede536f2059bb6c869e7a5f07fd7ad9758e28Jesse Wilson            urlConnection.getInputStream();
1656eafede536f2059bb6c869e7a5f07fd7ad9758e28Jesse Wilson            fail();
1657eafede536f2059bb6c869e7a5f07fd7ad9758e28Jesse Wilson        } catch (SocketTimeoutException expected) {
16582d9fa917aae6a6da38e9d1eda05841ffdf8855bbJesse Wilson            long elapsed = System.currentTimeMillis() - start;
16592d9fa917aae6a6da38e9d1eda05841ffdf8855bbJesse Wilson            int attempts = InetAddress.getAllByName("localhost").length; // one per IP address
16602d9fa917aae6a6da38e9d1eda05841ffdf8855bbJesse Wilson            assertTrue("timeout=" +timeout + ", elapsed=" + elapsed + ", attempts=" + attempts,
16612d9fa917aae6a6da38e9d1eda05841ffdf8855bbJesse Wilson                    Math.abs((attempts * timeout) - elapsed) < 500);
16625fc5dde4c719c1dfdac46b67d5d2e4884d07721eElliott Hughes        } finally {
16635fc5dde4c719c1dfdac46b67d5d2e4884d07721eElliott Hughes            ss.close();
1664f02c695ed03e708623d9365dec26d533356ef2d0Brian Carlstrom        }
1665eafede536f2059bb6c869e7a5f07fd7ad9758e28Jesse Wilson    }
1666eafede536f2059bb6c869e7a5f07fd7ad9758e28Jesse Wilson
1667eafede536f2059bb6c869e7a5f07fd7ad9758e28Jesse Wilson    public void testReadTimeouts() throws IOException {
1668eafede536f2059bb6c869e7a5f07fd7ad9758e28Jesse Wilson        /*
1669eafede536f2059bb6c869e7a5f07fd7ad9758e28Jesse Wilson         * This relies on the fact that MockWebServer doesn't close the
1670eafede536f2059bb6c869e7a5f07fd7ad9758e28Jesse Wilson         * connection after a response has been sent. This causes the client to
1671eafede536f2059bb6c869e7a5f07fd7ad9758e28Jesse Wilson         * try to read more bytes than are sent, which results in a timeout.
1672eafede536f2059bb6c869e7a5f07fd7ad9758e28Jesse Wilson         */
1673eafede536f2059bb6c869e7a5f07fd7ad9758e28Jesse Wilson        MockResponse timeout = new MockResponse()
1674eafede536f2059bb6c869e7a5f07fd7ad9758e28Jesse Wilson                .setBody("ABC")
1675eafede536f2059bb6c869e7a5f07fd7ad9758e28Jesse Wilson                .clearHeaders()
1676eafede536f2059bb6c869e7a5f07fd7ad9758e28Jesse Wilson                .addHeader("Content-Length: 4");
1677eafede536f2059bb6c869e7a5f07fd7ad9758e28Jesse Wilson        server.enqueue(timeout);
1678b7f4d6c3968c372767b2510f38a3d506067aced6Jesse Wilson        server.enqueue(new MockResponse().setBody("unused")); // to keep the server alive
1679eafede536f2059bb6c869e7a5f07fd7ad9758e28Jesse Wilson        server.play();
1680eafede536f2059bb6c869e7a5f07fd7ad9758e28Jesse Wilson
1681eafede536f2059bb6c869e7a5f07fd7ad9758e28Jesse Wilson        URLConnection urlConnection = server.getUrl("/").openConnection();
1682eafede536f2059bb6c869e7a5f07fd7ad9758e28Jesse Wilson        urlConnection.setReadTimeout(1000);
1683eafede536f2059bb6c869e7a5f07fd7ad9758e28Jesse Wilson        InputStream in = urlConnection.getInputStream();
1684eafede536f2059bb6c869e7a5f07fd7ad9758e28Jesse Wilson        assertEquals('A', in.read());
1685eafede536f2059bb6c869e7a5f07fd7ad9758e28Jesse Wilson        assertEquals('B', in.read());
1686eafede536f2059bb6c869e7a5f07fd7ad9758e28Jesse Wilson        assertEquals('C', in.read());
1687eafede536f2059bb6c869e7a5f07fd7ad9758e28Jesse Wilson        try {
1688eafede536f2059bb6c869e7a5f07fd7ad9758e28Jesse Wilson            in.read(); // if Content-Length was accurate, this would return -1 immediately
1689eafede536f2059bb6c869e7a5f07fd7ad9758e28Jesse Wilson            fail();
1690eafede536f2059bb6c869e7a5f07fd7ad9758e28Jesse Wilson        } catch (SocketTimeoutException expected) {
1691eafede536f2059bb6c869e7a5f07fd7ad9758e28Jesse Wilson        }
1692eafede536f2059bb6c869e7a5f07fd7ad9758e28Jesse Wilson    }
1693eafede536f2059bb6c869e7a5f07fd7ad9758e28Jesse Wilson
1694125f068f0a6cd739beac97821c9421cf8317cc87Jesse Wilson    public void testSetChunkedEncodingAsRequestProperty() throws IOException, InterruptedException {
1695125f068f0a6cd739beac97821c9421cf8317cc87Jesse Wilson        server.enqueue(new MockResponse());
1696125f068f0a6cd739beac97821c9421cf8317cc87Jesse Wilson        server.play();
1697125f068f0a6cd739beac97821c9421cf8317cc87Jesse Wilson
1698125f068f0a6cd739beac97821c9421cf8317cc87Jesse Wilson        HttpURLConnection urlConnection = (HttpURLConnection) server.getUrl("/").openConnection();
1699125f068f0a6cd739beac97821c9421cf8317cc87Jesse Wilson        urlConnection.setRequestProperty("Transfer-encoding", "chunked");
1700125f068f0a6cd739beac97821c9421cf8317cc87Jesse Wilson        urlConnection.setDoOutput(true);
1701125f068f0a6cd739beac97821c9421cf8317cc87Jesse Wilson        urlConnection.getOutputStream().write("ABC".getBytes("UTF-8"));
1702125f068f0a6cd739beac97821c9421cf8317cc87Jesse Wilson        assertEquals(200, urlConnection.getResponseCode());
1703125f068f0a6cd739beac97821c9421cf8317cc87Jesse Wilson
1704125f068f0a6cd739beac97821c9421cf8317cc87Jesse Wilson        RecordedRequest request = server.takeRequest();
1705125f068f0a6cd739beac97821c9421cf8317cc87Jesse Wilson        assertEquals("ABC", new String(request.getBody(), "UTF-8"));
1706125f068f0a6cd739beac97821c9421cf8317cc87Jesse Wilson    }
1707125f068f0a6cd739beac97821c9421cf8317cc87Jesse Wilson
1708f418bf447fd007cd2ec2d45b4b0399a11904e9b4Jesse Wilson    public void testConnectionCloseInRequest() throws IOException, InterruptedException {
1709f418bf447fd007cd2ec2d45b4b0399a11904e9b4Jesse Wilson        server.enqueue(new MockResponse()); // server doesn't honor the connection: close header!
1710f418bf447fd007cd2ec2d45b4b0399a11904e9b4Jesse Wilson        server.enqueue(new MockResponse());
1711f418bf447fd007cd2ec2d45b4b0399a11904e9b4Jesse Wilson        server.play();
1712f418bf447fd007cd2ec2d45b4b0399a11904e9b4Jesse Wilson
1713f418bf447fd007cd2ec2d45b4b0399a11904e9b4Jesse Wilson        HttpURLConnection a = (HttpURLConnection) server.getUrl("/").openConnection();
1714f418bf447fd007cd2ec2d45b4b0399a11904e9b4Jesse Wilson        a.setRequestProperty("Connection", "close");
1715f418bf447fd007cd2ec2d45b4b0399a11904e9b4Jesse Wilson        assertEquals(200, a.getResponseCode());
1716f418bf447fd007cd2ec2d45b4b0399a11904e9b4Jesse Wilson
1717f418bf447fd007cd2ec2d45b4b0399a11904e9b4Jesse Wilson        HttpURLConnection b = (HttpURLConnection) server.getUrl("/").openConnection();
1718f418bf447fd007cd2ec2d45b4b0399a11904e9b4Jesse Wilson        assertEquals(200, b.getResponseCode());
1719f418bf447fd007cd2ec2d45b4b0399a11904e9b4Jesse Wilson
1720f418bf447fd007cd2ec2d45b4b0399a11904e9b4Jesse Wilson        assertEquals(0, server.takeRequest().getSequenceNumber());
1721f418bf447fd007cd2ec2d45b4b0399a11904e9b4Jesse Wilson        assertEquals("When connection: close is used, each request should get its own connection",
1722f418bf447fd007cd2ec2d45b4b0399a11904e9b4Jesse Wilson                0, server.takeRequest().getSequenceNumber());
1723f418bf447fd007cd2ec2d45b4b0399a11904e9b4Jesse Wilson    }
1724f418bf447fd007cd2ec2d45b4b0399a11904e9b4Jesse Wilson
1725f418bf447fd007cd2ec2d45b4b0399a11904e9b4Jesse Wilson    public void testConnectionCloseInResponse() throws IOException, InterruptedException {
1726f418bf447fd007cd2ec2d45b4b0399a11904e9b4Jesse Wilson        server.enqueue(new MockResponse().addHeader("Connection: close"));
1727f418bf447fd007cd2ec2d45b4b0399a11904e9b4Jesse Wilson        server.enqueue(new MockResponse());
1728f418bf447fd007cd2ec2d45b4b0399a11904e9b4Jesse Wilson        server.play();
1729f418bf447fd007cd2ec2d45b4b0399a11904e9b4Jesse Wilson
1730f418bf447fd007cd2ec2d45b4b0399a11904e9b4Jesse Wilson        HttpURLConnection a = (HttpURLConnection) server.getUrl("/").openConnection();
1731f418bf447fd007cd2ec2d45b4b0399a11904e9b4Jesse Wilson        assertEquals(200, a.getResponseCode());
1732f418bf447fd007cd2ec2d45b4b0399a11904e9b4Jesse Wilson
1733f418bf447fd007cd2ec2d45b4b0399a11904e9b4Jesse Wilson        HttpURLConnection b = (HttpURLConnection) server.getUrl("/").openConnection();
1734f418bf447fd007cd2ec2d45b4b0399a11904e9b4Jesse Wilson        assertEquals(200, b.getResponseCode());
1735f418bf447fd007cd2ec2d45b4b0399a11904e9b4Jesse Wilson
1736f418bf447fd007cd2ec2d45b4b0399a11904e9b4Jesse Wilson        assertEquals(0, server.takeRequest().getSequenceNumber());
1737f418bf447fd007cd2ec2d45b4b0399a11904e9b4Jesse Wilson        assertEquals("When connection: close is used, each request should get its own connection",
1738f418bf447fd007cd2ec2d45b4b0399a11904e9b4Jesse Wilson                0, server.takeRequest().getSequenceNumber());
1739f418bf447fd007cd2ec2d45b4b0399a11904e9b4Jesse Wilson    }
1740f418bf447fd007cd2ec2d45b4b0399a11904e9b4Jesse Wilson
1741f418bf447fd007cd2ec2d45b4b0399a11904e9b4Jesse Wilson    public void testConnectionCloseWithRedirect() throws IOException, InterruptedException {
1742f418bf447fd007cd2ec2d45b4b0399a11904e9b4Jesse Wilson        MockResponse response = new MockResponse()
1743f418bf447fd007cd2ec2d45b4b0399a11904e9b4Jesse Wilson                .setResponseCode(HttpURLConnection.HTTP_MOVED_TEMP)
1744f418bf447fd007cd2ec2d45b4b0399a11904e9b4Jesse Wilson                .addHeader("Location: /foo")
1745f418bf447fd007cd2ec2d45b4b0399a11904e9b4Jesse Wilson                .addHeader("Connection: close");
1746f418bf447fd007cd2ec2d45b4b0399a11904e9b4Jesse Wilson        server.enqueue(response);
1747f418bf447fd007cd2ec2d45b4b0399a11904e9b4Jesse Wilson        server.enqueue(new MockResponse().setBody("This is the new location!"));
1748f418bf447fd007cd2ec2d45b4b0399a11904e9b4Jesse Wilson        server.play();
1749f418bf447fd007cd2ec2d45b4b0399a11904e9b4Jesse Wilson
1750f418bf447fd007cd2ec2d45b4b0399a11904e9b4Jesse Wilson        URLConnection connection = server.getUrl("/").openConnection();
1751f418bf447fd007cd2ec2d45b4b0399a11904e9b4Jesse Wilson        assertEquals("This is the new location!",
1752f418bf447fd007cd2ec2d45b4b0399a11904e9b4Jesse Wilson                readAscii(connection.getInputStream(), Integer.MAX_VALUE));
1753f418bf447fd007cd2ec2d45b4b0399a11904e9b4Jesse Wilson
1754f418bf447fd007cd2ec2d45b4b0399a11904e9b4Jesse Wilson        assertEquals(0, server.takeRequest().getSequenceNumber());
1755f418bf447fd007cd2ec2d45b4b0399a11904e9b4Jesse Wilson        assertEquals("When connection: close is used, each request should get its own connection",
1756f418bf447fd007cd2ec2d45b4b0399a11904e9b4Jesse Wilson                0, server.takeRequest().getSequenceNumber());
1757f418bf447fd007cd2ec2d45b4b0399a11904e9b4Jesse Wilson    }
1758f418bf447fd007cd2ec2d45b4b0399a11904e9b4Jesse Wilson
175965d890eb22aeba9b009ee642ffd4fff48a6f98aeJesse Wilson    public void testResponseCodeDisagreesWithHeaders() throws IOException, InterruptedException {
176065d890eb22aeba9b009ee642ffd4fff48a6f98aeJesse Wilson        server.enqueue(new MockResponse()
176165d890eb22aeba9b009ee642ffd4fff48a6f98aeJesse Wilson                .setResponseCode(HttpURLConnection.HTTP_NO_CONTENT)
176265d890eb22aeba9b009ee642ffd4fff48a6f98aeJesse Wilson                .setBody("This body is not allowed!"));
176365d890eb22aeba9b009ee642ffd4fff48a6f98aeJesse Wilson        server.play();
176465d890eb22aeba9b009ee642ffd4fff48a6f98aeJesse Wilson
176565d890eb22aeba9b009ee642ffd4fff48a6f98aeJesse Wilson        URLConnection connection = server.getUrl("/").openConnection();
176665d890eb22aeba9b009ee642ffd4fff48a6f98aeJesse Wilson        assertEquals("This body is not allowed!",
176765d890eb22aeba9b009ee642ffd4fff48a6f98aeJesse Wilson                readAscii(connection.getInputStream(), Integer.MAX_VALUE));
176865d890eb22aeba9b009ee642ffd4fff48a6f98aeJesse Wilson    }
176965d890eb22aeba9b009ee642ffd4fff48a6f98aeJesse Wilson
1770ef66494dce45a0b7ec22ec3fb20c60096517a4e3Jesse Wilson    public void testSingleByteReadIsSigned() throws IOException {
1771ef66494dce45a0b7ec22ec3fb20c60096517a4e3Jesse Wilson        server.enqueue(new MockResponse().setBody(new byte[] { -2, -1 }));
1772ef66494dce45a0b7ec22ec3fb20c60096517a4e3Jesse Wilson        server.play();
1773ef66494dce45a0b7ec22ec3fb20c60096517a4e3Jesse Wilson
1774ef66494dce45a0b7ec22ec3fb20c60096517a4e3Jesse Wilson        URLConnection connection = server.getUrl("/").openConnection();
1775ef66494dce45a0b7ec22ec3fb20c60096517a4e3Jesse Wilson        InputStream in = connection.getInputStream();
1776ef66494dce45a0b7ec22ec3fb20c60096517a4e3Jesse Wilson        assertEquals(254, in.read());
1777ef66494dce45a0b7ec22ec3fb20c60096517a4e3Jesse Wilson        assertEquals(255, in.read());
1778ef66494dce45a0b7ec22ec3fb20c60096517a4e3Jesse Wilson        assertEquals(-1, in.read());
1779ef66494dce45a0b7ec22ec3fb20c60096517a4e3Jesse Wilson    }
1780ef66494dce45a0b7ec22ec3fb20c60096517a4e3Jesse Wilson
1781f29ad8a60254345d1943d1b3836482395a7c916fJesse Wilson    public void testFlushAfterStreamTransmittedWithChunkedEncoding() throws IOException {
1782f29ad8a60254345d1943d1b3836482395a7c916fJesse Wilson        testFlushAfterStreamTransmitted(TransferKind.CHUNKED);
1783f29ad8a60254345d1943d1b3836482395a7c916fJesse Wilson    }
1784f29ad8a60254345d1943d1b3836482395a7c916fJesse Wilson
1785f29ad8a60254345d1943d1b3836482395a7c916fJesse Wilson    public void testFlushAfterStreamTransmittedWithFixedLength() throws IOException {
1786f29ad8a60254345d1943d1b3836482395a7c916fJesse Wilson        testFlushAfterStreamTransmitted(TransferKind.FIXED_LENGTH);
1787f29ad8a60254345d1943d1b3836482395a7c916fJesse Wilson    }
1788f29ad8a60254345d1943d1b3836482395a7c916fJesse Wilson
1789f29ad8a60254345d1943d1b3836482395a7c916fJesse Wilson    public void testFlushAfterStreamTransmittedWithNoLengthHeaders() throws IOException {
1790f29ad8a60254345d1943d1b3836482395a7c916fJesse Wilson        testFlushAfterStreamTransmitted(TransferKind.END_OF_STREAM);
1791f29ad8a60254345d1943d1b3836482395a7c916fJesse Wilson    }
1792f29ad8a60254345d1943d1b3836482395a7c916fJesse Wilson
1793f29ad8a60254345d1943d1b3836482395a7c916fJesse Wilson    /**
1794f29ad8a60254345d1943d1b3836482395a7c916fJesse Wilson     * We explicitly permit apps to close the upload stream even after it has
1795f29ad8a60254345d1943d1b3836482395a7c916fJesse Wilson     * been transmitted.  We also permit flush so that buffered streams can
1796f29ad8a60254345d1943d1b3836482395a7c916fJesse Wilson     * do a no-op flush when they are closed. http://b/3038470
1797f29ad8a60254345d1943d1b3836482395a7c916fJesse Wilson     */
1798f29ad8a60254345d1943d1b3836482395a7c916fJesse Wilson    private void testFlushAfterStreamTransmitted(TransferKind transferKind) throws IOException {
1799f29ad8a60254345d1943d1b3836482395a7c916fJesse Wilson        server.enqueue(new MockResponse().setBody("abc"));
1800f29ad8a60254345d1943d1b3836482395a7c916fJesse Wilson        server.play();
1801f29ad8a60254345d1943d1b3836482395a7c916fJesse Wilson
1802f29ad8a60254345d1943d1b3836482395a7c916fJesse Wilson        HttpURLConnection connection = (HttpURLConnection) server.getUrl("/").openConnection();
1803f29ad8a60254345d1943d1b3836482395a7c916fJesse Wilson        connection.setDoOutput(true);
1804f29ad8a60254345d1943d1b3836482395a7c916fJesse Wilson        byte[] upload = "def".getBytes("UTF-8");
1805f29ad8a60254345d1943d1b3836482395a7c916fJesse Wilson
1806f29ad8a60254345d1943d1b3836482395a7c916fJesse Wilson        if (transferKind == TransferKind.CHUNKED) {
1807f29ad8a60254345d1943d1b3836482395a7c916fJesse Wilson            connection.setChunkedStreamingMode(0);
1808f29ad8a60254345d1943d1b3836482395a7c916fJesse Wilson        } else if (transferKind == TransferKind.FIXED_LENGTH) {
1809f29ad8a60254345d1943d1b3836482395a7c916fJesse Wilson            connection.setFixedLengthStreamingMode(upload.length);
1810f29ad8a60254345d1943d1b3836482395a7c916fJesse Wilson        }
1811f29ad8a60254345d1943d1b3836482395a7c916fJesse Wilson
1812f29ad8a60254345d1943d1b3836482395a7c916fJesse Wilson        OutputStream out = connection.getOutputStream();
1813f29ad8a60254345d1943d1b3836482395a7c916fJesse Wilson        out.write(upload);
1814f29ad8a60254345d1943d1b3836482395a7c916fJesse Wilson        assertEquals("abc", readAscii(connection.getInputStream(), Integer.MAX_VALUE));
1815f29ad8a60254345d1943d1b3836482395a7c916fJesse Wilson
1816f29ad8a60254345d1943d1b3836482395a7c916fJesse Wilson        out.flush(); // dubious but permitted
1817f29ad8a60254345d1943d1b3836482395a7c916fJesse Wilson        try {
1818f29ad8a60254345d1943d1b3836482395a7c916fJesse Wilson            out.write("ghi".getBytes("UTF-8"));
1819f29ad8a60254345d1943d1b3836482395a7c916fJesse Wilson            fail();
1820f29ad8a60254345d1943d1b3836482395a7c916fJesse Wilson        } catch (IOException expected) {
1821f29ad8a60254345d1943d1b3836482395a7c916fJesse Wilson        }
1822f29ad8a60254345d1943d1b3836482395a7c916fJesse Wilson    }
1823f29ad8a60254345d1943d1b3836482395a7c916fJesse Wilson
1824c6dae581716b9362a5c7f166c80a7f2b46ed1124Jesse Wilson    public void testGetHeadersThrows() throws IOException {
1825e942f46f10bb9384a1b186b3d7b74f9704c57090Jesse Wilson        server.enqueue(new MockResponse().setSocketPolicy(DISCONNECT_AT_START));
1826c6dae581716b9362a5c7f166c80a7f2b46ed1124Jesse Wilson        server.play();
1827c6dae581716b9362a5c7f166c80a7f2b46ed1124Jesse Wilson
1828c6dae581716b9362a5c7f166c80a7f2b46ed1124Jesse Wilson        HttpURLConnection connection = (HttpURLConnection) server.getUrl("/").openConnection();
1829c6dae581716b9362a5c7f166c80a7f2b46ed1124Jesse Wilson        try {
1830c6dae581716b9362a5c7f166c80a7f2b46ed1124Jesse Wilson            connection.getInputStream();
1831c6dae581716b9362a5c7f166c80a7f2b46ed1124Jesse Wilson            fail();
1832c6dae581716b9362a5c7f166c80a7f2b46ed1124Jesse Wilson        } catch (IOException expected) {
1833c6dae581716b9362a5c7f166c80a7f2b46ed1124Jesse Wilson        }
1834c6dae581716b9362a5c7f166c80a7f2b46ed1124Jesse Wilson
1835c6dae581716b9362a5c7f166c80a7f2b46ed1124Jesse Wilson        try {
1836c6dae581716b9362a5c7f166c80a7f2b46ed1124Jesse Wilson            connection.getInputStream();
1837c6dae581716b9362a5c7f166c80a7f2b46ed1124Jesse Wilson            fail();
1838f29ad8a60254345d1943d1b3836482395a7c916fJesse Wilson        } catch (IOException expected) {
1839f29ad8a60254345d1943d1b3836482395a7c916fJesse Wilson        }
1840f29ad8a60254345d1943d1b3836482395a7c916fJesse Wilson    }
1841f29ad8a60254345d1943d1b3836482395a7c916fJesse Wilson
1842b7f4d6c3968c372767b2510f38a3d506067aced6Jesse Wilson    public void testGetKeepAlive() throws Exception {
1843b7f4d6c3968c372767b2510f38a3d506067aced6Jesse Wilson        MockWebServer server = new MockWebServer();
1844b7f4d6c3968c372767b2510f38a3d506067aced6Jesse Wilson        server.enqueue(new MockResponse().setBody("ABC"));
1845b7f4d6c3968c372767b2510f38a3d506067aced6Jesse Wilson        server.play();
1846b7f4d6c3968c372767b2510f38a3d506067aced6Jesse Wilson
1847b7f4d6c3968c372767b2510f38a3d506067aced6Jesse Wilson        // The request should work once and then fail
1848b7f4d6c3968c372767b2510f38a3d506067aced6Jesse Wilson        URLConnection connection = server.getUrl("").openConnection();
1849b7f4d6c3968c372767b2510f38a3d506067aced6Jesse Wilson        InputStream input = connection.getInputStream();
1850b7f4d6c3968c372767b2510f38a3d506067aced6Jesse Wilson        assertEquals("ABC", readAscii(input, Integer.MAX_VALUE));
1851b7f4d6c3968c372767b2510f38a3d506067aced6Jesse Wilson        input.close();
1852b7f4d6c3968c372767b2510f38a3d506067aced6Jesse Wilson        try {
1853b7f4d6c3968c372767b2510f38a3d506067aced6Jesse Wilson            server.getUrl("").openConnection().getInputStream();
1854b7f4d6c3968c372767b2510f38a3d506067aced6Jesse Wilson            fail();
1855b7f4d6c3968c372767b2510f38a3d506067aced6Jesse Wilson        } catch (ConnectException expected) {
1856b7f4d6c3968c372767b2510f38a3d506067aced6Jesse Wilson        }
1857b7f4d6c3968c372767b2510f38a3d506067aced6Jesse Wilson    }
1858b7f4d6c3968c372767b2510f38a3d506067aced6Jesse Wilson
1859b7f4d6c3968c372767b2510f38a3d506067aced6Jesse Wilson    /**
1860d1b5e5da828434388e486a388710d21e4306dae0Jesse Wilson     * This test goes through the exhaustive set of interesting ASCII characters
1861d1b5e5da828434388e486a388710d21e4306dae0Jesse Wilson     * because most of those characters are interesting in some way according to
1862d1b5e5da828434388e486a388710d21e4306dae0Jesse Wilson     * RFC 2396 and RFC 2732. http://b/1158780
1863b7f4d6c3968c372767b2510f38a3d506067aced6Jesse Wilson     */
1864d1b5e5da828434388e486a388710d21e4306dae0Jesse Wilson    public void testLenientUrlToUri() throws Exception {
1865d1b5e5da828434388e486a388710d21e4306dae0Jesse Wilson        // alphanum
1866d1b5e5da828434388e486a388710d21e4306dae0Jesse Wilson        testUrlToUriMapping("abzABZ09", "abzABZ09", "abzABZ09", "abzABZ09", "abzABZ09");
1867d1b5e5da828434388e486a388710d21e4306dae0Jesse Wilson
1868d1b5e5da828434388e486a388710d21e4306dae0Jesse Wilson        // control characters
1869d1b5e5da828434388e486a388710d21e4306dae0Jesse Wilson        testUrlToUriMapping("\u0001", "%01", "%01", "%01", "%01");
1870d1b5e5da828434388e486a388710d21e4306dae0Jesse Wilson        testUrlToUriMapping("\u001f", "%1F", "%1F", "%1F", "%1F");
1871d1b5e5da828434388e486a388710d21e4306dae0Jesse Wilson
1872d1b5e5da828434388e486a388710d21e4306dae0Jesse Wilson        // ascii characters
1873d1b5e5da828434388e486a388710d21e4306dae0Jesse Wilson        testUrlToUriMapping("%20", "%20", "%20", "%20", "%20");
1874d1b5e5da828434388e486a388710d21e4306dae0Jesse Wilson        testUrlToUriMapping("%20", "%20", "%20", "%20", "%20");
1875d1b5e5da828434388e486a388710d21e4306dae0Jesse Wilson        testUrlToUriMapping(" ", "%20", "%20", "%20", "%20");
1876d1b5e5da828434388e486a388710d21e4306dae0Jesse Wilson        testUrlToUriMapping("!", "!", "!", "!", "!");
1877d1b5e5da828434388e486a388710d21e4306dae0Jesse Wilson        testUrlToUriMapping("\"", "%22", "%22", "%22", "%22");
1878d1b5e5da828434388e486a388710d21e4306dae0Jesse Wilson        testUrlToUriMapping("#", null, null, null, "%23");
1879d1b5e5da828434388e486a388710d21e4306dae0Jesse Wilson        testUrlToUriMapping("$", "$", "$", "$", "$");
1880d1b5e5da828434388e486a388710d21e4306dae0Jesse Wilson        testUrlToUriMapping("&", "&", "&", "&", "&");
1881d1b5e5da828434388e486a388710d21e4306dae0Jesse Wilson        testUrlToUriMapping("'", "'", "'", "'", "'");
1882d1b5e5da828434388e486a388710d21e4306dae0Jesse Wilson        testUrlToUriMapping("(", "(", "(", "(", "(");
1883d1b5e5da828434388e486a388710d21e4306dae0Jesse Wilson        testUrlToUriMapping(")", ")", ")", ")", ")");
1884d1b5e5da828434388e486a388710d21e4306dae0Jesse Wilson        testUrlToUriMapping("*", "*", "*", "*", "*");
1885d1b5e5da828434388e486a388710d21e4306dae0Jesse Wilson        testUrlToUriMapping("+", "+", "+", "+", "+");
1886d1b5e5da828434388e486a388710d21e4306dae0Jesse Wilson        testUrlToUriMapping(",", ",", ",", ",", ",");
1887d1b5e5da828434388e486a388710d21e4306dae0Jesse Wilson        testUrlToUriMapping("-", "-", "-", "-", "-");
1888d1b5e5da828434388e486a388710d21e4306dae0Jesse Wilson        testUrlToUriMapping(".", ".", ".", ".", ".");
1889d1b5e5da828434388e486a388710d21e4306dae0Jesse Wilson        testUrlToUriMapping("/", null, "/", "/", "/");
1890d1b5e5da828434388e486a388710d21e4306dae0Jesse Wilson        testUrlToUriMapping(":", null, ":", ":", ":");
1891d1b5e5da828434388e486a388710d21e4306dae0Jesse Wilson        testUrlToUriMapping(";", ";", ";", ";", ";");
1892d1b5e5da828434388e486a388710d21e4306dae0Jesse Wilson        testUrlToUriMapping("<", "%3C", "%3C", "%3C", "%3C");
1893d1b5e5da828434388e486a388710d21e4306dae0Jesse Wilson        testUrlToUriMapping("=", "=", "=", "=", "=");
1894d1b5e5da828434388e486a388710d21e4306dae0Jesse Wilson        testUrlToUriMapping(">", "%3E", "%3E", "%3E", "%3E");
1895d1b5e5da828434388e486a388710d21e4306dae0Jesse Wilson        testUrlToUriMapping("?", null, null, "?", "?");
1896d1b5e5da828434388e486a388710d21e4306dae0Jesse Wilson        testUrlToUriMapping("@", "@", "@", "@", "@");
1897d1b5e5da828434388e486a388710d21e4306dae0Jesse Wilson        testUrlToUriMapping("[", null, "%5B", null, "%5B");
1898d1b5e5da828434388e486a388710d21e4306dae0Jesse Wilson        testUrlToUriMapping("\\", "%5C", "%5C", "%5C", "%5C");
1899d1b5e5da828434388e486a388710d21e4306dae0Jesse Wilson        testUrlToUriMapping("]", null, "%5D", null, "%5D");
1900d1b5e5da828434388e486a388710d21e4306dae0Jesse Wilson        testUrlToUriMapping("^", "%5E", "%5E", "%5E", "%5E");
1901d1b5e5da828434388e486a388710d21e4306dae0Jesse Wilson        testUrlToUriMapping("_", "_", "_", "_", "_");
1902d1b5e5da828434388e486a388710d21e4306dae0Jesse Wilson        testUrlToUriMapping("`", "%60", "%60", "%60", "%60");
1903d1b5e5da828434388e486a388710d21e4306dae0Jesse Wilson        testUrlToUriMapping("{", "%7B", "%7B", "%7B", "%7B");
1904d1b5e5da828434388e486a388710d21e4306dae0Jesse Wilson        testUrlToUriMapping("|", "%7C", "%7C", "%7C", "%7C");
1905d1b5e5da828434388e486a388710d21e4306dae0Jesse Wilson        testUrlToUriMapping("}", "%7D", "%7D", "%7D", "%7D");
1906d1b5e5da828434388e486a388710d21e4306dae0Jesse Wilson        testUrlToUriMapping("~", "~", "~", "~", "~");
1907d1b5e5da828434388e486a388710d21e4306dae0Jesse Wilson        testUrlToUriMapping("~", "~", "~", "~", "~");
1908d1b5e5da828434388e486a388710d21e4306dae0Jesse Wilson        testUrlToUriMapping("\u007f", "%7F", "%7F", "%7F", "%7F");
1909d1b5e5da828434388e486a388710d21e4306dae0Jesse Wilson
1910d1b5e5da828434388e486a388710d21e4306dae0Jesse Wilson        // beyond ascii
1911d1b5e5da828434388e486a388710d21e4306dae0Jesse Wilson        testUrlToUriMapping("\u0080", "%C2%80", "%C2%80", "%C2%80", "%C2%80");
1912d1b5e5da828434388e486a388710d21e4306dae0Jesse Wilson        testUrlToUriMapping("\u20ac", "\u20ac", "\u20ac", "\u20ac", "\u20ac");
191332559028b14b9b321b10eede050afd554a376569Jesse Wilson        testUrlToUriMapping("\ud842\udf9f",
191432559028b14b9b321b10eede050afd554a376569Jesse Wilson                "\ud842\udf9f", "\ud842\udf9f", "\ud842\udf9f", "\ud842\udf9f");
1915d1b5e5da828434388e486a388710d21e4306dae0Jesse Wilson    }
1916d1b5e5da828434388e486a388710d21e4306dae0Jesse Wilson
1917d1b5e5da828434388e486a388710d21e4306dae0Jesse Wilson    public void testLenientUrlToUriNul() throws Exception {
1918d1b5e5da828434388e486a388710d21e4306dae0Jesse Wilson        testUrlToUriMapping("\u0000", "%00", "%00", "%00", "%00"); // RI fails this
1919d1b5e5da828434388e486a388710d21e4306dae0Jesse Wilson    }
1920d1b5e5da828434388e486a388710d21e4306dae0Jesse Wilson
1921d1b5e5da828434388e486a388710d21e4306dae0Jesse Wilson    private void testUrlToUriMapping(String string, String asAuthority, String asFile,
1922d1b5e5da828434388e486a388710d21e4306dae0Jesse Wilson            String asQuery, String asFragment) throws Exception {
1923d1b5e5da828434388e486a388710d21e4306dae0Jesse Wilson        if (asAuthority != null) {
1924d1b5e5da828434388e486a388710d21e4306dae0Jesse Wilson            assertEquals("http://host" + asAuthority + ".tld/",
1925d1b5e5da828434388e486a388710d21e4306dae0Jesse Wilson                    backdoorUrlToUri(new URL("http://host" + string + ".tld/")).toString());
1926d1b5e5da828434388e486a388710d21e4306dae0Jesse Wilson        }
1927d1b5e5da828434388e486a388710d21e4306dae0Jesse Wilson        if (asFile != null) {
1928d1b5e5da828434388e486a388710d21e4306dae0Jesse Wilson            assertEquals("http://host.tld/file" + asFile + "/",
1929d1b5e5da828434388e486a388710d21e4306dae0Jesse Wilson                    backdoorUrlToUri(new URL("http://host.tld/file" + string + "/")).toString());
1930d1b5e5da828434388e486a388710d21e4306dae0Jesse Wilson        }
1931d1b5e5da828434388e486a388710d21e4306dae0Jesse Wilson        if (asQuery != null) {
1932d1b5e5da828434388e486a388710d21e4306dae0Jesse Wilson            assertEquals("http://host.tld/file?q" + asQuery + "=x",
1933d1b5e5da828434388e486a388710d21e4306dae0Jesse Wilson                    backdoorUrlToUri(new URL("http://host.tld/file?q" + string + "=x")).toString());
1934d1b5e5da828434388e486a388710d21e4306dae0Jesse Wilson        }
1935d1b5e5da828434388e486a388710d21e4306dae0Jesse Wilson        assertEquals("http://host.tld/file#" + asFragment + "-x",
1936d1b5e5da828434388e486a388710d21e4306dae0Jesse Wilson                backdoorUrlToUri(new URL("http://host.tld/file#" + asFragment + "-x")).toString());
1937d1b5e5da828434388e486a388710d21e4306dae0Jesse Wilson    }
1938b7f4d6c3968c372767b2510f38a3d506067aced6Jesse Wilson
1939d1b5e5da828434388e486a388710d21e4306dae0Jesse Wilson    /**
1940d1b5e5da828434388e486a388710d21e4306dae0Jesse Wilson     * Exercises HttpURLConnection to convert URL to a URI. Unlike URL#toURI,
1941d1b5e5da828434388e486a388710d21e4306dae0Jesse Wilson     * HttpURLConnection recovers from URLs with unescaped but unsupported URI
1942d1b5e5da828434388e486a388710d21e4306dae0Jesse Wilson     * characters like '{' and '|' by escaping these characters.
1943d1b5e5da828434388e486a388710d21e4306dae0Jesse Wilson     */
1944d1b5e5da828434388e486a388710d21e4306dae0Jesse Wilson    private URI backdoorUrlToUri(URL url) throws Exception {
1945d1b5e5da828434388e486a388710d21e4306dae0Jesse Wilson        final AtomicReference<URI> uriReference = new AtomicReference<URI>();
1946d1b5e5da828434388e486a388710d21e4306dae0Jesse Wilson
1947d1b5e5da828434388e486a388710d21e4306dae0Jesse Wilson        ResponseCache.setDefault(new ResponseCache() {
1948d1b5e5da828434388e486a388710d21e4306dae0Jesse Wilson            @Override public CacheRequest put(URI uri, URLConnection connection) throws IOException {
1949d1b5e5da828434388e486a388710d21e4306dae0Jesse Wilson                return null;
1950d1b5e5da828434388e486a388710d21e4306dae0Jesse Wilson            }
1951d1b5e5da828434388e486a388710d21e4306dae0Jesse Wilson            @Override public CacheResponse get(URI uri, String requestMethod,
1952d1b5e5da828434388e486a388710d21e4306dae0Jesse Wilson                    Map<String, List<String>> requestHeaders) throws IOException {
1953d1b5e5da828434388e486a388710d21e4306dae0Jesse Wilson                uriReference.set(uri);
1954d1b5e5da828434388e486a388710d21e4306dae0Jesse Wilson                throw new UnsupportedOperationException();
1955d1b5e5da828434388e486a388710d21e4306dae0Jesse Wilson            }
1956d1b5e5da828434388e486a388710d21e4306dae0Jesse Wilson        });
1957d1b5e5da828434388e486a388710d21e4306dae0Jesse Wilson
1958d1b5e5da828434388e486a388710d21e4306dae0Jesse Wilson        try {
1959d1b5e5da828434388e486a388710d21e4306dae0Jesse Wilson            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
1960d1b5e5da828434388e486a388710d21e4306dae0Jesse Wilson            connection.getResponseCode();
1961d1b5e5da828434388e486a388710d21e4306dae0Jesse Wilson        } catch (Exception expected) {
1962d1b5e5da828434388e486a388710d21e4306dae0Jesse Wilson        }
1963d1b5e5da828434388e486a388710d21e4306dae0Jesse Wilson
1964d1b5e5da828434388e486a388710d21e4306dae0Jesse Wilson        return uriReference.get();
1965b7f4d6c3968c372767b2510f38a3d506067aced6Jesse Wilson    }
1966b7f4d6c3968c372767b2510f38a3d506067aced6Jesse Wilson
1967afd9b157f467b7c4f2f0b5592dca72f18d844602Jesse Wilson    /**
1968afd9b157f467b7c4f2f0b5592dca72f18d844602Jesse Wilson     * Don't explode if the cache returns a null body. http://b/3373699
1969afd9b157f467b7c4f2f0b5592dca72f18d844602Jesse Wilson     */
1970afd9b157f467b7c4f2f0b5592dca72f18d844602Jesse Wilson    public void testResponseCacheReturnsNullOutputStream() throws Exception {
1971afd9b157f467b7c4f2f0b5592dca72f18d844602Jesse Wilson        final AtomicBoolean aborted = new AtomicBoolean();
1972afd9b157f467b7c4f2f0b5592dca72f18d844602Jesse Wilson        ResponseCache.setDefault(new ResponseCache() {
1973afd9b157f467b7c4f2f0b5592dca72f18d844602Jesse Wilson            @Override public CacheResponse get(URI uri, String requestMethod,
1974afd9b157f467b7c4f2f0b5592dca72f18d844602Jesse Wilson                    Map<String, List<String>> requestHeaders) throws IOException {
1975afd9b157f467b7c4f2f0b5592dca72f18d844602Jesse Wilson                return null;
1976afd9b157f467b7c4f2f0b5592dca72f18d844602Jesse Wilson            }
1977afd9b157f467b7c4f2f0b5592dca72f18d844602Jesse Wilson            @Override public CacheRequest put(URI uri, URLConnection connection) throws IOException {
1978afd9b157f467b7c4f2f0b5592dca72f18d844602Jesse Wilson                return new CacheRequest() {
1979afd9b157f467b7c4f2f0b5592dca72f18d844602Jesse Wilson                    @Override public void abort() {
1980afd9b157f467b7c4f2f0b5592dca72f18d844602Jesse Wilson                        aborted.set(true);
1981afd9b157f467b7c4f2f0b5592dca72f18d844602Jesse Wilson                    }
1982afd9b157f467b7c4f2f0b5592dca72f18d844602Jesse Wilson                    @Override public OutputStream getBody() throws IOException {
1983afd9b157f467b7c4f2f0b5592dca72f18d844602Jesse Wilson                        return null;
1984afd9b157f467b7c4f2f0b5592dca72f18d844602Jesse Wilson                    }
1985afd9b157f467b7c4f2f0b5592dca72f18d844602Jesse Wilson                };
1986afd9b157f467b7c4f2f0b5592dca72f18d844602Jesse Wilson            }
1987afd9b157f467b7c4f2f0b5592dca72f18d844602Jesse Wilson        });
1988afd9b157f467b7c4f2f0b5592dca72f18d844602Jesse Wilson
1989afd9b157f467b7c4f2f0b5592dca72f18d844602Jesse Wilson        server.enqueue(new MockResponse().setBody("abcdef"));
1990afd9b157f467b7c4f2f0b5592dca72f18d844602Jesse Wilson        server.play();
1991afd9b157f467b7c4f2f0b5592dca72f18d844602Jesse Wilson
1992afd9b157f467b7c4f2f0b5592dca72f18d844602Jesse Wilson        HttpURLConnection connection = (HttpURLConnection) server.getUrl("/").openConnection();
1993afd9b157f467b7c4f2f0b5592dca72f18d844602Jesse Wilson        InputStream in = connection.getInputStream();
1994afd9b157f467b7c4f2f0b5592dca72f18d844602Jesse Wilson        assertEquals("abc", readAscii(in, 3));
1995afd9b157f467b7c4f2f0b5592dca72f18d844602Jesse Wilson        in.close();
1996afd9b157f467b7c4f2f0b5592dca72f18d844602Jesse Wilson        assertFalse(aborted.get()); // The best behavior is ambiguous, but RI 6 doesn't abort here
1997afd9b157f467b7c4f2f0b5592dca72f18d844602Jesse Wilson    }
1998d1b5e5da828434388e486a388710d21e4306dae0Jesse Wilson
19995e8b5a55eda914b67c62b4e77152922d5c77eb68Jesse Wilson
20005e8b5a55eda914b67c62b4e77152922d5c77eb68Jesse Wilson    /**
20015e8b5a55eda914b67c62b4e77152922d5c77eb68Jesse Wilson     * http://code.google.com/p/android/issues/detail?id=14562
20025e8b5a55eda914b67c62b4e77152922d5c77eb68Jesse Wilson     */
20035e8b5a55eda914b67c62b4e77152922d5c77eb68Jesse Wilson    public void testReadAfterLastByte() throws Exception {
20045e8b5a55eda914b67c62b4e77152922d5c77eb68Jesse Wilson        server.enqueue(new MockResponse()
20055e8b5a55eda914b67c62b4e77152922d5c77eb68Jesse Wilson                .setBody("ABC")
20065e8b5a55eda914b67c62b4e77152922d5c77eb68Jesse Wilson                .clearHeaders()
20075e8b5a55eda914b67c62b4e77152922d5c77eb68Jesse Wilson                .addHeader("Connection: close")
20085e8b5a55eda914b67c62b4e77152922d5c77eb68Jesse Wilson                .setSocketPolicy(SocketPolicy.DISCONNECT_AT_END));
20095e8b5a55eda914b67c62b4e77152922d5c77eb68Jesse Wilson        server.play();
20105e8b5a55eda914b67c62b4e77152922d5c77eb68Jesse Wilson
20115e8b5a55eda914b67c62b4e77152922d5c77eb68Jesse Wilson        HttpURLConnection connection = (HttpURLConnection) server.getUrl("/").openConnection();
20125e8b5a55eda914b67c62b4e77152922d5c77eb68Jesse Wilson        InputStream in = connection.getInputStream();
20135e8b5a55eda914b67c62b4e77152922d5c77eb68Jesse Wilson        assertEquals("ABC", readAscii(in, 3));
20145e8b5a55eda914b67c62b4e77152922d5c77eb68Jesse Wilson        assertEquals(-1, in.read());
2015bc4c79c6a2059003f695f7ad204de36700e8d701Jesse Wilson        assertEquals(-1, in.read()); // throws IOException in Gingerbread
2016bc4c79c6a2059003f695f7ad204de36700e8d701Jesse Wilson    }
2017bc4c79c6a2059003f695f7ad204de36700e8d701Jesse Wilson
2018ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson    public void testGetContent() throws Exception {
2019ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson        server.enqueue(new MockResponse().setBody("A"));
2020ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson        server.play();
2021ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson        HttpURLConnection connection = (HttpURLConnection) server.getUrl("/").openConnection();
2022ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson        InputStream in = (InputStream) connection.getContent();
2023ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson        assertEquals("A", readAscii(in, Integer.MAX_VALUE));
2024ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson    }
2025ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson
2026ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson    public void testGetContentOfType() throws Exception {
2027ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson        server.enqueue(new MockResponse().setBody("A"));
2028ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson        server.play();
2029ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson        HttpURLConnection connection = (HttpURLConnection) server.getUrl("/").openConnection();
2030ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson        try {
2031ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson            connection.getContent(null);
2032ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson            fail();
2033ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson        } catch (NullPointerException expected) {
2034ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson        }
2035ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson        try {
2036ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson            connection.getContent(new Class[] { null });
2037ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson            fail();
2038ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson        } catch (NullPointerException expected) {
2039ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson        }
2040ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson        assertNull(connection.getContent(new Class[] { getClass() }));
2041ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson        connection.disconnect();
2042ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson    }
2043ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson
2044ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson    public void testGetOutputStreamOnGetFails() throws Exception {
2045ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson        server.enqueue(new MockResponse());
2046ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson        server.play();
2047ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson        HttpURLConnection connection = (HttpURLConnection) server.getUrl("/").openConnection();
2048ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson        try {
2049ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson            connection.getOutputStream();
2050ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson            fail();
2051ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson        } catch (ProtocolException expected) {
2052ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson        }
2053ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson    }
2054ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson
2055ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson    public void testGetOutputAfterGetInputStreamFails() throws Exception {
2056ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson        server.enqueue(new MockResponse());
2057ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson        server.play();
2058ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson        HttpURLConnection connection = (HttpURLConnection) server.getUrl("/").openConnection();
2059ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson        connection.setDoOutput(true);
2060ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson        try {
2061ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson            connection.getInputStream();
2062ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson            connection.getOutputStream();
2063ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson            fail();
2064ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson        } catch (ProtocolException expected) {
2065ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson        }
2066ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson    }
2067ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson
2068ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson    public void testSetDoOutputOrDoInputAfterConnectFails() throws Exception {
2069ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson        server.enqueue(new MockResponse());
2070ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson        server.play();
2071ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson        HttpURLConnection connection = (HttpURLConnection) server.getUrl("/").openConnection();
2072ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson        connection.connect();
2073ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson        try {
2074ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson            connection.setDoOutput(true);
2075ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson            fail();
2076ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson        } catch (IllegalStateException expected) {
2077ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson        }
2078ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson        try {
2079ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson            connection.setDoInput(true);
2080ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson            fail();
2081ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson        } catch (IllegalStateException expected) {
2082ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson        }
2083ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson        connection.disconnect();
2084ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson    }
2085ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson
2086ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson    public void testClientSendsContentLength() throws Exception {
2087ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson        server.enqueue(new MockResponse().setBody("A"));
2088ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson        server.play();
2089ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson        HttpURLConnection connection = (HttpURLConnection) server.getUrl("/").openConnection();
2090ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson        connection.setDoOutput(true);
2091ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson        OutputStream out = connection.getOutputStream();
2092ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson        out.write(new byte[] { 'A', 'B', 'C' });
2093ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson        out.close();
2094ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson        assertEquals("A", readAscii(connection.getInputStream(), Integer.MAX_VALUE));
2095ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson        RecordedRequest request = server.takeRequest();
2096ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson        assertContains(request.getHeaders(), "Content-Length: 3");
2097ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson    }
2098ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson
2099ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson    public void testGetContentLengthConnects() throws Exception {
2100ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson        server.enqueue(new MockResponse().setBody("ABC"));
2101ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson        server.play();
2102ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson        HttpURLConnection connection = (HttpURLConnection) server.getUrl("/").openConnection();
2103ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson        assertEquals(3, connection.getContentLength());
2104ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson        connection.disconnect();
2105ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson    }
2106ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson
2107ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson    public void testGetContentTypeConnects() throws Exception {
2108ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson        server.enqueue(new MockResponse()
2109ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson                .addHeader("Content-Type: text/plain")
2110ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson                .setBody("ABC"));
2111ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson        server.play();
2112ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson        HttpURLConnection connection = (HttpURLConnection) server.getUrl("/").openConnection();
2113ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson        assertEquals("text/plain", connection.getContentType());
2114ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson        connection.disconnect();
2115ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson    }
2116ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson
2117ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson    public void testGetContentEncodingConnects() throws Exception {
2118ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson        server.enqueue(new MockResponse()
2119ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson                .addHeader("Content-Encoding: identity")
2120ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson                .setBody("ABC"));
2121ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson        server.play();
2122ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson        HttpURLConnection connection = (HttpURLConnection) server.getUrl("/").openConnection();
2123ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson        assertEquals("identity", connection.getContentEncoding());
2124ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson        connection.disconnect();
2125ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson    }
2126ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson
21275292410e4ebf7fb5149eefd2f52fcb94c46690a6Jesse Wilson    // http://b/4361656
21285292410e4ebf7fb5149eefd2f52fcb94c46690a6Jesse Wilson    public void testUrlContainsQueryButNoPath() throws Exception {
21295292410e4ebf7fb5149eefd2f52fcb94c46690a6Jesse Wilson        server.enqueue(new MockResponse().setBody("A"));
21305292410e4ebf7fb5149eefd2f52fcb94c46690a6Jesse Wilson        server.play();
21315292410e4ebf7fb5149eefd2f52fcb94c46690a6Jesse Wilson        URL url = new URL("http", server.getHostName(), server.getPort(), "?query");
21325292410e4ebf7fb5149eefd2f52fcb94c46690a6Jesse Wilson        assertEquals("A", readAscii(url.openConnection().getInputStream(), Integer.MAX_VALUE));
21335292410e4ebf7fb5149eefd2f52fcb94c46690a6Jesse Wilson        RecordedRequest request = server.takeRequest();
21345292410e4ebf7fb5149eefd2f52fcb94c46690a6Jesse Wilson        assertEquals("GET /?query HTTP/1.1", request.getRequestLine());
21355292410e4ebf7fb5149eefd2f52fcb94c46690a6Jesse Wilson    }
21365292410e4ebf7fb5149eefd2f52fcb94c46690a6Jesse Wilson
213725a753691a80186cd4d7086b12c0e52225d95897Jesse Wilson    // http://code.google.com/p/android/issues/detail?id=20442
213825a753691a80186cd4d7086b12c0e52225d95897Jesse Wilson    public void testInputStreamAvailableWithChunkedEncoding() throws Exception {
213925a753691a80186cd4d7086b12c0e52225d95897Jesse Wilson        testInputStreamAvailable(TransferKind.CHUNKED);
214025a753691a80186cd4d7086b12c0e52225d95897Jesse Wilson    }
214125a753691a80186cd4d7086b12c0e52225d95897Jesse Wilson
214225a753691a80186cd4d7086b12c0e52225d95897Jesse Wilson    public void testInputStreamAvailableWithContentLengthHeader() throws Exception {
214325a753691a80186cd4d7086b12c0e52225d95897Jesse Wilson        testInputStreamAvailable(TransferKind.FIXED_LENGTH);
214425a753691a80186cd4d7086b12c0e52225d95897Jesse Wilson    }
214525a753691a80186cd4d7086b12c0e52225d95897Jesse Wilson
214625a753691a80186cd4d7086b12c0e52225d95897Jesse Wilson    public void testInputStreamAvailableWithNoLengthHeaders() throws Exception {
214725a753691a80186cd4d7086b12c0e52225d95897Jesse Wilson        testInputStreamAvailable(TransferKind.END_OF_STREAM);
214825a753691a80186cd4d7086b12c0e52225d95897Jesse Wilson    }
214925a753691a80186cd4d7086b12c0e52225d95897Jesse Wilson
215025a753691a80186cd4d7086b12c0e52225d95897Jesse Wilson    private void testInputStreamAvailable(TransferKind transferKind) throws IOException {
215125a753691a80186cd4d7086b12c0e52225d95897Jesse Wilson        String body = "ABCDEFGH";
215225a753691a80186cd4d7086b12c0e52225d95897Jesse Wilson        MockResponse response = new MockResponse();
215325a753691a80186cd4d7086b12c0e52225d95897Jesse Wilson        transferKind.setBody(response, body, 4);
215425a753691a80186cd4d7086b12c0e52225d95897Jesse Wilson        server.enqueue(response);
215525a753691a80186cd4d7086b12c0e52225d95897Jesse Wilson        server.play();
215625a753691a80186cd4d7086b12c0e52225d95897Jesse Wilson        URLConnection connection = server.getUrl("/").openConnection();
215725a753691a80186cd4d7086b12c0e52225d95897Jesse Wilson        InputStream in = connection.getInputStream();
215825a753691a80186cd4d7086b12c0e52225d95897Jesse Wilson        for (int i = 0; i < body.length(); i++) {
215925a753691a80186cd4d7086b12c0e52225d95897Jesse Wilson            assertTrue(in.available() >= 0);
216025a753691a80186cd4d7086b12c0e52225d95897Jesse Wilson            assertEquals(body.charAt(i), in.read());
216125a753691a80186cd4d7086b12c0e52225d95897Jesse Wilson        }
216225a753691a80186cd4d7086b12c0e52225d95897Jesse Wilson        assertEquals(0, in.available());
216325a753691a80186cd4d7086b12c0e52225d95897Jesse Wilson        assertEquals(-1, in.read());
216425a753691a80186cd4d7086b12c0e52225d95897Jesse Wilson    }
216525a753691a80186cd4d7086b12c0e52225d95897Jesse Wilson
2166deb26711801f9bfafcd5cad20963b3c3913404fdElliott Hughes    // http://code.google.com/p/android/issues/detail?id=28095
2167deb26711801f9bfafcd5cad20963b3c3913404fdElliott Hughes    public void testInvalidIpv4Address() throws Exception {
2168deb26711801f9bfafcd5cad20963b3c3913404fdElliott Hughes        try {
2169deb26711801f9bfafcd5cad20963b3c3913404fdElliott Hughes            URI uri = new URI("http://1111.111.111.111/index.html");
2170deb26711801f9bfafcd5cad20963b3c3913404fdElliott Hughes            uri.toURL().openConnection().connect();
2171deb26711801f9bfafcd5cad20963b3c3913404fdElliott Hughes            fail();
2172deb26711801f9bfafcd5cad20963b3c3913404fdElliott Hughes        } catch (UnknownHostException expected) {
2173deb26711801f9bfafcd5cad20963b3c3913404fdElliott Hughes        }
2174deb26711801f9bfafcd5cad20963b3c3913404fdElliott Hughes    }
2175deb26711801f9bfafcd5cad20963b3c3913404fdElliott Hughes
2176d0d626655f1d452070d3116678037e8759f807f4Jesse Wilson    // http://code.google.com/p/android/issues/detail?id=16895
2177d0d626655f1d452070d3116678037e8759f807f4Jesse Wilson    public void testUrlWithSpaceInHost() throws Exception {
2178d0d626655f1d452070d3116678037e8759f807f4Jesse Wilson        URLConnection urlConnection = new URL("http://and roid.com/").openConnection();
2179d0d626655f1d452070d3116678037e8759f807f4Jesse Wilson        try {
2180d0d626655f1d452070d3116678037e8759f807f4Jesse Wilson            urlConnection.getInputStream();
2181d0d626655f1d452070d3116678037e8759f807f4Jesse Wilson            fail();
2182d0d626655f1d452070d3116678037e8759f807f4Jesse Wilson        } catch (UnknownHostException expected) {
2183d0d626655f1d452070d3116678037e8759f807f4Jesse Wilson        }
2184d0d626655f1d452070d3116678037e8759f807f4Jesse Wilson    }
2185d0d626655f1d452070d3116678037e8759f807f4Jesse Wilson
2186d0d626655f1d452070d3116678037e8759f807f4Jesse Wilson    public void testUrlWithSpaceInHostViaHttpProxy() throws Exception {
2187d0d626655f1d452070d3116678037e8759f807f4Jesse Wilson        server.enqueue(new MockResponse());
2188d0d626655f1d452070d3116678037e8759f807f4Jesse Wilson        server.play();
2189d0d626655f1d452070d3116678037e8759f807f4Jesse Wilson        URLConnection urlConnection = new URL("http://and roid.com/")
2190d0d626655f1d452070d3116678037e8759f807f4Jesse Wilson                .openConnection(server.toProxyAddress());
2191d0d626655f1d452070d3116678037e8759f807f4Jesse Wilson        try {
2192d0d626655f1d452070d3116678037e8759f807f4Jesse Wilson            urlConnection.getInputStream();
2193d0d626655f1d452070d3116678037e8759f807f4Jesse Wilson            fail(); // the RI makes a bogus proxy request for "GET http://and roid.com/ HTTP/1.1"
2194d0d626655f1d452070d3116678037e8759f807f4Jesse Wilson        } catch (UnknownHostException expected) {
2195d0d626655f1d452070d3116678037e8759f807f4Jesse Wilson        }
2196d0d626655f1d452070d3116678037e8759f807f4Jesse Wilson    }
2197d0d626655f1d452070d3116678037e8759f807f4Jesse Wilson
2198abe4e615f473b387b1c00a738062a7c428f05a33Jesse Wilson    public void testSslFallback() throws Exception {
2199abe4e615f473b387b1c00a738062a7c428f05a33Jesse Wilson        TestSSLContext testSSLContext = TestSSLContext.create();
2200abe4e615f473b387b1c00a738062a7c428f05a33Jesse Wilson        server.useHttps(testSSLContext.serverContext.getSocketFactory(), false);
2201abe4e615f473b387b1c00a738062a7c428f05a33Jesse Wilson        server.enqueue(new MockResponse().setSocketPolicy(SocketPolicy.FAIL_HANDSHAKE));
2202abe4e615f473b387b1c00a738062a7c428f05a33Jesse Wilson        server.enqueue(new MockResponse().setBody("This required a 2nd handshake"));
2203abe4e615f473b387b1c00a738062a7c428f05a33Jesse Wilson        server.play();
2204abe4e615f473b387b1c00a738062a7c428f05a33Jesse Wilson
2205abe4e615f473b387b1c00a738062a7c428f05a33Jesse Wilson        HttpsURLConnection connection = (HttpsURLConnection) server.getUrl("/").openConnection();
2206abe4e615f473b387b1c00a738062a7c428f05a33Jesse Wilson        connection.setSSLSocketFactory(testSSLContext.clientContext.getSocketFactory());
2207abe4e615f473b387b1c00a738062a7c428f05a33Jesse Wilson        assertEquals("This required a 2nd handshake",
2208abe4e615f473b387b1c00a738062a7c428f05a33Jesse Wilson                readAscii(connection.getInputStream(), Integer.MAX_VALUE));
2209abe4e615f473b387b1c00a738062a7c428f05a33Jesse Wilson
2210abe4e615f473b387b1c00a738062a7c428f05a33Jesse Wilson        RecordedRequest first = server.takeRequest();
2211abe4e615f473b387b1c00a738062a7c428f05a33Jesse Wilson        assertEquals(0, first.getSequenceNumber());
2212abe4e615f473b387b1c00a738062a7c428f05a33Jesse Wilson        RecordedRequest retry = server.takeRequest();
2213abe4e615f473b387b1c00a738062a7c428f05a33Jesse Wilson        assertEquals(0, retry.getSequenceNumber());
2214abe4e615f473b387b1c00a738062a7c428f05a33Jesse Wilson        assertEquals("SSLv3", retry.getSslProtocol());
2215abe4e615f473b387b1c00a738062a7c428f05a33Jesse Wilson    }
2216abe4e615f473b387b1c00a738062a7c428f05a33Jesse Wilson
2217a468471e8ccc2f642d5b2ae3c75873a74267ece2Jesse Wilson    public void testInspectSslBeforeConnect() throws Exception {
2218a468471e8ccc2f642d5b2ae3c75873a74267ece2Jesse Wilson        TestSSLContext testSSLContext = TestSSLContext.create();
2219a468471e8ccc2f642d5b2ae3c75873a74267ece2Jesse Wilson        server.useHttps(testSSLContext.serverContext.getSocketFactory(), false);
2220a468471e8ccc2f642d5b2ae3c75873a74267ece2Jesse Wilson        server.enqueue(new MockResponse());
2221a468471e8ccc2f642d5b2ae3c75873a74267ece2Jesse Wilson        server.play();
2222a468471e8ccc2f642d5b2ae3c75873a74267ece2Jesse Wilson
2223a468471e8ccc2f642d5b2ae3c75873a74267ece2Jesse Wilson        HttpsURLConnection connection = (HttpsURLConnection) server.getUrl("/").openConnection();
2224a468471e8ccc2f642d5b2ae3c75873a74267ece2Jesse Wilson        connection.setSSLSocketFactory(testSSLContext.clientContext.getSocketFactory());
2225a468471e8ccc2f642d5b2ae3c75873a74267ece2Jesse Wilson        assertNotNull(connection.getHostnameVerifier());
2226a468471e8ccc2f642d5b2ae3c75873a74267ece2Jesse Wilson        try {
2227a468471e8ccc2f642d5b2ae3c75873a74267ece2Jesse Wilson            connection.getLocalCertificates();
2228a468471e8ccc2f642d5b2ae3c75873a74267ece2Jesse Wilson            fail();
2229a468471e8ccc2f642d5b2ae3c75873a74267ece2Jesse Wilson        } catch (IllegalStateException expected) {
2230a468471e8ccc2f642d5b2ae3c75873a74267ece2Jesse Wilson        }
2231a468471e8ccc2f642d5b2ae3c75873a74267ece2Jesse Wilson        try {
2232a468471e8ccc2f642d5b2ae3c75873a74267ece2Jesse Wilson            connection.getServerCertificates();
2233a468471e8ccc2f642d5b2ae3c75873a74267ece2Jesse Wilson            fail();
2234a468471e8ccc2f642d5b2ae3c75873a74267ece2Jesse Wilson        } catch (IllegalStateException expected) {
2235a468471e8ccc2f642d5b2ae3c75873a74267ece2Jesse Wilson        }
2236a468471e8ccc2f642d5b2ae3c75873a74267ece2Jesse Wilson        try {
2237a468471e8ccc2f642d5b2ae3c75873a74267ece2Jesse Wilson            connection.getCipherSuite();
2238a468471e8ccc2f642d5b2ae3c75873a74267ece2Jesse Wilson            fail();
2239a468471e8ccc2f642d5b2ae3c75873a74267ece2Jesse Wilson        } catch (IllegalStateException expected) {
2240a468471e8ccc2f642d5b2ae3c75873a74267ece2Jesse Wilson        }
2241a468471e8ccc2f642d5b2ae3c75873a74267ece2Jesse Wilson        try {
2242a468471e8ccc2f642d5b2ae3c75873a74267ece2Jesse Wilson            connection.getPeerPrincipal();
2243a468471e8ccc2f642d5b2ae3c75873a74267ece2Jesse Wilson            fail();
2244a468471e8ccc2f642d5b2ae3c75873a74267ece2Jesse Wilson        } catch (IllegalStateException expected) {
2245a468471e8ccc2f642d5b2ae3c75873a74267ece2Jesse Wilson        }
2246a468471e8ccc2f642d5b2ae3c75873a74267ece2Jesse Wilson    }
2247a468471e8ccc2f642d5b2ae3c75873a74267ece2Jesse Wilson
2248a468471e8ccc2f642d5b2ae3c75873a74267ece2Jesse Wilson    /**
2249a468471e8ccc2f642d5b2ae3c75873a74267ece2Jesse Wilson     * Test that we can inspect the SSL session after connect().
2250a468471e8ccc2f642d5b2ae3c75873a74267ece2Jesse Wilson     * http://code.google.com/p/android/issues/detail?id=24431
2251a468471e8ccc2f642d5b2ae3c75873a74267ece2Jesse Wilson     */
2252a468471e8ccc2f642d5b2ae3c75873a74267ece2Jesse Wilson    public void testInspectSslAfterConnect() throws Exception {
2253a468471e8ccc2f642d5b2ae3c75873a74267ece2Jesse Wilson        TestSSLContext testSSLContext = TestSSLContext.create();
2254a468471e8ccc2f642d5b2ae3c75873a74267ece2Jesse Wilson        server.useHttps(testSSLContext.serverContext.getSocketFactory(), false);
2255a468471e8ccc2f642d5b2ae3c75873a74267ece2Jesse Wilson        server.enqueue(new MockResponse());
2256a468471e8ccc2f642d5b2ae3c75873a74267ece2Jesse Wilson        server.play();
2257a468471e8ccc2f642d5b2ae3c75873a74267ece2Jesse Wilson
2258a468471e8ccc2f642d5b2ae3c75873a74267ece2Jesse Wilson        HttpsURLConnection connection = (HttpsURLConnection) server.getUrl("/").openConnection();
2259a468471e8ccc2f642d5b2ae3c75873a74267ece2Jesse Wilson        connection.setSSLSocketFactory(testSSLContext.clientContext.getSocketFactory());
2260a468471e8ccc2f642d5b2ae3c75873a74267ece2Jesse Wilson        connection.connect();
2261a468471e8ccc2f642d5b2ae3c75873a74267ece2Jesse Wilson        assertNotNull(connection.getHostnameVerifier());
2262a468471e8ccc2f642d5b2ae3c75873a74267ece2Jesse Wilson        assertNull(connection.getLocalCertificates());
2263a468471e8ccc2f642d5b2ae3c75873a74267ece2Jesse Wilson        assertNotNull(connection.getServerCertificates());
2264a468471e8ccc2f642d5b2ae3c75873a74267ece2Jesse Wilson        assertNotNull(connection.getCipherSuite());
2265a468471e8ccc2f642d5b2ae3c75873a74267ece2Jesse Wilson        assertNotNull(connection.getPeerPrincipal());
2266a468471e8ccc2f642d5b2ae3c75873a74267ece2Jesse Wilson    }
2267a468471e8ccc2f642d5b2ae3c75873a74267ece2Jesse Wilson
2268bc4c79c6a2059003f695f7ad204de36700e8d701Jesse Wilson    /**
22690c59055dd24e1659f85d9ff7e2148883f663bd62Jesse Wilson     * Returns a gzipped copy of {@code bytes}.
2270deb236fb06f2a14861e7d40dea959f181cd5cf28Jesse Wilson     */
2271deb236fb06f2a14861e7d40dea959f181cd5cf28Jesse Wilson    public byte[] gzip(byte[] bytes) throws IOException {
2272deb236fb06f2a14861e7d40dea959f181cd5cf28Jesse Wilson        ByteArrayOutputStream bytesOut = new ByteArrayOutputStream();
2273deb236fb06f2a14861e7d40dea959f181cd5cf28Jesse Wilson        OutputStream gzippedOut = new GZIPOutputStream(bytesOut);
2274deb236fb06f2a14861e7d40dea959f181cd5cf28Jesse Wilson        gzippedOut.write(bytes);
2275deb236fb06f2a14861e7d40dea959f181cd5cf28Jesse Wilson        gzippedOut.close();
2276deb236fb06f2a14861e7d40dea959f181cd5cf28Jesse Wilson        return bytesOut.toByteArray();
2277deb236fb06f2a14861e7d40dea959f181cd5cf28Jesse Wilson    }
2278deb236fb06f2a14861e7d40dea959f181cd5cf28Jesse Wilson
2279c8977f474b30c5f3807398859a6b16687af6fc7bJesse Wilson    /**
2280c8977f474b30c5f3807398859a6b16687af6fc7bJesse Wilson     * Reads at most {@code limit} characters from {@code in} and asserts that
2281c8977f474b30c5f3807398859a6b16687af6fc7bJesse Wilson     * content equals {@code expected}.
2282c8977f474b30c5f3807398859a6b16687af6fc7bJesse Wilson     */
2283c8977f474b30c5f3807398859a6b16687af6fc7bJesse Wilson    private void assertContent(String expected, URLConnection connection, int limit)
2284c8977f474b30c5f3807398859a6b16687af6fc7bJesse Wilson            throws IOException {
2285f02c695ed03e708623d9365dec26d533356ef2d0Brian Carlstrom        connection.connect();
228651e468abf2628ce964d3657042f3ac8f2c947504Jesse Wilson        assertEquals(expected, readAscii(connection.getInputStream(), limit));
2287c8977f474b30c5f3807398859a6b16687af6fc7bJesse Wilson        ((HttpURLConnection) connection).disconnect();
2288c8977f474b30c5f3807398859a6b16687af6fc7bJesse Wilson    }
2289c8977f474b30c5f3807398859a6b16687af6fc7bJesse Wilson
2290c8977f474b30c5f3807398859a6b16687af6fc7bJesse Wilson    private void assertContent(String expected, URLConnection connection) throws IOException {
2291c8977f474b30c5f3807398859a6b16687af6fc7bJesse Wilson        assertContent(expected, connection, Integer.MAX_VALUE);
2292c8977f474b30c5f3807398859a6b16687af6fc7bJesse Wilson    }
2293c8977f474b30c5f3807398859a6b16687af6fc7bJesse Wilson
229460476787f0e0f052366d8031c74e507ffd3d16a3Jesse Wilson    private void assertContains(List<String> headers, String header) {
229560476787f0e0f052366d8031c74e507ffd3d16a3Jesse Wilson        assertTrue(headers.toString(), headers.contains(header));
229660476787f0e0f052366d8031c74e507ffd3d16a3Jesse Wilson    }
229751e468abf2628ce964d3657042f3ac8f2c947504Jesse Wilson
2298ffd579b668428272b78f5c6c64f9c89766f37c1aJesse Wilson    private void assertContainsNoneMatching(List<String> headers, String pattern) {
2299ffd579b668428272b78f5c6c64f9c89766f37c1aJesse Wilson        for (String header : headers) {
2300ffd579b668428272b78f5c6c64f9c89766f37c1aJesse Wilson            if (header.matches(pattern)) {
2301ffd579b668428272b78f5c6c64f9c89766f37c1aJesse Wilson                fail("Header " + header + " matches " + pattern);
2302ffd579b668428272b78f5c6c64f9c89766f37c1aJesse Wilson            }
2303ffd579b668428272b78f5c6c64f9c89766f37c1aJesse Wilson        }
2304ffd579b668428272b78f5c6c64f9c89766f37c1aJesse Wilson    }
2305ffd579b668428272b78f5c6c64f9c89766f37c1aJesse Wilson
2306eafede536f2059bb6c869e7a5f07fd7ad9758e28Jesse Wilson    private Set<String> newSet(String... elements) {
230783a47d4d0c536e06fc53eda9d5a1a5d93f9accc6Jesse Wilson        return new HashSet<String>(Arrays.asList(elements));
230883a47d4d0c536e06fc53eda9d5a1a5d93f9accc6Jesse Wilson    }
230983a47d4d0c536e06fc53eda9d5a1a5d93f9accc6Jesse Wilson
231051e468abf2628ce964d3657042f3ac8f2c947504Jesse Wilson    enum TransferKind {
231151e468abf2628ce964d3657042f3ac8f2c947504Jesse Wilson        CHUNKED() {
2312deb236fb06f2a14861e7d40dea959f181cd5cf28Jesse Wilson            @Override void setBody(MockResponse response, byte[] content, int chunkSize)
231351e468abf2628ce964d3657042f3ac8f2c947504Jesse Wilson                    throws IOException {
231451e468abf2628ce964d3657042f3ac8f2c947504Jesse Wilson                response.setChunkedBody(content, chunkSize);
231551e468abf2628ce964d3657042f3ac8f2c947504Jesse Wilson            }
231651e468abf2628ce964d3657042f3ac8f2c947504Jesse Wilson        },
231751e468abf2628ce964d3657042f3ac8f2c947504Jesse Wilson        FIXED_LENGTH() {
2318deb236fb06f2a14861e7d40dea959f181cd5cf28Jesse Wilson            @Override void setBody(MockResponse response, byte[] content, int chunkSize) {
231951e468abf2628ce964d3657042f3ac8f2c947504Jesse Wilson                response.setBody(content);
232051e468abf2628ce964d3657042f3ac8f2c947504Jesse Wilson            }
232151e468abf2628ce964d3657042f3ac8f2c947504Jesse Wilson        },
232251e468abf2628ce964d3657042f3ac8f2c947504Jesse Wilson        END_OF_STREAM() {
2323deb236fb06f2a14861e7d40dea959f181cd5cf28Jesse Wilson            @Override void setBody(MockResponse response, byte[] content, int chunkSize) {
232451e468abf2628ce964d3657042f3ac8f2c947504Jesse Wilson                response.setBody(content);
2325e942f46f10bb9384a1b186b3d7b74f9704c57090Jesse Wilson                response.setSocketPolicy(DISCONNECT_AT_END);
232651e468abf2628ce964d3657042f3ac8f2c947504Jesse Wilson                for (Iterator<String> h = response.getHeaders().iterator(); h.hasNext(); ) {
232751e468abf2628ce964d3657042f3ac8f2c947504Jesse Wilson                    if (h.next().startsWith("Content-Length:")) {
232851e468abf2628ce964d3657042f3ac8f2c947504Jesse Wilson                        h.remove();
232951e468abf2628ce964d3657042f3ac8f2c947504Jesse Wilson                        break;
233051e468abf2628ce964d3657042f3ac8f2c947504Jesse Wilson                    }
233151e468abf2628ce964d3657042f3ac8f2c947504Jesse Wilson                }
233251e468abf2628ce964d3657042f3ac8f2c947504Jesse Wilson            }
233351e468abf2628ce964d3657042f3ac8f2c947504Jesse Wilson        };
233451e468abf2628ce964d3657042f3ac8f2c947504Jesse Wilson
2335deb236fb06f2a14861e7d40dea959f181cd5cf28Jesse Wilson        abstract void setBody(MockResponse response, byte[] content, int chunkSize)
233651e468abf2628ce964d3657042f3ac8f2c947504Jesse Wilson                throws IOException;
2337deb236fb06f2a14861e7d40dea959f181cd5cf28Jesse Wilson
2338deb236fb06f2a14861e7d40dea959f181cd5cf28Jesse Wilson        void setBody(MockResponse response, String content, int chunkSize) throws IOException {
2339deb236fb06f2a14861e7d40dea959f181cd5cf28Jesse Wilson            setBody(response, content.getBytes("UTF-8"), chunkSize);
2340deb236fb06f2a14861e7d40dea959f181cd5cf28Jesse Wilson        }
234151e468abf2628ce964d3657042f3ac8f2c947504Jesse Wilson    }
2342c0372d90016d241ac979faa6fa1731f30b6f2a03Jesse Wilson
2343984fcff696380abd6ea14e80030f9fd2d09dbad0Jesse Wilson    enum ProxyConfig {
2344f02c695ed03e708623d9365dec26d533356ef2d0Brian Carlstrom        NO_PROXY() {
2345f02c695ed03e708623d9365dec26d533356ef2d0Brian Carlstrom            @Override public HttpURLConnection connect(MockWebServer server, URL url)
2346f02c695ed03e708623d9365dec26d533356ef2d0Brian Carlstrom                    throws IOException {
2347f02c695ed03e708623d9365dec26d533356ef2d0Brian Carlstrom                return (HttpURLConnection) url.openConnection(Proxy.NO_PROXY);
2348f02c695ed03e708623d9365dec26d533356ef2d0Brian Carlstrom            }
2349f02c695ed03e708623d9365dec26d533356ef2d0Brian Carlstrom        },
2350f02c695ed03e708623d9365dec26d533356ef2d0Brian Carlstrom
2351984fcff696380abd6ea14e80030f9fd2d09dbad0Jesse Wilson        CREATE_ARG() {
2352984fcff696380abd6ea14e80030f9fd2d09dbad0Jesse Wilson            @Override public HttpURLConnection connect(MockWebServer server, URL url)
2353984fcff696380abd6ea14e80030f9fd2d09dbad0Jesse Wilson                    throws IOException {
2354984fcff696380abd6ea14e80030f9fd2d09dbad0Jesse Wilson                return (HttpURLConnection) url.openConnection(server.toProxyAddress());
2355984fcff696380abd6ea14e80030f9fd2d09dbad0Jesse Wilson            }
2356984fcff696380abd6ea14e80030f9fd2d09dbad0Jesse Wilson        },
2357984fcff696380abd6ea14e80030f9fd2d09dbad0Jesse Wilson
2358984fcff696380abd6ea14e80030f9fd2d09dbad0Jesse Wilson        PROXY_SYSTEM_PROPERTY() {
2359984fcff696380abd6ea14e80030f9fd2d09dbad0Jesse Wilson            @Override public HttpURLConnection connect(MockWebServer server, URL url)
2360984fcff696380abd6ea14e80030f9fd2d09dbad0Jesse Wilson                    throws IOException {
2361984fcff696380abd6ea14e80030f9fd2d09dbad0Jesse Wilson                System.setProperty("proxyHost", "localhost");
2362984fcff696380abd6ea14e80030f9fd2d09dbad0Jesse Wilson                System.setProperty("proxyPort", Integer.toString(server.getPort()));
2363984fcff696380abd6ea14e80030f9fd2d09dbad0Jesse Wilson                return (HttpURLConnection) url.openConnection();
2364984fcff696380abd6ea14e80030f9fd2d09dbad0Jesse Wilson            }
2365984fcff696380abd6ea14e80030f9fd2d09dbad0Jesse Wilson        },
2366984fcff696380abd6ea14e80030f9fd2d09dbad0Jesse Wilson
2367984fcff696380abd6ea14e80030f9fd2d09dbad0Jesse Wilson        HTTP_PROXY_SYSTEM_PROPERTY() {
2368984fcff696380abd6ea14e80030f9fd2d09dbad0Jesse Wilson            @Override public HttpURLConnection connect(MockWebServer server, URL url)
2369984fcff696380abd6ea14e80030f9fd2d09dbad0Jesse Wilson                    throws IOException {
2370984fcff696380abd6ea14e80030f9fd2d09dbad0Jesse Wilson                System.setProperty("http.proxyHost", "localhost");
2371984fcff696380abd6ea14e80030f9fd2d09dbad0Jesse Wilson                System.setProperty("http.proxyPort", Integer.toString(server.getPort()));
2372984fcff696380abd6ea14e80030f9fd2d09dbad0Jesse Wilson                return (HttpURLConnection) url.openConnection();
2373984fcff696380abd6ea14e80030f9fd2d09dbad0Jesse Wilson            }
2374984fcff696380abd6ea14e80030f9fd2d09dbad0Jesse Wilson        },
2375984fcff696380abd6ea14e80030f9fd2d09dbad0Jesse Wilson
2376984fcff696380abd6ea14e80030f9fd2d09dbad0Jesse Wilson        HTTPS_PROXY_SYSTEM_PROPERTY() {
2377984fcff696380abd6ea14e80030f9fd2d09dbad0Jesse Wilson            @Override public HttpURLConnection connect(MockWebServer server, URL url)
2378984fcff696380abd6ea14e80030f9fd2d09dbad0Jesse Wilson                    throws IOException {
2379984fcff696380abd6ea14e80030f9fd2d09dbad0Jesse Wilson                System.setProperty("https.proxyHost", "localhost");
2380984fcff696380abd6ea14e80030f9fd2d09dbad0Jesse Wilson                System.setProperty("https.proxyPort", Integer.toString(server.getPort()));
2381984fcff696380abd6ea14e80030f9fd2d09dbad0Jesse Wilson                return (HttpURLConnection) url.openConnection();
2382984fcff696380abd6ea14e80030f9fd2d09dbad0Jesse Wilson            }
2383984fcff696380abd6ea14e80030f9fd2d09dbad0Jesse Wilson        };
2384984fcff696380abd6ea14e80030f9fd2d09dbad0Jesse Wilson
2385984fcff696380abd6ea14e80030f9fd2d09dbad0Jesse Wilson        public abstract HttpURLConnection connect(MockWebServer server, URL url) throws IOException;
2386984fcff696380abd6ea14e80030f9fd2d09dbad0Jesse Wilson    }
2387984fcff696380abd6ea14e80030f9fd2d09dbad0Jesse Wilson
2388c0372d90016d241ac979faa6fa1731f30b6f2a03Jesse Wilson    private static class RecordingTrustManager implements X509TrustManager {
2389c0372d90016d241ac979faa6fa1731f30b6f2a03Jesse Wilson        private final List<String> calls = new ArrayList<String>();
2390c0372d90016d241ac979faa6fa1731f30b6f2a03Jesse Wilson
2391c0372d90016d241ac979faa6fa1731f30b6f2a03Jesse Wilson        public X509Certificate[] getAcceptedIssuers() {
2392c0372d90016d241ac979faa6fa1731f30b6f2a03Jesse Wilson            calls.add("getAcceptedIssuers");
2393c0372d90016d241ac979faa6fa1731f30b6f2a03Jesse Wilson            return new X509Certificate[] {};
2394c0372d90016d241ac979faa6fa1731f30b6f2a03Jesse Wilson        }
2395c0372d90016d241ac979faa6fa1731f30b6f2a03Jesse Wilson
2396c0372d90016d241ac979faa6fa1731f30b6f2a03Jesse Wilson        public void checkClientTrusted(X509Certificate[] chain, String authType)
2397c0372d90016d241ac979faa6fa1731f30b6f2a03Jesse Wilson                throws CertificateException {
2398c0372d90016d241ac979faa6fa1731f30b6f2a03Jesse Wilson            calls.add("checkClientTrusted " + certificatesToString(chain) + " " + authType);
2399c0372d90016d241ac979faa6fa1731f30b6f2a03Jesse Wilson        }
2400c0372d90016d241ac979faa6fa1731f30b6f2a03Jesse Wilson
2401c0372d90016d241ac979faa6fa1731f30b6f2a03Jesse Wilson        public void checkServerTrusted(X509Certificate[] chain, String authType)
2402c0372d90016d241ac979faa6fa1731f30b6f2a03Jesse Wilson                throws CertificateException {
2403c0372d90016d241ac979faa6fa1731f30b6f2a03Jesse Wilson            calls.add("checkServerTrusted " + certificatesToString(chain) + " " + authType);
2404c0372d90016d241ac979faa6fa1731f30b6f2a03Jesse Wilson        }
2405c0372d90016d241ac979faa6fa1731f30b6f2a03Jesse Wilson
2406c0372d90016d241ac979faa6fa1731f30b6f2a03Jesse Wilson        private String certificatesToString(X509Certificate[] certificates) {
2407c0372d90016d241ac979faa6fa1731f30b6f2a03Jesse Wilson            List<String> result = new ArrayList<String>();
2408c0372d90016d241ac979faa6fa1731f30b6f2a03Jesse Wilson            for (X509Certificate certificate : certificates) {
2409c0372d90016d241ac979faa6fa1731f30b6f2a03Jesse Wilson                result.add(certificate.getSubjectDN() + " " + certificate.getSerialNumber());
2410c0372d90016d241ac979faa6fa1731f30b6f2a03Jesse Wilson            }
2411c0372d90016d241ac979faa6fa1731f30b6f2a03Jesse Wilson            return result.toString();
2412c0372d90016d241ac979faa6fa1731f30b6f2a03Jesse Wilson        }
2413c0372d90016d241ac979faa6fa1731f30b6f2a03Jesse Wilson    }
2414c0372d90016d241ac979faa6fa1731f30b6f2a03Jesse Wilson
2415c0372d90016d241ac979faa6fa1731f30b6f2a03Jesse Wilson    private static class RecordingHostnameVerifier implements HostnameVerifier {
2416c0372d90016d241ac979faa6fa1731f30b6f2a03Jesse Wilson        private final List<String> calls = new ArrayList<String>();
2417c0372d90016d241ac979faa6fa1731f30b6f2a03Jesse Wilson
2418c0372d90016d241ac979faa6fa1731f30b6f2a03Jesse Wilson        public boolean verify(String hostname, SSLSession session) {
2419c0372d90016d241ac979faa6fa1731f30b6f2a03Jesse Wilson            calls.add("verify " + hostname);
2420c0372d90016d241ac979faa6fa1731f30b6f2a03Jesse Wilson            return true;
2421c0372d90016d241ac979faa6fa1731f30b6f2a03Jesse Wilson        }
2422c0372d90016d241ac979faa6fa1731f30b6f2a03Jesse Wilson    }
24235757cb35ad2e58d7accb7f5d3db6f2d5e72f097dJesse Wilson
24245757cb35ad2e58d7accb7f5d3db6f2d5e72f097dJesse Wilson    private static class SimpleAuthenticator extends Authenticator {
24255757cb35ad2e58d7accb7f5d3db6f2d5e72f097dJesse Wilson        /** base64("username:password") */
24265757cb35ad2e58d7accb7f5d3db6f2d5e72f097dJesse Wilson        private static final String BASE_64_CREDENTIALS = "dXNlcm5hbWU6cGFzc3dvcmQ=";
24275757cb35ad2e58d7accb7f5d3db6f2d5e72f097dJesse Wilson
24285757cb35ad2e58d7accb7f5d3db6f2d5e72f097dJesse Wilson        private String expectedPrompt;
24295757cb35ad2e58d7accb7f5d3db6f2d5e72f097dJesse Wilson        private RequestorType requestorType;
24305757cb35ad2e58d7accb7f5d3db6f2d5e72f097dJesse Wilson        private int requestingPort;
24315757cb35ad2e58d7accb7f5d3db6f2d5e72f097dJesse Wilson        private InetAddress requestingSite;
24325757cb35ad2e58d7accb7f5d3db6f2d5e72f097dJesse Wilson        private String requestingPrompt;
24335757cb35ad2e58d7accb7f5d3db6f2d5e72f097dJesse Wilson        private String requestingProtocol;
24345757cb35ad2e58d7accb7f5d3db6f2d5e72f097dJesse Wilson        private String requestingScheme;
24355757cb35ad2e58d7accb7f5d3db6f2d5e72f097dJesse Wilson
24365757cb35ad2e58d7accb7f5d3db6f2d5e72f097dJesse Wilson        protected PasswordAuthentication getPasswordAuthentication() {
24375757cb35ad2e58d7accb7f5d3db6f2d5e72f097dJesse Wilson            requestorType = getRequestorType();
24385757cb35ad2e58d7accb7f5d3db6f2d5e72f097dJesse Wilson            requestingPort = getRequestingPort();
24395757cb35ad2e58d7accb7f5d3db6f2d5e72f097dJesse Wilson            requestingSite = getRequestingSite();
24405757cb35ad2e58d7accb7f5d3db6f2d5e72f097dJesse Wilson            requestingPrompt = getRequestingPrompt();
24415757cb35ad2e58d7accb7f5d3db6f2d5e72f097dJesse Wilson            requestingProtocol = getRequestingProtocol();
24425757cb35ad2e58d7accb7f5d3db6f2d5e72f097dJesse Wilson            requestingScheme = getRequestingScheme();
24435757cb35ad2e58d7accb7f5d3db6f2d5e72f097dJesse Wilson            return (expectedPrompt == null || expectedPrompt.equals(requestingPrompt))
24445757cb35ad2e58d7accb7f5d3db6f2d5e72f097dJesse Wilson                    ? new PasswordAuthentication("username", "password".toCharArray())
24455757cb35ad2e58d7accb7f5d3db6f2d5e72f097dJesse Wilson                    : null;
24465757cb35ad2e58d7accb7f5d3db6f2d5e72f097dJesse Wilson        }
24475757cb35ad2e58d7accb7f5d3db6f2d5e72f097dJesse Wilson    }
2448e40c9e3935a5024c0f3ebfb3f1441fcd5c48ed86Elliott Hughes}
2449