URLConnectionTest.java revision 6d41a7cc3cb4cc684c8bece69ddc55954812ad6e
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
798d4bddd7d1fb7b1b7f0836648228235c6e4b56a18Jesse Wilson    public void testDisconnectedConnection() throws IOException {
799d4bddd7d1fb7b1b7f0836648228235c6e4b56a18Jesse Wilson        server.enqueue(new MockResponse().setBody("ABCDEFGHIJKLMNOPQR"));
800d4bddd7d1fb7b1b7f0836648228235c6e4b56a18Jesse Wilson        server.play();
801d4bddd7d1fb7b1b7f0836648228235c6e4b56a18Jesse Wilson
802d4bddd7d1fb7b1b7f0836648228235c6e4b56a18Jesse Wilson        HttpURLConnection connection = (HttpURLConnection) server.getUrl("/").openConnection();
803d4bddd7d1fb7b1b7f0836648228235c6e4b56a18Jesse Wilson        InputStream in = connection.getInputStream();
804d4bddd7d1fb7b1b7f0836648228235c6e4b56a18Jesse Wilson        assertEquals('A', (char) in.read());
805d4bddd7d1fb7b1b7f0836648228235c6e4b56a18Jesse Wilson        connection.disconnect();
806d4bddd7d1fb7b1b7f0836648228235c6e4b56a18Jesse Wilson        try {
807d4bddd7d1fb7b1b7f0836648228235c6e4b56a18Jesse Wilson            in.read();
808d4bddd7d1fb7b1b7f0836648228235c6e4b56a18Jesse Wilson            fail("Expected a connection closed exception");
809d4bddd7d1fb7b1b7f0836648228235c6e4b56a18Jesse Wilson        } catch (IOException expected) {
810d4bddd7d1fb7b1b7f0836648228235c6e4b56a18Jesse Wilson        }
811d4bddd7d1fb7b1b7f0836648228235c6e4b56a18Jesse Wilson    }
812d4bddd7d1fb7b1b7f0836648228235c6e4b56a18Jesse Wilson
813d742d7fc7f0593eb8c6e4ac9dd4c0f6a80374e46Jesse Wilson    public void testDisconnectBeforeConnect() throws IOException {
814d742d7fc7f0593eb8c6e4ac9dd4c0f6a80374e46Jesse Wilson        server.enqueue(new MockResponse().setBody("A"));
815d742d7fc7f0593eb8c6e4ac9dd4c0f6a80374e46Jesse Wilson        server.play();
816d742d7fc7f0593eb8c6e4ac9dd4c0f6a80374e46Jesse Wilson
817d742d7fc7f0593eb8c6e4ac9dd4c0f6a80374e46Jesse Wilson        HttpURLConnection connection = (HttpURLConnection) server.getUrl("/").openConnection();
818d742d7fc7f0593eb8c6e4ac9dd4c0f6a80374e46Jesse Wilson        connection.disconnect();
819d742d7fc7f0593eb8c6e4ac9dd4c0f6a80374e46Jesse Wilson
820d742d7fc7f0593eb8c6e4ac9dd4c0f6a80374e46Jesse Wilson        assertContent("A", connection);
821d742d7fc7f0593eb8c6e4ac9dd4c0f6a80374e46Jesse Wilson        assertEquals(200, connection.getResponseCode());
822d742d7fc7f0593eb8c6e4ac9dd4c0f6a80374e46Jesse Wilson    }
823d742d7fc7f0593eb8c6e4ac9dd4c0f6a80374e46Jesse Wilson
8248155888a2c4e7cc28596deec28433e1984cfaf11Brian Carlstrom    public void testDisconnectAfterOnlyResponseCodeCausesNoCloseGuardWarning() throws IOException {
8258155888a2c4e7cc28596deec28433e1984cfaf11Brian Carlstrom        CloseGuardGuard guard = new CloseGuardGuard();
8268155888a2c4e7cc28596deec28433e1984cfaf11Brian Carlstrom        try {
8278155888a2c4e7cc28596deec28433e1984cfaf11Brian Carlstrom            server.enqueue(new MockResponse()
8288155888a2c4e7cc28596deec28433e1984cfaf11Brian Carlstrom                           .setBody(gzip("ABCABCABC".getBytes("UTF-8")))
8298155888a2c4e7cc28596deec28433e1984cfaf11Brian Carlstrom                           .addHeader("Content-Encoding: gzip"));
8308155888a2c4e7cc28596deec28433e1984cfaf11Brian Carlstrom            server.play();
8318155888a2c4e7cc28596deec28433e1984cfaf11Brian Carlstrom
8328155888a2c4e7cc28596deec28433e1984cfaf11Brian Carlstrom            HttpURLConnection connection = (HttpURLConnection) server.getUrl("/").openConnection();
8338155888a2c4e7cc28596deec28433e1984cfaf11Brian Carlstrom            assertEquals(200, connection.getResponseCode());
8348155888a2c4e7cc28596deec28433e1984cfaf11Brian Carlstrom            connection.disconnect();
8358155888a2c4e7cc28596deec28433e1984cfaf11Brian Carlstrom            connection = null;
8368155888a2c4e7cc28596deec28433e1984cfaf11Brian Carlstrom            assertFalse(guard.wasCloseGuardCalled());
8378155888a2c4e7cc28596deec28433e1984cfaf11Brian Carlstrom        } finally {
8388155888a2c4e7cc28596deec28433e1984cfaf11Brian Carlstrom            guard.close();
8398155888a2c4e7cc28596deec28433e1984cfaf11Brian Carlstrom        }
8408155888a2c4e7cc28596deec28433e1984cfaf11Brian Carlstrom    }
8418155888a2c4e7cc28596deec28433e1984cfaf11Brian Carlstrom
8428155888a2c4e7cc28596deec28433e1984cfaf11Brian Carlstrom    public static class CloseGuardGuard implements Closeable, CloseGuard.Reporter  {
8438155888a2c4e7cc28596deec28433e1984cfaf11Brian Carlstrom        private final CloseGuard.Reporter oldReporter = CloseGuard.getReporter();
8448155888a2c4e7cc28596deec28433e1984cfaf11Brian Carlstrom
8458155888a2c4e7cc28596deec28433e1984cfaf11Brian Carlstrom        private AtomicBoolean closeGuardCalled = new AtomicBoolean();
8468155888a2c4e7cc28596deec28433e1984cfaf11Brian Carlstrom
8478155888a2c4e7cc28596deec28433e1984cfaf11Brian Carlstrom        public CloseGuardGuard() {
8488155888a2c4e7cc28596deec28433e1984cfaf11Brian Carlstrom            CloseGuard.setReporter(this);
8498155888a2c4e7cc28596deec28433e1984cfaf11Brian Carlstrom        }
8508155888a2c4e7cc28596deec28433e1984cfaf11Brian Carlstrom
8518155888a2c4e7cc28596deec28433e1984cfaf11Brian Carlstrom        @Override public void report(String message, Throwable allocationSite) {
8528155888a2c4e7cc28596deec28433e1984cfaf11Brian Carlstrom            oldReporter.report(message, allocationSite);
8538155888a2c4e7cc28596deec28433e1984cfaf11Brian Carlstrom            closeGuardCalled.set(true);
8548155888a2c4e7cc28596deec28433e1984cfaf11Brian Carlstrom        }
8558155888a2c4e7cc28596deec28433e1984cfaf11Brian Carlstrom
8568155888a2c4e7cc28596deec28433e1984cfaf11Brian Carlstrom        public boolean wasCloseGuardCalled() {
8573edd28a92fc86a1260347d0995e65a815d73bbbeMattias Petersson            FinalizationTester.induceFinalization();
8588155888a2c4e7cc28596deec28433e1984cfaf11Brian Carlstrom            close();
8598155888a2c4e7cc28596deec28433e1984cfaf11Brian Carlstrom            return closeGuardCalled.get();
8608155888a2c4e7cc28596deec28433e1984cfaf11Brian Carlstrom        }
8618155888a2c4e7cc28596deec28433e1984cfaf11Brian Carlstrom
8628155888a2c4e7cc28596deec28433e1984cfaf11Brian Carlstrom        @Override public void close() {
8638155888a2c4e7cc28596deec28433e1984cfaf11Brian Carlstrom            CloseGuard.setReporter(oldReporter);
8648155888a2c4e7cc28596deec28433e1984cfaf11Brian Carlstrom        }
8658155888a2c4e7cc28596deec28433e1984cfaf11Brian Carlstrom
8668155888a2c4e7cc28596deec28433e1984cfaf11Brian Carlstrom    }
8678155888a2c4e7cc28596deec28433e1984cfaf11Brian Carlstrom
868d742d7fc7f0593eb8c6e4ac9dd4c0f6a80374e46Jesse Wilson    public void testDefaultRequestProperty() throws Exception {
869d742d7fc7f0593eb8c6e4ac9dd4c0f6a80374e46Jesse Wilson        URLConnection.setDefaultRequestProperty("X-testSetDefaultRequestProperty", "A");
870d742d7fc7f0593eb8c6e4ac9dd4c0f6a80374e46Jesse Wilson        assertNull(URLConnection.getDefaultRequestProperty("X-setDefaultRequestProperty"));
871d742d7fc7f0593eb8c6e4ac9dd4c0f6a80374e46Jesse Wilson    }
872d742d7fc7f0593eb8c6e4ac9dd4c0f6a80374e46Jesse Wilson
87351e468abf2628ce964d3657042f3ac8f2c947504Jesse Wilson    /**
87451e468abf2628ce964d3657042f3ac8f2c947504Jesse Wilson     * Reads {@code count} characters from the stream. If the stream is
87551e468abf2628ce964d3657042f3ac8f2c947504Jesse Wilson     * exhausted before {@code count} characters can be read, the remaining
87651e468abf2628ce964d3657042f3ac8f2c947504Jesse Wilson     * characters are returned and the stream is closed.
87751e468abf2628ce964d3657042f3ac8f2c947504Jesse Wilson     */
87851e468abf2628ce964d3657042f3ac8f2c947504Jesse Wilson    private String readAscii(InputStream in, int count) throws IOException {
87951e468abf2628ce964d3657042f3ac8f2c947504Jesse Wilson        StringBuilder result = new StringBuilder();
88051e468abf2628ce964d3657042f3ac8f2c947504Jesse Wilson        for (int i = 0; i < count; i++) {
88151e468abf2628ce964d3657042f3ac8f2c947504Jesse Wilson            int value = in.read();
88251e468abf2628ce964d3657042f3ac8f2c947504Jesse Wilson            if (value == -1) {
88351e468abf2628ce964d3657042f3ac8f2c947504Jesse Wilson                in.close();
88451e468abf2628ce964d3657042f3ac8f2c947504Jesse Wilson                break;
88551e468abf2628ce964d3657042f3ac8f2c947504Jesse Wilson            }
88651e468abf2628ce964d3657042f3ac8f2c947504Jesse Wilson            result.append((char) value);
88751e468abf2628ce964d3657042f3ac8f2c947504Jesse Wilson        }
88851e468abf2628ce964d3657042f3ac8f2c947504Jesse Wilson        return result.toString();
88951e468abf2628ce964d3657042f3ac8f2c947504Jesse Wilson    }
89051e468abf2628ce964d3657042f3ac8f2c947504Jesse Wilson
89151e468abf2628ce964d3657042f3ac8f2c947504Jesse Wilson    public void testMarkAndResetWithContentLengthHeader() throws IOException {
89251e468abf2628ce964d3657042f3ac8f2c947504Jesse Wilson        testMarkAndReset(TransferKind.FIXED_LENGTH);
89351e468abf2628ce964d3657042f3ac8f2c947504Jesse Wilson    }
89451e468abf2628ce964d3657042f3ac8f2c947504Jesse Wilson
89551e468abf2628ce964d3657042f3ac8f2c947504Jesse Wilson    public void testMarkAndResetWithChunkedEncoding() throws IOException {
89651e468abf2628ce964d3657042f3ac8f2c947504Jesse Wilson        testMarkAndReset(TransferKind.CHUNKED);
89751e468abf2628ce964d3657042f3ac8f2c947504Jesse Wilson    }
89851e468abf2628ce964d3657042f3ac8f2c947504Jesse Wilson
89951e468abf2628ce964d3657042f3ac8f2c947504Jesse Wilson    public void testMarkAndResetWithNoLengthHeaders() throws IOException {
90051e468abf2628ce964d3657042f3ac8f2c947504Jesse Wilson        testMarkAndReset(TransferKind.END_OF_STREAM);
90151e468abf2628ce964d3657042f3ac8f2c947504Jesse Wilson    }
90251e468abf2628ce964d3657042f3ac8f2c947504Jesse Wilson
9030c2fd828abec671333b8b88281825fd27a783723Jesse Wilson    private void testMarkAndReset(TransferKind transferKind) throws IOException {
90451e468abf2628ce964d3657042f3ac8f2c947504Jesse Wilson        MockResponse response = new MockResponse();
90551e468abf2628ce964d3657042f3ac8f2c947504Jesse Wilson        transferKind.setBody(response, "ABCDEFGHIJKLMNOPQRSTUVWXYZ", 1024);
90651e468abf2628ce964d3657042f3ac8f2c947504Jesse Wilson        server.enqueue(response);
907953df613522e12a418cb7cb73248594d6c9f53d4Jesse Wilson        server.enqueue(response);
90851e468abf2628ce964d3657042f3ac8f2c947504Jesse Wilson        server.play();
90951e468abf2628ce964d3657042f3ac8f2c947504Jesse Wilson
91051e468abf2628ce964d3657042f3ac8f2c947504Jesse Wilson        InputStream in = server.getUrl("/").openConnection().getInputStream();
91151e468abf2628ce964d3657042f3ac8f2c947504Jesse Wilson        assertFalse("This implementation claims to support mark().", in.markSupported());
91251e468abf2628ce964d3657042f3ac8f2c947504Jesse Wilson        in.mark(5);
91351e468abf2628ce964d3657042f3ac8f2c947504Jesse Wilson        assertEquals("ABCDE", readAscii(in, 5));
91451e468abf2628ce964d3657042f3ac8f2c947504Jesse Wilson        try {
91551e468abf2628ce964d3657042f3ac8f2c947504Jesse Wilson            in.reset();
91651e468abf2628ce964d3657042f3ac8f2c947504Jesse Wilson            fail();
91751e468abf2628ce964d3657042f3ac8f2c947504Jesse Wilson        } catch (IOException expected) {
91851e468abf2628ce964d3657042f3ac8f2c947504Jesse Wilson        }
91951e468abf2628ce964d3657042f3ac8f2c947504Jesse Wilson        assertEquals("FGHIJKLMNOPQRSTUVWXYZ", readAscii(in, Integer.MAX_VALUE));
92051e468abf2628ce964d3657042f3ac8f2c947504Jesse Wilson        assertContent("ABCDEFGHIJKLMNOPQRSTUVWXYZ", server.getUrl("/").openConnection());
92151e468abf2628ce964d3657042f3ac8f2c947504Jesse Wilson    }
92251e468abf2628ce964d3657042f3ac8f2c947504Jesse Wilson
92351e468abf2628ce964d3657042f3ac8f2c947504Jesse Wilson    /**
92451e468abf2628ce964d3657042f3ac8f2c947504Jesse Wilson     * We've had a bug where we forget the HTTP response when we see response
92551e468abf2628ce964d3657042f3ac8f2c947504Jesse Wilson     * code 401. This causes a new HTTP request to be issued for every call into
92651e468abf2628ce964d3657042f3ac8f2c947504Jesse Wilson     * the URLConnection.
92751e468abf2628ce964d3657042f3ac8f2c947504Jesse Wilson     */
92851e468abf2628ce964d3657042f3ac8f2c947504Jesse Wilson    public void testUnauthorizedResponseHandling() throws IOException {
92951e468abf2628ce964d3657042f3ac8f2c947504Jesse Wilson        MockResponse response = new MockResponse()
9305757cb35ad2e58d7accb7f5d3db6f2d5e72f097dJesse Wilson                .addHeader("WWW-Authenticate: Basic realm=\"protected area\"")
93151e468abf2628ce964d3657042f3ac8f2c947504Jesse Wilson                .setResponseCode(401) // UNAUTHORIZED
93251e468abf2628ce964d3657042f3ac8f2c947504Jesse Wilson                .setBody("Unauthorized");
93351e468abf2628ce964d3657042f3ac8f2c947504Jesse Wilson        server.enqueue(response);
93451e468abf2628ce964d3657042f3ac8f2c947504Jesse Wilson        server.enqueue(response);
93551e468abf2628ce964d3657042f3ac8f2c947504Jesse Wilson        server.enqueue(response);
93651e468abf2628ce964d3657042f3ac8f2c947504Jesse Wilson        server.play();
93751e468abf2628ce964d3657042f3ac8f2c947504Jesse Wilson
93851e468abf2628ce964d3657042f3ac8f2c947504Jesse Wilson        URL url = server.getUrl("/");
93951e468abf2628ce964d3657042f3ac8f2c947504Jesse Wilson        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
94051e468abf2628ce964d3657042f3ac8f2c947504Jesse Wilson
94151e468abf2628ce964d3657042f3ac8f2c947504Jesse Wilson        assertEquals(401, conn.getResponseCode());
94251e468abf2628ce964d3657042f3ac8f2c947504Jesse Wilson        assertEquals(401, conn.getResponseCode());
94351e468abf2628ce964d3657042f3ac8f2c947504Jesse Wilson        assertEquals(401, conn.getResponseCode());
94451e468abf2628ce964d3657042f3ac8f2c947504Jesse Wilson        assertEquals(1, server.getRequestCount());
94551e468abf2628ce964d3657042f3ac8f2c947504Jesse Wilson    }
94651e468abf2628ce964d3657042f3ac8f2c947504Jesse Wilson
9476906b0c12dcf3216883d0373973a252812a20d32Jesse Wilson    public void testNonHexChunkSize() throws IOException {
9486906b0c12dcf3216883d0373973a252812a20d32Jesse Wilson        server.enqueue(new MockResponse()
9496906b0c12dcf3216883d0373973a252812a20d32Jesse Wilson                .setBody("5\r\nABCDE\r\nG\r\nFGHIJKLMNOPQRSTU\r\n0\r\n\r\n")
9506906b0c12dcf3216883d0373973a252812a20d32Jesse Wilson                .clearHeaders()
9516906b0c12dcf3216883d0373973a252812a20d32Jesse Wilson                .addHeader("Transfer-encoding: chunked"));
9526906b0c12dcf3216883d0373973a252812a20d32Jesse Wilson        server.play();
9536906b0c12dcf3216883d0373973a252812a20d32Jesse Wilson
9546906b0c12dcf3216883d0373973a252812a20d32Jesse Wilson        URLConnection connection = server.getUrl("/").openConnection();
9556906b0c12dcf3216883d0373973a252812a20d32Jesse Wilson        try {
9566906b0c12dcf3216883d0373973a252812a20d32Jesse Wilson            readAscii(connection.getInputStream(), Integer.MAX_VALUE);
9576906b0c12dcf3216883d0373973a252812a20d32Jesse Wilson            fail();
9586906b0c12dcf3216883d0373973a252812a20d32Jesse Wilson        } catch (IOException e) {
9596906b0c12dcf3216883d0373973a252812a20d32Jesse Wilson        }
9606906b0c12dcf3216883d0373973a252812a20d32Jesse Wilson    }
9616906b0c12dcf3216883d0373973a252812a20d32Jesse Wilson
9626906b0c12dcf3216883d0373973a252812a20d32Jesse Wilson    public void testMissingChunkBody() throws IOException {
9636906b0c12dcf3216883d0373973a252812a20d32Jesse Wilson        server.enqueue(new MockResponse()
9646906b0c12dcf3216883d0373973a252812a20d32Jesse Wilson                .setBody("5")
9656906b0c12dcf3216883d0373973a252812a20d32Jesse Wilson                .clearHeaders()
9666906b0c12dcf3216883d0373973a252812a20d32Jesse Wilson                .addHeader("Transfer-encoding: chunked")
967e942f46f10bb9384a1b186b3d7b74f9704c57090Jesse Wilson                .setSocketPolicy(DISCONNECT_AT_END));
9686906b0c12dcf3216883d0373973a252812a20d32Jesse Wilson        server.play();
9696906b0c12dcf3216883d0373973a252812a20d32Jesse Wilson
9706906b0c12dcf3216883d0373973a252812a20d32Jesse Wilson        URLConnection connection = server.getUrl("/").openConnection();
9716906b0c12dcf3216883d0373973a252812a20d32Jesse Wilson        try {
9726906b0c12dcf3216883d0373973a252812a20d32Jesse Wilson            readAscii(connection.getInputStream(), Integer.MAX_VALUE);
9736906b0c12dcf3216883d0373973a252812a20d32Jesse Wilson            fail();
9746906b0c12dcf3216883d0373973a252812a20d32Jesse Wilson        } catch (IOException e) {
9756906b0c12dcf3216883d0373973a252812a20d32Jesse Wilson        }
9766906b0c12dcf3216883d0373973a252812a20d32Jesse Wilson    }
9776906b0c12dcf3216883d0373973a252812a20d32Jesse Wilson
97850ae32218918eae80298bd1ab8e4f588bbbabdb2Jesse Wilson    /**
97950ae32218918eae80298bd1ab8e4f588bbbabdb2Jesse Wilson     * This test checks whether connections are gzipped by default. This
98050ae32218918eae80298bd1ab8e4f588bbbabdb2Jesse Wilson     * behavior in not required by the API, so a failure of this test does not
98150ae32218918eae80298bd1ab8e4f588bbbabdb2Jesse Wilson     * imply a bug in the implementation.
98250ae32218918eae80298bd1ab8e4f588bbbabdb2Jesse Wilson     */
98350ae32218918eae80298bd1ab8e4f588bbbabdb2Jesse Wilson    public void testGzipEncodingEnabledByDefault() throws IOException, InterruptedException {
98450ae32218918eae80298bd1ab8e4f588bbbabdb2Jesse Wilson        server.enqueue(new MockResponse()
98550ae32218918eae80298bd1ab8e4f588bbbabdb2Jesse Wilson                .setBody(gzip("ABCABCABC".getBytes("UTF-8")))
98650ae32218918eae80298bd1ab8e4f588bbbabdb2Jesse Wilson                .addHeader("Content-Encoding: gzip"));
98750ae32218918eae80298bd1ab8e4f588bbbabdb2Jesse Wilson        server.play();
98850ae32218918eae80298bd1ab8e4f588bbbabdb2Jesse Wilson
98950ae32218918eae80298bd1ab8e4f588bbbabdb2Jesse Wilson        URLConnection connection = server.getUrl("/").openConnection();
99050ae32218918eae80298bd1ab8e4f588bbbabdb2Jesse Wilson        assertEquals("ABCABCABC", readAscii(connection.getInputStream(), Integer.MAX_VALUE));
9918116f7e97e00d223e7fbe5c950c9a5e3277de124Jesse Wilson        assertNull(connection.getContentEncoding());
9926d41a7cc3cb4cc684c8bece69ddc55954812ad6eNarayan Kamath        assertEquals(-1, connection.getContentLength());
99350ae32218918eae80298bd1ab8e4f588bbbabdb2Jesse Wilson
99450ae32218918eae80298bd1ab8e4f588bbbabdb2Jesse Wilson        RecordedRequest request = server.takeRequest();
99550ae32218918eae80298bd1ab8e4f588bbbabdb2Jesse Wilson        assertContains(request.getHeaders(), "Accept-Encoding: gzip");
99650ae32218918eae80298bd1ab8e4f588bbbabdb2Jesse Wilson    }
99750ae32218918eae80298bd1ab8e4f588bbbabdb2Jesse Wilson
998deb236fb06f2a14861e7d40dea959f181cd5cf28Jesse Wilson    public void testClientConfiguredGzipContentEncoding() throws Exception {
9996d41a7cc3cb4cc684c8bece69ddc55954812ad6eNarayan Kamath        byte[] bodyBytes = gzip("ABCDEFGHIJKLMNOPQRSTUVWXYZ".getBytes("UTF-8"));
1000deb236fb06f2a14861e7d40dea959f181cd5cf28Jesse Wilson        server.enqueue(new MockResponse()
10016d41a7cc3cb4cc684c8bece69ddc55954812ad6eNarayan Kamath                .setBody(bodyBytes)
10026d41a7cc3cb4cc684c8bece69ddc55954812ad6eNarayan Kamath                .addHeader("Content-Encoding: gzip")
10036d41a7cc3cb4cc684c8bece69ddc55954812ad6eNarayan Kamath                .addHeader("Content-Length: " + bodyBytes.length));
1004deb236fb06f2a14861e7d40dea959f181cd5cf28Jesse Wilson        server.play();
1005deb236fb06f2a14861e7d40dea959f181cd5cf28Jesse Wilson
1006deb236fb06f2a14861e7d40dea959f181cd5cf28Jesse Wilson        URLConnection connection = server.getUrl("/").openConnection();
1007deb236fb06f2a14861e7d40dea959f181cd5cf28Jesse Wilson        connection.addRequestProperty("Accept-Encoding", "gzip");
1008deb236fb06f2a14861e7d40dea959f181cd5cf28Jesse Wilson        InputStream gunzippedIn = new GZIPInputStream(connection.getInputStream());
1009deb236fb06f2a14861e7d40dea959f181cd5cf28Jesse Wilson        assertEquals("ABCDEFGHIJKLMNOPQRSTUVWXYZ", readAscii(gunzippedIn, Integer.MAX_VALUE));
10106d41a7cc3cb4cc684c8bece69ddc55954812ad6eNarayan Kamath        assertEquals(bodyBytes.length, connection.getContentLength());
1011deb236fb06f2a14861e7d40dea959f181cd5cf28Jesse Wilson
1012deb236fb06f2a14861e7d40dea959f181cd5cf28Jesse Wilson        RecordedRequest request = server.takeRequest();
1013deb236fb06f2a14861e7d40dea959f181cd5cf28Jesse Wilson        assertContains(request.getHeaders(), "Accept-Encoding: gzip");
1014deb236fb06f2a14861e7d40dea959f181cd5cf28Jesse Wilson    }
1015deb236fb06f2a14861e7d40dea959f181cd5cf28Jesse Wilson
1016deb236fb06f2a14861e7d40dea959f181cd5cf28Jesse Wilson    public void testGzipAndConnectionReuseWithFixedLength() throws Exception {
1017deb236fb06f2a14861e7d40dea959f181cd5cf28Jesse Wilson        testClientConfiguredGzipContentEncodingAndConnectionReuse(TransferKind.FIXED_LENGTH);
1018deb236fb06f2a14861e7d40dea959f181cd5cf28Jesse Wilson    }
1019deb236fb06f2a14861e7d40dea959f181cd5cf28Jesse Wilson
1020deb236fb06f2a14861e7d40dea959f181cd5cf28Jesse Wilson    public void testGzipAndConnectionReuseWithChunkedEncoding() throws Exception {
1021deb236fb06f2a14861e7d40dea959f181cd5cf28Jesse Wilson        testClientConfiguredGzipContentEncodingAndConnectionReuse(TransferKind.CHUNKED);
1022deb236fb06f2a14861e7d40dea959f181cd5cf28Jesse Wilson    }
1023deb236fb06f2a14861e7d40dea959f181cd5cf28Jesse Wilson
102450ae32218918eae80298bd1ab8e4f588bbbabdb2Jesse Wilson    public void testClientConfiguredCustomContentEncoding() throws Exception {
102550ae32218918eae80298bd1ab8e4f588bbbabdb2Jesse Wilson        server.enqueue(new MockResponse()
102650ae32218918eae80298bd1ab8e4f588bbbabdb2Jesse Wilson                .setBody("ABCDE")
102750ae32218918eae80298bd1ab8e4f588bbbabdb2Jesse Wilson                .addHeader("Content-Encoding: custom"));
102850ae32218918eae80298bd1ab8e4f588bbbabdb2Jesse Wilson        server.play();
102950ae32218918eae80298bd1ab8e4f588bbbabdb2Jesse Wilson
103050ae32218918eae80298bd1ab8e4f588bbbabdb2Jesse Wilson        URLConnection connection = server.getUrl("/").openConnection();
103150ae32218918eae80298bd1ab8e4f588bbbabdb2Jesse Wilson        connection.addRequestProperty("Accept-Encoding", "custom");
103250ae32218918eae80298bd1ab8e4f588bbbabdb2Jesse Wilson        assertEquals("ABCDE", readAscii(connection.getInputStream(), Integer.MAX_VALUE));
103350ae32218918eae80298bd1ab8e4f588bbbabdb2Jesse Wilson
103450ae32218918eae80298bd1ab8e4f588bbbabdb2Jesse Wilson        RecordedRequest request = server.takeRequest();
103550ae32218918eae80298bd1ab8e4f588bbbabdb2Jesse Wilson        assertContains(request.getHeaders(), "Accept-Encoding: custom");
103650ae32218918eae80298bd1ab8e4f588bbbabdb2Jesse Wilson    }
103750ae32218918eae80298bd1ab8e4f588bbbabdb2Jesse Wilson
1038deb236fb06f2a14861e7d40dea959f181cd5cf28Jesse Wilson    /**
1039deb236fb06f2a14861e7d40dea959f181cd5cf28Jesse Wilson     * Test a bug where gzip input streams weren't exhausting the input stream,
1040deb236fb06f2a14861e7d40dea959f181cd5cf28Jesse Wilson     * which corrupted the request that followed.
1041deb236fb06f2a14861e7d40dea959f181cd5cf28Jesse Wilson     * http://code.google.com/p/android/issues/detail?id=7059
1042deb236fb06f2a14861e7d40dea959f181cd5cf28Jesse Wilson     */
1043deb236fb06f2a14861e7d40dea959f181cd5cf28Jesse Wilson    private void testClientConfiguredGzipContentEncodingAndConnectionReuse(
1044deb236fb06f2a14861e7d40dea959f181cd5cf28Jesse Wilson            TransferKind transferKind) throws Exception {
1045deb236fb06f2a14861e7d40dea959f181cd5cf28Jesse Wilson        MockResponse responseOne = new MockResponse();
1046deb236fb06f2a14861e7d40dea959f181cd5cf28Jesse Wilson        responseOne.addHeader("Content-Encoding: gzip");
1047deb236fb06f2a14861e7d40dea959f181cd5cf28Jesse Wilson        transferKind.setBody(responseOne, gzip("one (gzipped)".getBytes("UTF-8")), 5);
1048deb236fb06f2a14861e7d40dea959f181cd5cf28Jesse Wilson        server.enqueue(responseOne);
1049deb236fb06f2a14861e7d40dea959f181cd5cf28Jesse Wilson        MockResponse responseTwo = new MockResponse();
1050deb236fb06f2a14861e7d40dea959f181cd5cf28Jesse Wilson        transferKind.setBody(responseTwo, "two (identity)", 5);
1051deb236fb06f2a14861e7d40dea959f181cd5cf28Jesse Wilson        server.enqueue(responseTwo);
1052deb236fb06f2a14861e7d40dea959f181cd5cf28Jesse Wilson        server.play();
1053deb236fb06f2a14861e7d40dea959f181cd5cf28Jesse Wilson
1054deb236fb06f2a14861e7d40dea959f181cd5cf28Jesse Wilson        URLConnection connection = server.getUrl("/").openConnection();
1055deb236fb06f2a14861e7d40dea959f181cd5cf28Jesse Wilson        connection.addRequestProperty("Accept-Encoding", "gzip");
1056deb236fb06f2a14861e7d40dea959f181cd5cf28Jesse Wilson        InputStream gunzippedIn = new GZIPInputStream(connection.getInputStream());
1057deb236fb06f2a14861e7d40dea959f181cd5cf28Jesse Wilson        assertEquals("one (gzipped)", readAscii(gunzippedIn, Integer.MAX_VALUE));
1058deb236fb06f2a14861e7d40dea959f181cd5cf28Jesse Wilson        assertEquals(0, server.takeRequest().getSequenceNumber());
1059deb236fb06f2a14861e7d40dea959f181cd5cf28Jesse Wilson
1060deb236fb06f2a14861e7d40dea959f181cd5cf28Jesse Wilson        connection = server.getUrl("/").openConnection();
1061deb236fb06f2a14861e7d40dea959f181cd5cf28Jesse Wilson        assertEquals("two (identity)", readAscii(connection.getInputStream(), Integer.MAX_VALUE));
1062deb236fb06f2a14861e7d40dea959f181cd5cf28Jesse Wilson        assertEquals(1, server.takeRequest().getSequenceNumber());
1063deb236fb06f2a14861e7d40dea959f181cd5cf28Jesse Wilson    }
1064deb236fb06f2a14861e7d40dea959f181cd5cf28Jesse Wilson
1065deb236fb06f2a14861e7d40dea959f181cd5cf28Jesse Wilson    /**
1066df29c7dc69965462cd19de8910b04c8cb463e57fJesse Wilson     * Test that HEAD requests don't have a body regardless of the response
1067df29c7dc69965462cd19de8910b04c8cb463e57fJesse Wilson     * headers. http://code.google.com/p/android/issues/detail?id=24672
1068df29c7dc69965462cd19de8910b04c8cb463e57fJesse Wilson     */
1069df29c7dc69965462cd19de8910b04c8cb463e57fJesse Wilson    public void testHeadAndContentLength() throws Exception {
1070df29c7dc69965462cd19de8910b04c8cb463e57fJesse Wilson        server.enqueue(new MockResponse()
1071df29c7dc69965462cd19de8910b04c8cb463e57fJesse Wilson                .clearHeaders()
1072df29c7dc69965462cd19de8910b04c8cb463e57fJesse Wilson                .addHeader("Content-Length: 100"));
1073df29c7dc69965462cd19de8910b04c8cb463e57fJesse Wilson        server.enqueue(new MockResponse().setBody("A"));
1074df29c7dc69965462cd19de8910b04c8cb463e57fJesse Wilson        server.play();
1075df29c7dc69965462cd19de8910b04c8cb463e57fJesse Wilson
1076df29c7dc69965462cd19de8910b04c8cb463e57fJesse Wilson        HttpURLConnection connection1 = (HttpURLConnection) server.getUrl("/").openConnection();
1077df29c7dc69965462cd19de8910b04c8cb463e57fJesse Wilson        connection1.setRequestMethod("HEAD");
1078df29c7dc69965462cd19de8910b04c8cb463e57fJesse Wilson        assertEquals("100", connection1.getHeaderField("Content-Length"));
1079df29c7dc69965462cd19de8910b04c8cb463e57fJesse Wilson        assertContent("", connection1);
1080df29c7dc69965462cd19de8910b04c8cb463e57fJesse Wilson
1081df29c7dc69965462cd19de8910b04c8cb463e57fJesse Wilson        HttpURLConnection connection2 = (HttpURLConnection) server.getUrl("/").openConnection();
1082df29c7dc69965462cd19de8910b04c8cb463e57fJesse Wilson        assertEquals("A", readAscii(connection2.getInputStream(), Integer.MAX_VALUE));
1083df29c7dc69965462cd19de8910b04c8cb463e57fJesse Wilson
1084df29c7dc69965462cd19de8910b04c8cb463e57fJesse Wilson        assertEquals(0, server.takeRequest().getSequenceNumber());
1085df29c7dc69965462cd19de8910b04c8cb463e57fJesse Wilson        assertEquals(1, server.takeRequest().getSequenceNumber());
1086df29c7dc69965462cd19de8910b04c8cb463e57fJesse Wilson    }
1087df29c7dc69965462cd19de8910b04c8cb463e57fJesse Wilson
1088df29c7dc69965462cd19de8910b04c8cb463e57fJesse Wilson    /**
1089ffd579b668428272b78f5c6c64f9c89766f37c1aJesse Wilson     * Obnoxiously test that the chunk sizes transmitted exactly equal the
1090ffd579b668428272b78f5c6c64f9c89766f37c1aJesse Wilson     * requested data+chunk header size. Although setChunkedStreamingMode()
1091ffd579b668428272b78f5c6c64f9c89766f37c1aJesse Wilson     * isn't specific about whether the size applies to the data or the
1092ffd579b668428272b78f5c6c64f9c89766f37c1aJesse Wilson     * complete chunk, the RI interprets it as a complete chunk.
1093ffd579b668428272b78f5c6c64f9c89766f37c1aJesse Wilson     */
1094ffd579b668428272b78f5c6c64f9c89766f37c1aJesse Wilson    public void testSetChunkedStreamingMode() throws IOException, InterruptedException {
1095ffd579b668428272b78f5c6c64f9c89766f37c1aJesse Wilson        server.enqueue(new MockResponse());
1096ffd579b668428272b78f5c6c64f9c89766f37c1aJesse Wilson        server.play();
1097ffd579b668428272b78f5c6c64f9c89766f37c1aJesse Wilson
1098ffd579b668428272b78f5c6c64f9c89766f37c1aJesse Wilson        HttpURLConnection urlConnection = (HttpURLConnection) server.getUrl("/").openConnection();
1099ffd579b668428272b78f5c6c64f9c89766f37c1aJesse Wilson        urlConnection.setChunkedStreamingMode(8);
1100ffd579b668428272b78f5c6c64f9c89766f37c1aJesse Wilson        urlConnection.setDoOutput(true);
1101ffd579b668428272b78f5c6c64f9c89766f37c1aJesse Wilson        OutputStream outputStream = urlConnection.getOutputStream();
1102ffd579b668428272b78f5c6c64f9c89766f37c1aJesse Wilson        outputStream.write("ABCDEFGHIJKLMNOPQ".getBytes("US-ASCII"));
1103ffd579b668428272b78f5c6c64f9c89766f37c1aJesse Wilson        assertEquals(200, urlConnection.getResponseCode());
1104ffd579b668428272b78f5c6c64f9c89766f37c1aJesse Wilson
1105ffd579b668428272b78f5c6c64f9c89766f37c1aJesse Wilson        RecordedRequest request = server.takeRequest();
1106ffd579b668428272b78f5c6c64f9c89766f37c1aJesse Wilson        assertEquals("ABCDEFGHIJKLMNOPQ", new String(request.getBody(), "US-ASCII"));
1107ffd579b668428272b78f5c6c64f9c89766f37c1aJesse Wilson        assertEquals(Arrays.asList(3, 3, 3, 3, 3, 2), request.getChunkSizes());
1108ffd579b668428272b78f5c6c64f9c89766f37c1aJesse Wilson    }
1109ffd579b668428272b78f5c6c64f9c89766f37c1aJesse Wilson
1110ffd579b668428272b78f5c6c64f9c89766f37c1aJesse Wilson    public void testAuthenticateWithFixedLengthStreaming() throws Exception {
1111ffd579b668428272b78f5c6c64f9c89766f37c1aJesse Wilson        testAuthenticateWithStreamingPost(StreamingMode.FIXED_LENGTH);
1112ffd579b668428272b78f5c6c64f9c89766f37c1aJesse Wilson    }
1113ffd579b668428272b78f5c6c64f9c89766f37c1aJesse Wilson
1114ffd579b668428272b78f5c6c64f9c89766f37c1aJesse Wilson    public void testAuthenticateWithChunkedStreaming() throws Exception {
1115ffd579b668428272b78f5c6c64f9c89766f37c1aJesse Wilson        testAuthenticateWithStreamingPost(StreamingMode.CHUNKED);
1116ffd579b668428272b78f5c6c64f9c89766f37c1aJesse Wilson    }
1117ffd579b668428272b78f5c6c64f9c89766f37c1aJesse Wilson
1118ffd579b668428272b78f5c6c64f9c89766f37c1aJesse Wilson    private void testAuthenticateWithStreamingPost(StreamingMode streamingMode) throws Exception {
1119ffd579b668428272b78f5c6c64f9c89766f37c1aJesse Wilson        MockResponse pleaseAuthenticate = new MockResponse()
1120ffd579b668428272b78f5c6c64f9c89766f37c1aJesse Wilson                .setResponseCode(401)
1121ffd579b668428272b78f5c6c64f9c89766f37c1aJesse Wilson                .addHeader("WWW-Authenticate: Basic realm=\"protected area\"")
1122ffd579b668428272b78f5c6c64f9c89766f37c1aJesse Wilson                .setBody("Please authenticate.");
1123ffd579b668428272b78f5c6c64f9c89766f37c1aJesse Wilson        server.enqueue(pleaseAuthenticate);
1124ffd579b668428272b78f5c6c64f9c89766f37c1aJesse Wilson        server.play();
1125ffd579b668428272b78f5c6c64f9c89766f37c1aJesse Wilson
11265757cb35ad2e58d7accb7f5d3db6f2d5e72f097dJesse Wilson        Authenticator.setDefault(new SimpleAuthenticator());
1127ffd579b668428272b78f5c6c64f9c89766f37c1aJesse Wilson        HttpURLConnection connection = (HttpURLConnection) server.getUrl("/").openConnection();
1128ffd579b668428272b78f5c6c64f9c89766f37c1aJesse Wilson        connection.setDoOutput(true);
1129ffd579b668428272b78f5c6c64f9c89766f37c1aJesse Wilson        byte[] requestBody = { 'A', 'B', 'C', 'D' };
1130ffd579b668428272b78f5c6c64f9c89766f37c1aJesse Wilson        if (streamingMode == StreamingMode.FIXED_LENGTH) {
1131ffd579b668428272b78f5c6c64f9c89766f37c1aJesse Wilson            connection.setFixedLengthStreamingMode(requestBody.length);
1132ffd579b668428272b78f5c6c64f9c89766f37c1aJesse Wilson        } else if (streamingMode == StreamingMode.CHUNKED) {
1133ffd579b668428272b78f5c6c64f9c89766f37c1aJesse Wilson            connection.setChunkedStreamingMode(0);
1134ffd579b668428272b78f5c6c64f9c89766f37c1aJesse Wilson        }
1135ffd579b668428272b78f5c6c64f9c89766f37c1aJesse Wilson        OutputStream outputStream = connection.getOutputStream();
1136ffd579b668428272b78f5c6c64f9c89766f37c1aJesse Wilson        outputStream.write(requestBody);
1137ffd579b668428272b78f5c6c64f9c89766f37c1aJesse Wilson        outputStream.close();
1138ffd579b668428272b78f5c6c64f9c89766f37c1aJesse Wilson        try {
1139ffd579b668428272b78f5c6c64f9c89766f37c1aJesse Wilson            connection.getInputStream();
1140ffd579b668428272b78f5c6c64f9c89766f37c1aJesse Wilson            fail();
1141ffd579b668428272b78f5c6c64f9c89766f37c1aJesse Wilson        } catch (HttpRetryException expected) {
1142ffd579b668428272b78f5c6c64f9c89766f37c1aJesse Wilson        }
1143ffd579b668428272b78f5c6c64f9c89766f37c1aJesse Wilson
1144ffd579b668428272b78f5c6c64f9c89766f37c1aJesse Wilson        // no authorization header for the request...
1145ffd579b668428272b78f5c6c64f9c89766f37c1aJesse Wilson        RecordedRequest request = server.takeRequest();
1146ffd579b668428272b78f5c6c64f9c89766f37c1aJesse Wilson        assertContainsNoneMatching(request.getHeaders(), "Authorization: Basic .*");
1147ffd579b668428272b78f5c6c64f9c89766f37c1aJesse Wilson        assertEquals(Arrays.toString(requestBody), Arrays.toString(request.getBody()));
1148ffd579b668428272b78f5c6c64f9c89766f37c1aJesse Wilson    }
1149ffd579b668428272b78f5c6c64f9c89766f37c1aJesse Wilson
1150ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson    public void testSetValidRequestMethod() throws Exception {
1151ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson        server.play();
1152ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson        assertValidRequestMethod("GET");
1153ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson        assertValidRequestMethod("DELETE");
1154ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson        assertValidRequestMethod("HEAD");
1155ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson        assertValidRequestMethod("OPTIONS");
1156ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson        assertValidRequestMethod("POST");
1157ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson        assertValidRequestMethod("PUT");
1158ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson        assertValidRequestMethod("TRACE");
1159ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson    }
1160ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson
1161ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson    private void assertValidRequestMethod(String requestMethod) throws Exception {
1162ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson        HttpURLConnection connection = (HttpURLConnection) server.getUrl("/").openConnection();
1163ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson        connection.setRequestMethod(requestMethod);
1164ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson        assertEquals(requestMethod, connection.getRequestMethod());
1165ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson    }
1166ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson
1167ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson    public void testSetInvalidRequestMethodLowercase() throws Exception {
1168ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson        server.play();
1169ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson        assertInvalidRequestMethod("get");
1170ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson    }
1171ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson
1172ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson    public void testSetInvalidRequestMethodConnect() throws Exception {
1173ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson        server.play();
1174ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson        assertInvalidRequestMethod("CONNECT");
1175ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson    }
1176ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson
1177ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson    private void assertInvalidRequestMethod(String requestMethod) throws Exception {
1178ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson        HttpURLConnection connection = (HttpURLConnection) server.getUrl("/").openConnection();
1179ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson        try {
1180ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson            connection.setRequestMethod(requestMethod);
1181ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson            fail();
1182ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson        } catch (ProtocolException expected) {
1183ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson        }
1184ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson    }
1185ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson
1186ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson    public void testCannotSetNegativeFixedLengthStreamingMode() throws Exception {
1187ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson        server.play();
1188ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson        HttpURLConnection connection = (HttpURLConnection) server.getUrl("/").openConnection();
1189ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson        try {
1190ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson            connection.setFixedLengthStreamingMode(-2);
1191ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson            fail();
1192ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson        } catch (IllegalArgumentException expected) {
1193ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson        }
1194ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson    }
1195ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson
1196ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson    public void testCanSetNegativeChunkedStreamingMode() throws Exception {
1197ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson        server.play();
1198ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson        HttpURLConnection connection = (HttpURLConnection) server.getUrl("/").openConnection();
1199ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson        connection.setChunkedStreamingMode(-2);
1200ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson    }
1201ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson
1202ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson    public void testCannotSetFixedLengthStreamingModeAfterConnect() throws Exception {
1203ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson        server.enqueue(new MockResponse().setBody("A"));
1204ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson        server.play();
1205ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson        HttpURLConnection connection = (HttpURLConnection) server.getUrl("/").openConnection();
1206ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson        assertEquals("A", readAscii(connection.getInputStream(), Integer.MAX_VALUE));
1207ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson        try {
1208ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson            connection.setFixedLengthStreamingMode(1);
1209ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson            fail();
1210ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson        } catch (IllegalStateException expected) {
1211ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson        }
1212ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson    }
1213ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson
1214ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson    public void testCannotSetChunkedStreamingModeAfterConnect() throws Exception {
1215ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson        server.enqueue(new MockResponse().setBody("A"));
1216ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson        server.play();
1217ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson        HttpURLConnection connection = (HttpURLConnection) server.getUrl("/").openConnection();
1218ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson        assertEquals("A", readAscii(connection.getInputStream(), Integer.MAX_VALUE));
1219ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson        try {
1220ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson            connection.setChunkedStreamingMode(1);
1221ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson            fail();
1222ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson        } catch (IllegalStateException expected) {
1223ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson        }
1224ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson    }
1225ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson
1226ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson    public void testCannotSetFixedLengthStreamingModeAfterChunkedStreamingMode() throws Exception {
1227ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson        server.play();
1228ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson        HttpURLConnection connection = (HttpURLConnection) server.getUrl("/").openConnection();
1229ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson        connection.setChunkedStreamingMode(1);
1230ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson        try {
1231ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson            connection.setFixedLengthStreamingMode(1);
1232ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson            fail();
1233ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson        } catch (IllegalStateException expected) {
1234ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson        }
1235ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson    }
1236ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson
1237ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson    public void testCannotSetChunkedStreamingModeAfterFixedLengthStreamingMode() throws Exception {
1238ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson        server.play();
1239ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson        HttpURLConnection connection = (HttpURLConnection) server.getUrl("/").openConnection();
1240ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson        connection.setFixedLengthStreamingMode(1);
1241ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson        try {
1242ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson            connection.setChunkedStreamingMode(1);
1243ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson            fail();
1244ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson        } catch (IllegalStateException expected) {
1245ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson        }
1246ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson    }
1247ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson
124835eef71e8ce721c4199c525890ecc1a263054596Jesse Wilson    public void testSecureFixedLengthStreaming() throws Exception {
124935eef71e8ce721c4199c525890ecc1a263054596Jesse Wilson        testSecureStreamingPost(StreamingMode.FIXED_LENGTH);
125035eef71e8ce721c4199c525890ecc1a263054596Jesse Wilson    }
125135eef71e8ce721c4199c525890ecc1a263054596Jesse Wilson
125235eef71e8ce721c4199c525890ecc1a263054596Jesse Wilson    public void testSecureChunkedStreaming() throws Exception {
125335eef71e8ce721c4199c525890ecc1a263054596Jesse Wilson        testSecureStreamingPost(StreamingMode.CHUNKED);
125435eef71e8ce721c4199c525890ecc1a263054596Jesse Wilson    }
125535eef71e8ce721c4199c525890ecc1a263054596Jesse Wilson
125635eef71e8ce721c4199c525890ecc1a263054596Jesse Wilson    /**
125735eef71e8ce721c4199c525890ecc1a263054596Jesse Wilson     * Users have reported problems using HTTPS with streaming request bodies.
125835eef71e8ce721c4199c525890ecc1a263054596Jesse Wilson     * http://code.google.com/p/android/issues/detail?id=12860
125935eef71e8ce721c4199c525890ecc1a263054596Jesse Wilson     */
126035eef71e8ce721c4199c525890ecc1a263054596Jesse Wilson    private void testSecureStreamingPost(StreamingMode streamingMode) throws Exception {
126135eef71e8ce721c4199c525890ecc1a263054596Jesse Wilson        TestSSLContext testSSLContext = TestSSLContext.create();
126235eef71e8ce721c4199c525890ecc1a263054596Jesse Wilson        server.useHttps(testSSLContext.serverContext.getSocketFactory(), false);
126335eef71e8ce721c4199c525890ecc1a263054596Jesse Wilson        server.enqueue(new MockResponse().setBody("Success!"));
126435eef71e8ce721c4199c525890ecc1a263054596Jesse Wilson        server.play();
126535eef71e8ce721c4199c525890ecc1a263054596Jesse Wilson
126635eef71e8ce721c4199c525890ecc1a263054596Jesse Wilson        HttpsURLConnection connection = (HttpsURLConnection) server.getUrl("/").openConnection();
126735eef71e8ce721c4199c525890ecc1a263054596Jesse Wilson        connection.setSSLSocketFactory(testSSLContext.clientContext.getSocketFactory());
126835eef71e8ce721c4199c525890ecc1a263054596Jesse Wilson        connection.setDoOutput(true);
126935eef71e8ce721c4199c525890ecc1a263054596Jesse Wilson        byte[] requestBody = { 'A', 'B', 'C', 'D' };
127035eef71e8ce721c4199c525890ecc1a263054596Jesse Wilson        if (streamingMode == StreamingMode.FIXED_LENGTH) {
127135eef71e8ce721c4199c525890ecc1a263054596Jesse Wilson            connection.setFixedLengthStreamingMode(requestBody.length);
127235eef71e8ce721c4199c525890ecc1a263054596Jesse Wilson        } else if (streamingMode == StreamingMode.CHUNKED) {
127335eef71e8ce721c4199c525890ecc1a263054596Jesse Wilson            connection.setChunkedStreamingMode(0);
127435eef71e8ce721c4199c525890ecc1a263054596Jesse Wilson        }
127535eef71e8ce721c4199c525890ecc1a263054596Jesse Wilson        OutputStream outputStream = connection.getOutputStream();
127635eef71e8ce721c4199c525890ecc1a263054596Jesse Wilson        outputStream.write(requestBody);
127735eef71e8ce721c4199c525890ecc1a263054596Jesse Wilson        outputStream.close();
127835eef71e8ce721c4199c525890ecc1a263054596Jesse Wilson        assertEquals("Success!", readAscii(connection.getInputStream(), Integer.MAX_VALUE));
127935eef71e8ce721c4199c525890ecc1a263054596Jesse Wilson
128035eef71e8ce721c4199c525890ecc1a263054596Jesse Wilson        RecordedRequest request = server.takeRequest();
128135eef71e8ce721c4199c525890ecc1a263054596Jesse Wilson        assertEquals("POST / HTTP/1.1", request.getRequestLine());
128235eef71e8ce721c4199c525890ecc1a263054596Jesse Wilson        if (streamingMode == StreamingMode.FIXED_LENGTH) {
128335eef71e8ce721c4199c525890ecc1a263054596Jesse Wilson            assertEquals(Collections.<Integer>emptyList(), request.getChunkSizes());
128435eef71e8ce721c4199c525890ecc1a263054596Jesse Wilson        } else if (streamingMode == StreamingMode.CHUNKED) {
128535eef71e8ce721c4199c525890ecc1a263054596Jesse Wilson            assertEquals(Arrays.asList(4), request.getChunkSizes());
128635eef71e8ce721c4199c525890ecc1a263054596Jesse Wilson        }
128735eef71e8ce721c4199c525890ecc1a263054596Jesse Wilson        assertEquals(Arrays.toString(requestBody), Arrays.toString(request.getBody()));
128835eef71e8ce721c4199c525890ecc1a263054596Jesse Wilson    }
128935eef71e8ce721c4199c525890ecc1a263054596Jesse Wilson
1290ffd579b668428272b78f5c6c64f9c89766f37c1aJesse Wilson    enum StreamingMode {
1291ffd579b668428272b78f5c6c64f9c89766f37c1aJesse Wilson        FIXED_LENGTH, CHUNKED
1292ffd579b668428272b78f5c6c64f9c89766f37c1aJesse Wilson    }
1293ffd579b668428272b78f5c6c64f9c89766f37c1aJesse Wilson
1294ffd579b668428272b78f5c6c64f9c89766f37c1aJesse Wilson    public void testAuthenticateWithPost() throws Exception {
1295ffd579b668428272b78f5c6c64f9c89766f37c1aJesse Wilson        MockResponse pleaseAuthenticate = new MockResponse()
1296ffd579b668428272b78f5c6c64f9c89766f37c1aJesse Wilson                .setResponseCode(401)
1297ffd579b668428272b78f5c6c64f9c89766f37c1aJesse Wilson                .addHeader("WWW-Authenticate: Basic realm=\"protected area\"")
1298ffd579b668428272b78f5c6c64f9c89766f37c1aJesse Wilson                .setBody("Please authenticate.");
1299ffd579b668428272b78f5c6c64f9c89766f37c1aJesse Wilson        // fail auth three times...
1300ffd579b668428272b78f5c6c64f9c89766f37c1aJesse Wilson        server.enqueue(pleaseAuthenticate);
1301ffd579b668428272b78f5c6c64f9c89766f37c1aJesse Wilson        server.enqueue(pleaseAuthenticate);
1302ffd579b668428272b78f5c6c64f9c89766f37c1aJesse Wilson        server.enqueue(pleaseAuthenticate);
1303ffd579b668428272b78f5c6c64f9c89766f37c1aJesse Wilson        // ...then succeed the fourth time
1304ffd579b668428272b78f5c6c64f9c89766f37c1aJesse Wilson        server.enqueue(new MockResponse().setBody("Successful auth!"));
1305ffd579b668428272b78f5c6c64f9c89766f37c1aJesse Wilson        server.play();
1306ffd579b668428272b78f5c6c64f9c89766f37c1aJesse Wilson
13075757cb35ad2e58d7accb7f5d3db6f2d5e72f097dJesse Wilson        Authenticator.setDefault(new SimpleAuthenticator());
1308ffd579b668428272b78f5c6c64f9c89766f37c1aJesse Wilson        HttpURLConnection connection = (HttpURLConnection) server.getUrl("/").openConnection();
1309ffd579b668428272b78f5c6c64f9c89766f37c1aJesse Wilson        connection.setDoOutput(true);
1310ffd579b668428272b78f5c6c64f9c89766f37c1aJesse Wilson        byte[] requestBody = { 'A', 'B', 'C', 'D' };
1311ffd579b668428272b78f5c6c64f9c89766f37c1aJesse Wilson        OutputStream outputStream = connection.getOutputStream();
1312ffd579b668428272b78f5c6c64f9c89766f37c1aJesse Wilson        outputStream.write(requestBody);
1313ffd579b668428272b78f5c6c64f9c89766f37c1aJesse Wilson        outputStream.close();
1314ffd579b668428272b78f5c6c64f9c89766f37c1aJesse Wilson        assertEquals("Successful auth!", readAscii(connection.getInputStream(), Integer.MAX_VALUE));
1315ffd579b668428272b78f5c6c64f9c89766f37c1aJesse Wilson
1316ffd579b668428272b78f5c6c64f9c89766f37c1aJesse Wilson        // no authorization header for the first request...
1317ffd579b668428272b78f5c6c64f9c89766f37c1aJesse Wilson        RecordedRequest request = server.takeRequest();
13185757cb35ad2e58d7accb7f5d3db6f2d5e72f097dJesse Wilson        assertContainsNoneMatching(request.getHeaders(), "Authorization: .*");
1319ffd579b668428272b78f5c6c64f9c89766f37c1aJesse Wilson
1320da289bcd0a9e207cc03c752f7c21c9004056e179Jesse Wilson        // ...but the three requests that follow include an authorization header
1321ffd579b668428272b78f5c6c64f9c89766f37c1aJesse Wilson        for (int i = 0; i < 3; i++) {
1322ffd579b668428272b78f5c6c64f9c89766f37c1aJesse Wilson            request = server.takeRequest();
1323ffd579b668428272b78f5c6c64f9c89766f37c1aJesse Wilson            assertEquals("POST / HTTP/1.1", request.getRequestLine());
13245757cb35ad2e58d7accb7f5d3db6f2d5e72f097dJesse Wilson            assertContains(request.getHeaders(), "Authorization: Basic "
13255757cb35ad2e58d7accb7f5d3db6f2d5e72f097dJesse Wilson                    + SimpleAuthenticator.BASE_64_CREDENTIALS);
1326ffd579b668428272b78f5c6c64f9c89766f37c1aJesse Wilson            assertEquals(Arrays.toString(requestBody), Arrays.toString(request.getBody()));
1327ffd579b668428272b78f5c6c64f9c89766f37c1aJesse Wilson        }
1328ffd579b668428272b78f5c6c64f9c89766f37c1aJesse Wilson    }
1329ffd579b668428272b78f5c6c64f9c89766f37c1aJesse Wilson
1330ffd579b668428272b78f5c6c64f9c89766f37c1aJesse Wilson    public void testAuthenticateWithGet() throws Exception {
1331ffd579b668428272b78f5c6c64f9c89766f37c1aJesse Wilson        MockResponse pleaseAuthenticate = new MockResponse()
1332ffd579b668428272b78f5c6c64f9c89766f37c1aJesse Wilson                .setResponseCode(401)
1333ffd579b668428272b78f5c6c64f9c89766f37c1aJesse Wilson                .addHeader("WWW-Authenticate: Basic realm=\"protected area\"")
1334ffd579b668428272b78f5c6c64f9c89766f37c1aJesse Wilson                .setBody("Please authenticate.");
1335ffd579b668428272b78f5c6c64f9c89766f37c1aJesse Wilson        // fail auth three times...
1336ffd579b668428272b78f5c6c64f9c89766f37c1aJesse Wilson        server.enqueue(pleaseAuthenticate);
1337ffd579b668428272b78f5c6c64f9c89766f37c1aJesse Wilson        server.enqueue(pleaseAuthenticate);
1338ffd579b668428272b78f5c6c64f9c89766f37c1aJesse Wilson        server.enqueue(pleaseAuthenticate);
1339ffd579b668428272b78f5c6c64f9c89766f37c1aJesse Wilson        // ...then succeed the fourth time
1340ffd579b668428272b78f5c6c64f9c89766f37c1aJesse Wilson        server.enqueue(new MockResponse().setBody("Successful auth!"));
1341ffd579b668428272b78f5c6c64f9c89766f37c1aJesse Wilson        server.play();
1342ffd579b668428272b78f5c6c64f9c89766f37c1aJesse Wilson
13435757cb35ad2e58d7accb7f5d3db6f2d5e72f097dJesse Wilson        SimpleAuthenticator authenticator = new SimpleAuthenticator();
13445757cb35ad2e58d7accb7f5d3db6f2d5e72f097dJesse Wilson        Authenticator.setDefault(authenticator);
1345ffd579b668428272b78f5c6c64f9c89766f37c1aJesse Wilson        HttpURLConnection connection = (HttpURLConnection) server.getUrl("/").openConnection();
1346ffd579b668428272b78f5c6c64f9c89766f37c1aJesse Wilson        assertEquals("Successful auth!", readAscii(connection.getInputStream(), Integer.MAX_VALUE));
13475757cb35ad2e58d7accb7f5d3db6f2d5e72f097dJesse Wilson        assertEquals(Authenticator.RequestorType.SERVER, authenticator.requestorType);
13485757cb35ad2e58d7accb7f5d3db6f2d5e72f097dJesse Wilson        assertEquals(server.getPort(), authenticator.requestingPort);
13495757cb35ad2e58d7accb7f5d3db6f2d5e72f097dJesse Wilson        assertEquals(InetAddress.getByName(server.getHostName()), authenticator.requestingSite);
13505757cb35ad2e58d7accb7f5d3db6f2d5e72f097dJesse Wilson        assertEquals("protected area", authenticator.requestingPrompt);
13515757cb35ad2e58d7accb7f5d3db6f2d5e72f097dJesse Wilson        assertEquals("http", authenticator.requestingProtocol);
13525757cb35ad2e58d7accb7f5d3db6f2d5e72f097dJesse Wilson        assertEquals("Basic", authenticator.requestingScheme);
1353ffd579b668428272b78f5c6c64f9c89766f37c1aJesse Wilson
1354ffd579b668428272b78f5c6c64f9c89766f37c1aJesse Wilson        // no authorization header for the first request...
1355ffd579b668428272b78f5c6c64f9c89766f37c1aJesse Wilson        RecordedRequest request = server.takeRequest();
13565757cb35ad2e58d7accb7f5d3db6f2d5e72f097dJesse Wilson        assertContainsNoneMatching(request.getHeaders(), "Authorization: .*");
1357ffd579b668428272b78f5c6c64f9c89766f37c1aJesse Wilson
1358ffd579b668428272b78f5c6c64f9c89766f37c1aJesse Wilson        // ...but the three requests that follow requests include an authorization header
1359ffd579b668428272b78f5c6c64f9c89766f37c1aJesse Wilson        for (int i = 0; i < 3; i++) {
1360ffd579b668428272b78f5c6c64f9c89766f37c1aJesse Wilson            request = server.takeRequest();
1361ffd579b668428272b78f5c6c64f9c89766f37c1aJesse Wilson            assertEquals("GET / HTTP/1.1", request.getRequestLine());
13625757cb35ad2e58d7accb7f5d3db6f2d5e72f097dJesse Wilson            assertContains(request.getHeaders(), "Authorization: Basic "
13635757cb35ad2e58d7accb7f5d3db6f2d5e72f097dJesse Wilson                    + SimpleAuthenticator.BASE_64_CREDENTIALS);
1364ffd579b668428272b78f5c6c64f9c89766f37c1aJesse Wilson        }
1365ffd579b668428272b78f5c6c64f9c89766f37c1aJesse Wilson    }
1366ffd579b668428272b78f5c6c64f9c89766f37c1aJesse Wilson
13675757cb35ad2e58d7accb7f5d3db6f2d5e72f097dJesse Wilson    // http://code.google.com/p/android/issues/detail?id=19081
13685757cb35ad2e58d7accb7f5d3db6f2d5e72f097dJesse Wilson    public void testAuthenticateWithCommaSeparatedAuthenticationMethods() throws Exception {
13695757cb35ad2e58d7accb7f5d3db6f2d5e72f097dJesse Wilson        server.enqueue(new MockResponse()
13705757cb35ad2e58d7accb7f5d3db6f2d5e72f097dJesse Wilson                .setResponseCode(401)
13715757cb35ad2e58d7accb7f5d3db6f2d5e72f097dJesse Wilson                .addHeader("WWW-Authenticate: Scheme1 realm=\"a\", Scheme2 realm=\"b\", "
13725757cb35ad2e58d7accb7f5d3db6f2d5e72f097dJesse Wilson                        + "Scheme3 realm=\"c\"")
13735757cb35ad2e58d7accb7f5d3db6f2d5e72f097dJesse Wilson                .setBody("Please authenticate."));
13745757cb35ad2e58d7accb7f5d3db6f2d5e72f097dJesse Wilson        server.enqueue(new MockResponse().setBody("Successful auth!"));
13755757cb35ad2e58d7accb7f5d3db6f2d5e72f097dJesse Wilson        server.play();
13765757cb35ad2e58d7accb7f5d3db6f2d5e72f097dJesse Wilson
13775757cb35ad2e58d7accb7f5d3db6f2d5e72f097dJesse Wilson        SimpleAuthenticator authenticator = new SimpleAuthenticator();
13785757cb35ad2e58d7accb7f5d3db6f2d5e72f097dJesse Wilson        authenticator.expectedPrompt = "b";
13795757cb35ad2e58d7accb7f5d3db6f2d5e72f097dJesse Wilson        Authenticator.setDefault(authenticator);
13805757cb35ad2e58d7accb7f5d3db6f2d5e72f097dJesse Wilson        HttpURLConnection connection = (HttpURLConnection) server.getUrl("/").openConnection();
13815757cb35ad2e58d7accb7f5d3db6f2d5e72f097dJesse Wilson        assertEquals("Successful auth!", readAscii(connection.getInputStream(), Integer.MAX_VALUE));
13825757cb35ad2e58d7accb7f5d3db6f2d5e72f097dJesse Wilson
13835757cb35ad2e58d7accb7f5d3db6f2d5e72f097dJesse Wilson        assertContainsNoneMatching(server.takeRequest().getHeaders(), "Authorization: .*");
13845757cb35ad2e58d7accb7f5d3db6f2d5e72f097dJesse Wilson        assertContains(server.takeRequest().getHeaders(),
13855757cb35ad2e58d7accb7f5d3db6f2d5e72f097dJesse Wilson                "Authorization: Scheme2 " + SimpleAuthenticator.BASE_64_CREDENTIALS);
13865757cb35ad2e58d7accb7f5d3db6f2d5e72f097dJesse Wilson        assertEquals("Scheme2", authenticator.requestingScheme);
13875757cb35ad2e58d7accb7f5d3db6f2d5e72f097dJesse Wilson    }
13885757cb35ad2e58d7accb7f5d3db6f2d5e72f097dJesse Wilson
13895757cb35ad2e58d7accb7f5d3db6f2d5e72f097dJesse Wilson    public void testAuthenticateWithMultipleAuthenticationHeaders() throws Exception {
13905757cb35ad2e58d7accb7f5d3db6f2d5e72f097dJesse Wilson        server.enqueue(new MockResponse()
13915757cb35ad2e58d7accb7f5d3db6f2d5e72f097dJesse Wilson                .setResponseCode(401)
13925757cb35ad2e58d7accb7f5d3db6f2d5e72f097dJesse Wilson                .addHeader("WWW-Authenticate: Scheme1 realm=\"a\"")
13935757cb35ad2e58d7accb7f5d3db6f2d5e72f097dJesse Wilson                .addHeader("WWW-Authenticate: Scheme2 realm=\"b\"")
13945757cb35ad2e58d7accb7f5d3db6f2d5e72f097dJesse Wilson                .addHeader("WWW-Authenticate: Scheme3 realm=\"c\"")
13955757cb35ad2e58d7accb7f5d3db6f2d5e72f097dJesse Wilson                .setBody("Please authenticate."));
13965757cb35ad2e58d7accb7f5d3db6f2d5e72f097dJesse Wilson        server.enqueue(new MockResponse().setBody("Successful auth!"));
13975757cb35ad2e58d7accb7f5d3db6f2d5e72f097dJesse Wilson        server.play();
13985757cb35ad2e58d7accb7f5d3db6f2d5e72f097dJesse Wilson
13995757cb35ad2e58d7accb7f5d3db6f2d5e72f097dJesse Wilson        SimpleAuthenticator authenticator = new SimpleAuthenticator();
14005757cb35ad2e58d7accb7f5d3db6f2d5e72f097dJesse Wilson        authenticator.expectedPrompt = "b";
14015757cb35ad2e58d7accb7f5d3db6f2d5e72f097dJesse Wilson        Authenticator.setDefault(authenticator);
14025757cb35ad2e58d7accb7f5d3db6f2d5e72f097dJesse Wilson        HttpURLConnection connection = (HttpURLConnection) server.getUrl("/").openConnection();
14035757cb35ad2e58d7accb7f5d3db6f2d5e72f097dJesse Wilson        assertEquals("Successful auth!", readAscii(connection.getInputStream(), Integer.MAX_VALUE));
14045757cb35ad2e58d7accb7f5d3db6f2d5e72f097dJesse Wilson
14055757cb35ad2e58d7accb7f5d3db6f2d5e72f097dJesse Wilson        assertContainsNoneMatching(server.takeRequest().getHeaders(), "Authorization: .*");
14065757cb35ad2e58d7accb7f5d3db6f2d5e72f097dJesse Wilson        assertContains(server.takeRequest().getHeaders(),
14075757cb35ad2e58d7accb7f5d3db6f2d5e72f097dJesse Wilson                "Authorization: Scheme2 " + SimpleAuthenticator.BASE_64_CREDENTIALS);
14085757cb35ad2e58d7accb7f5d3db6f2d5e72f097dJesse Wilson        assertEquals("Scheme2", authenticator.requestingScheme);
14095757cb35ad2e58d7accb7f5d3db6f2d5e72f097dJesse Wilson    }
14105757cb35ad2e58d7accb7f5d3db6f2d5e72f097dJesse Wilson
1411c0372d90016d241ac979faa6fa1731f30b6f2a03Jesse Wilson    public void testRedirectedWithChunkedEncoding() throws Exception {
1412c0372d90016d241ac979faa6fa1731f30b6f2a03Jesse Wilson        testRedirected(TransferKind.CHUNKED, true);
1413c0372d90016d241ac979faa6fa1731f30b6f2a03Jesse Wilson    }
1414c0372d90016d241ac979faa6fa1731f30b6f2a03Jesse Wilson
1415c0372d90016d241ac979faa6fa1731f30b6f2a03Jesse Wilson    public void testRedirectedWithContentLengthHeader() throws Exception {
1416c0372d90016d241ac979faa6fa1731f30b6f2a03Jesse Wilson        testRedirected(TransferKind.FIXED_LENGTH, true);
1417c0372d90016d241ac979faa6fa1731f30b6f2a03Jesse Wilson    }
1418c0372d90016d241ac979faa6fa1731f30b6f2a03Jesse Wilson
1419c0372d90016d241ac979faa6fa1731f30b6f2a03Jesse Wilson    public void testRedirectedWithNoLengthHeaders() throws Exception {
1420c0372d90016d241ac979faa6fa1731f30b6f2a03Jesse Wilson        testRedirected(TransferKind.END_OF_STREAM, false);
1421c0372d90016d241ac979faa6fa1731f30b6f2a03Jesse Wilson    }
1422c0372d90016d241ac979faa6fa1731f30b6f2a03Jesse Wilson
1423c0372d90016d241ac979faa6fa1731f30b6f2a03Jesse Wilson    private void testRedirected(TransferKind transferKind, boolean reuse) throws Exception {
1424c0372d90016d241ac979faa6fa1731f30b6f2a03Jesse Wilson        MockResponse response = new MockResponse()
1425c0372d90016d241ac979faa6fa1731f30b6f2a03Jesse Wilson                .setResponseCode(HttpURLConnection.HTTP_MOVED_TEMP)
1426c0372d90016d241ac979faa6fa1731f30b6f2a03Jesse Wilson                .addHeader("Location: /foo");
1427c0372d90016d241ac979faa6fa1731f30b6f2a03Jesse Wilson        transferKind.setBody(response, "This page has moved!", 10);
1428c0372d90016d241ac979faa6fa1731f30b6f2a03Jesse Wilson        server.enqueue(response);
1429c0372d90016d241ac979faa6fa1731f30b6f2a03Jesse Wilson        server.enqueue(new MockResponse().setBody("This is the new location!"));
1430c0372d90016d241ac979faa6fa1731f30b6f2a03Jesse Wilson        server.play();
1431c0372d90016d241ac979faa6fa1731f30b6f2a03Jesse Wilson
1432c0372d90016d241ac979faa6fa1731f30b6f2a03Jesse Wilson        URLConnection connection = server.getUrl("/").openConnection();
1433c0372d90016d241ac979faa6fa1731f30b6f2a03Jesse Wilson        assertEquals("This is the new location!",
1434c0372d90016d241ac979faa6fa1731f30b6f2a03Jesse Wilson                readAscii(connection.getInputStream(), Integer.MAX_VALUE));
1435c0372d90016d241ac979faa6fa1731f30b6f2a03Jesse Wilson
1436c0372d90016d241ac979faa6fa1731f30b6f2a03Jesse Wilson        RecordedRequest first = server.takeRequest();
1437c0372d90016d241ac979faa6fa1731f30b6f2a03Jesse Wilson        assertEquals("GET / HTTP/1.1", first.getRequestLine());
1438c0372d90016d241ac979faa6fa1731f30b6f2a03Jesse Wilson        RecordedRequest retry = server.takeRequest();
1439c0372d90016d241ac979faa6fa1731f30b6f2a03Jesse Wilson        assertEquals("GET /foo HTTP/1.1", retry.getRequestLine());
1440c0372d90016d241ac979faa6fa1731f30b6f2a03Jesse Wilson        if (reuse) {
1441c0372d90016d241ac979faa6fa1731f30b6f2a03Jesse Wilson            assertEquals("Expected connection reuse", 1, retry.getSequenceNumber());
1442c0372d90016d241ac979faa6fa1731f30b6f2a03Jesse Wilson        }
1443c0372d90016d241ac979faa6fa1731f30b6f2a03Jesse Wilson    }
1444c0372d90016d241ac979faa6fa1731f30b6f2a03Jesse Wilson
1445c0372d90016d241ac979faa6fa1731f30b6f2a03Jesse Wilson    public void testRedirectedOnHttps() throws IOException, InterruptedException {
1446c0372d90016d241ac979faa6fa1731f30b6f2a03Jesse Wilson        TestSSLContext testSSLContext = TestSSLContext.create();
1447059dbc04218144f985b20a228bbe98139d400d0cBrian Carlstrom        server.useHttps(testSSLContext.serverContext.getSocketFactory(), false);
1448c0372d90016d241ac979faa6fa1731f30b6f2a03Jesse Wilson        server.enqueue(new MockResponse()
1449c0372d90016d241ac979faa6fa1731f30b6f2a03Jesse Wilson                .setResponseCode(HttpURLConnection.HTTP_MOVED_TEMP)
1450c0372d90016d241ac979faa6fa1731f30b6f2a03Jesse Wilson                .addHeader("Location: /foo")
1451c0372d90016d241ac979faa6fa1731f30b6f2a03Jesse Wilson                .setBody("This page has moved!"));
1452c0372d90016d241ac979faa6fa1731f30b6f2a03Jesse Wilson        server.enqueue(new MockResponse().setBody("This is the new location!"));
1453c0372d90016d241ac979faa6fa1731f30b6f2a03Jesse Wilson        server.play();
1454c0372d90016d241ac979faa6fa1731f30b6f2a03Jesse Wilson
1455c0372d90016d241ac979faa6fa1731f30b6f2a03Jesse Wilson        HttpsURLConnection connection = (HttpsURLConnection) server.getUrl("/").openConnection();
1456059dbc04218144f985b20a228bbe98139d400d0cBrian Carlstrom        connection.setSSLSocketFactory(testSSLContext.clientContext.getSocketFactory());
1457c0372d90016d241ac979faa6fa1731f30b6f2a03Jesse Wilson        assertEquals("This is the new location!",
1458c0372d90016d241ac979faa6fa1731f30b6f2a03Jesse Wilson                readAscii(connection.getInputStream(), Integer.MAX_VALUE));
1459c0372d90016d241ac979faa6fa1731f30b6f2a03Jesse Wilson
1460c0372d90016d241ac979faa6fa1731f30b6f2a03Jesse Wilson        RecordedRequest first = server.takeRequest();
1461c0372d90016d241ac979faa6fa1731f30b6f2a03Jesse Wilson        assertEquals("GET / HTTP/1.1", first.getRequestLine());
1462c0372d90016d241ac979faa6fa1731f30b6f2a03Jesse Wilson        RecordedRequest retry = server.takeRequest();
1463c0372d90016d241ac979faa6fa1731f30b6f2a03Jesse Wilson        assertEquals("GET /foo HTTP/1.1", retry.getRequestLine());
1464c0372d90016d241ac979faa6fa1731f30b6f2a03Jesse Wilson        assertEquals("Expected connection reuse", 1, retry.getSequenceNumber());
1465c0372d90016d241ac979faa6fa1731f30b6f2a03Jesse Wilson    }
1466c0372d90016d241ac979faa6fa1731f30b6f2a03Jesse Wilson
1467c0372d90016d241ac979faa6fa1731f30b6f2a03Jesse Wilson    public void testNotRedirectedFromHttpsToHttp() throws IOException, InterruptedException {
1468c0372d90016d241ac979faa6fa1731f30b6f2a03Jesse Wilson        TestSSLContext testSSLContext = TestSSLContext.create();
1469059dbc04218144f985b20a228bbe98139d400d0cBrian Carlstrom        server.useHttps(testSSLContext.serverContext.getSocketFactory(), false);
1470c0372d90016d241ac979faa6fa1731f30b6f2a03Jesse Wilson        server.enqueue(new MockResponse()
1471c0372d90016d241ac979faa6fa1731f30b6f2a03Jesse Wilson                .setResponseCode(HttpURLConnection.HTTP_MOVED_TEMP)
1472c0372d90016d241ac979faa6fa1731f30b6f2a03Jesse Wilson                .addHeader("Location: http://anyhost/foo")
1473c0372d90016d241ac979faa6fa1731f30b6f2a03Jesse Wilson                .setBody("This page has moved!"));
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 page has moved!",
1479c0372d90016d241ac979faa6fa1731f30b6f2a03Jesse Wilson                readAscii(connection.getInputStream(), Integer.MAX_VALUE));
1480c0372d90016d241ac979faa6fa1731f30b6f2a03Jesse Wilson    }
1481c0372d90016d241ac979faa6fa1731f30b6f2a03Jesse Wilson
1482c0372d90016d241ac979faa6fa1731f30b6f2a03Jesse Wilson    public void testNotRedirectedFromHttpToHttps() throws IOException, InterruptedException {
1483c0372d90016d241ac979faa6fa1731f30b6f2a03Jesse Wilson        server.enqueue(new MockResponse()
1484c0372d90016d241ac979faa6fa1731f30b6f2a03Jesse Wilson                .setResponseCode(HttpURLConnection.HTTP_MOVED_TEMP)
1485c0372d90016d241ac979faa6fa1731f30b6f2a03Jesse Wilson                .addHeader("Location: https://anyhost/foo")
1486c0372d90016d241ac979faa6fa1731f30b6f2a03Jesse Wilson                .setBody("This page has moved!"));
1487c0372d90016d241ac979faa6fa1731f30b6f2a03Jesse Wilson        server.play();
1488c0372d90016d241ac979faa6fa1731f30b6f2a03Jesse Wilson
1489c0372d90016d241ac979faa6fa1731f30b6f2a03Jesse Wilson        HttpURLConnection connection = (HttpURLConnection) server.getUrl("/").openConnection();
1490c0372d90016d241ac979faa6fa1731f30b6f2a03Jesse Wilson        assertEquals("This page has moved!",
1491c0372d90016d241ac979faa6fa1731f30b6f2a03Jesse Wilson                readAscii(connection.getInputStream(), Integer.MAX_VALUE));
1492c0372d90016d241ac979faa6fa1731f30b6f2a03Jesse Wilson    }
1493c0372d90016d241ac979faa6fa1731f30b6f2a03Jesse Wilson
1494c0372d90016d241ac979faa6fa1731f30b6f2a03Jesse Wilson    public void testRedirectToAnotherOriginServer() throws Exception {
1495c0372d90016d241ac979faa6fa1731f30b6f2a03Jesse Wilson        MockWebServer server2 = new MockWebServer();
1496c0372d90016d241ac979faa6fa1731f30b6f2a03Jesse Wilson        server2.enqueue(new MockResponse().setBody("This is the 2nd server!"));
1497c0372d90016d241ac979faa6fa1731f30b6f2a03Jesse Wilson        server2.play();
1498c0372d90016d241ac979faa6fa1731f30b6f2a03Jesse Wilson
1499c0372d90016d241ac979faa6fa1731f30b6f2a03Jesse Wilson        server.enqueue(new MockResponse()
1500c0372d90016d241ac979faa6fa1731f30b6f2a03Jesse Wilson                .setResponseCode(HttpURLConnection.HTTP_MOVED_TEMP)
1501c0372d90016d241ac979faa6fa1731f30b6f2a03Jesse Wilson                .addHeader("Location: " + server2.getUrl("/").toString())
1502c0372d90016d241ac979faa6fa1731f30b6f2a03Jesse Wilson                .setBody("This page has moved!"));
1503c0372d90016d241ac979faa6fa1731f30b6f2a03Jesse Wilson        server.enqueue(new MockResponse().setBody("This is the first server again!"));
1504c0372d90016d241ac979faa6fa1731f30b6f2a03Jesse Wilson        server.play();
1505c0372d90016d241ac979faa6fa1731f30b6f2a03Jesse Wilson
1506c0372d90016d241ac979faa6fa1731f30b6f2a03Jesse Wilson        URLConnection connection = server.getUrl("/").openConnection();
1507c0372d90016d241ac979faa6fa1731f30b6f2a03Jesse Wilson        assertEquals("This is the 2nd server!",
1508c0372d90016d241ac979faa6fa1731f30b6f2a03Jesse Wilson                readAscii(connection.getInputStream(), Integer.MAX_VALUE));
1509c0372d90016d241ac979faa6fa1731f30b6f2a03Jesse Wilson        assertEquals(server2.getUrl("/"), connection.getURL());
1510c0372d90016d241ac979faa6fa1731f30b6f2a03Jesse Wilson
1511c0372d90016d241ac979faa6fa1731f30b6f2a03Jesse Wilson        // make sure the first server was careful to recycle the connection
1512c0372d90016d241ac979faa6fa1731f30b6f2a03Jesse Wilson        assertEquals("This is the first server again!",
1513c0372d90016d241ac979faa6fa1731f30b6f2a03Jesse Wilson                readAscii(server.getUrl("/").openStream(), Integer.MAX_VALUE));
1514c0372d90016d241ac979faa6fa1731f30b6f2a03Jesse Wilson
1515c0372d90016d241ac979faa6fa1731f30b6f2a03Jesse Wilson        RecordedRequest first = server.takeRequest();
15160c2fd828abec671333b8b88281825fd27a783723Jesse Wilson        assertContains(first.getHeaders(), "Host: " + hostName + ":" + server.getPort());
1517c0372d90016d241ac979faa6fa1731f30b6f2a03Jesse Wilson        RecordedRequest second = server2.takeRequest();
15180c2fd828abec671333b8b88281825fd27a783723Jesse Wilson        assertContains(second.getHeaders(), "Host: " + hostName + ":" + server2.getPort());
1519c0372d90016d241ac979faa6fa1731f30b6f2a03Jesse Wilson        RecordedRequest third = server.takeRequest();
1520c0372d90016d241ac979faa6fa1731f30b6f2a03Jesse Wilson        assertEquals("Expected connection reuse", 1, third.getSequenceNumber());
1521c0372d90016d241ac979faa6fa1731f30b6f2a03Jesse Wilson
1522c0372d90016d241ac979faa6fa1731f30b6f2a03Jesse Wilson        server2.shutdown();
1523c0372d90016d241ac979faa6fa1731f30b6f2a03Jesse Wilson    }
1524c0372d90016d241ac979faa6fa1731f30b6f2a03Jesse Wilson
1525d742d7fc7f0593eb8c6e4ac9dd4c0f6a80374e46Jesse Wilson    public void testResponse300MultipleChoiceWithPost() throws Exception {
1526d742d7fc7f0593eb8c6e4ac9dd4c0f6a80374e46Jesse Wilson        // Chrome doesn't follow the redirect, but Firefox and the RI both do
1527d742d7fc7f0593eb8c6e4ac9dd4c0f6a80374e46Jesse Wilson        testResponseRedirectedWithPost(HttpURLConnection.HTTP_MULT_CHOICE);
1528d742d7fc7f0593eb8c6e4ac9dd4c0f6a80374e46Jesse Wilson    }
1529d742d7fc7f0593eb8c6e4ac9dd4c0f6a80374e46Jesse Wilson
1530d742d7fc7f0593eb8c6e4ac9dd4c0f6a80374e46Jesse Wilson    public void testResponse301MovedPermanentlyWithPost() throws Exception {
1531d742d7fc7f0593eb8c6e4ac9dd4c0f6a80374e46Jesse Wilson        testResponseRedirectedWithPost(HttpURLConnection.HTTP_MOVED_PERM);
1532d742d7fc7f0593eb8c6e4ac9dd4c0f6a80374e46Jesse Wilson    }
1533d742d7fc7f0593eb8c6e4ac9dd4c0f6a80374e46Jesse Wilson
1534d742d7fc7f0593eb8c6e4ac9dd4c0f6a80374e46Jesse Wilson    public void testResponse302MovedTemporarilyWithPost() throws Exception {
1535d742d7fc7f0593eb8c6e4ac9dd4c0f6a80374e46Jesse Wilson        testResponseRedirectedWithPost(HttpURLConnection.HTTP_MOVED_TEMP);
1536d742d7fc7f0593eb8c6e4ac9dd4c0f6a80374e46Jesse Wilson    }
1537d742d7fc7f0593eb8c6e4ac9dd4c0f6a80374e46Jesse Wilson
1538d742d7fc7f0593eb8c6e4ac9dd4c0f6a80374e46Jesse Wilson    public void testResponse303SeeOtherWithPost() throws Exception {
1539d742d7fc7f0593eb8c6e4ac9dd4c0f6a80374e46Jesse Wilson        testResponseRedirectedWithPost(HttpURLConnection.HTTP_SEE_OTHER);
1540d742d7fc7f0593eb8c6e4ac9dd4c0f6a80374e46Jesse Wilson    }
1541d742d7fc7f0593eb8c6e4ac9dd4c0f6a80374e46Jesse Wilson
1542d742d7fc7f0593eb8c6e4ac9dd4c0f6a80374e46Jesse Wilson    private void testResponseRedirectedWithPost(int redirectCode) throws Exception {
1543d742d7fc7f0593eb8c6e4ac9dd4c0f6a80374e46Jesse Wilson        server.enqueue(new MockResponse()
1544d742d7fc7f0593eb8c6e4ac9dd4c0f6a80374e46Jesse Wilson                .setResponseCode(redirectCode)
1545d742d7fc7f0593eb8c6e4ac9dd4c0f6a80374e46Jesse Wilson                .addHeader("Location: /page2")
1546d742d7fc7f0593eb8c6e4ac9dd4c0f6a80374e46Jesse Wilson                .setBody("This page has moved!"));
1547d742d7fc7f0593eb8c6e4ac9dd4c0f6a80374e46Jesse Wilson        server.enqueue(new MockResponse().setBody("Page 2"));
1548d742d7fc7f0593eb8c6e4ac9dd4c0f6a80374e46Jesse Wilson        server.play();
1549d742d7fc7f0593eb8c6e4ac9dd4c0f6a80374e46Jesse Wilson
1550d742d7fc7f0593eb8c6e4ac9dd4c0f6a80374e46Jesse Wilson        HttpURLConnection connection = (HttpURLConnection) server.getUrl("/page1").openConnection();
1551d742d7fc7f0593eb8c6e4ac9dd4c0f6a80374e46Jesse Wilson        connection.setDoOutput(true);
1552d742d7fc7f0593eb8c6e4ac9dd4c0f6a80374e46Jesse Wilson        byte[] requestBody = { 'A', 'B', 'C', 'D' };
1553d742d7fc7f0593eb8c6e4ac9dd4c0f6a80374e46Jesse Wilson        OutputStream outputStream = connection.getOutputStream();
1554d742d7fc7f0593eb8c6e4ac9dd4c0f6a80374e46Jesse Wilson        outputStream.write(requestBody);
1555d742d7fc7f0593eb8c6e4ac9dd4c0f6a80374e46Jesse Wilson        outputStream.close();
1556d742d7fc7f0593eb8c6e4ac9dd4c0f6a80374e46Jesse Wilson        assertEquals("Page 2", readAscii(connection.getInputStream(), Integer.MAX_VALUE));
1557d742d7fc7f0593eb8c6e4ac9dd4c0f6a80374e46Jesse Wilson        assertTrue(connection.getDoOutput());
1558d742d7fc7f0593eb8c6e4ac9dd4c0f6a80374e46Jesse Wilson
1559d742d7fc7f0593eb8c6e4ac9dd4c0f6a80374e46Jesse Wilson        RecordedRequest page1 = server.takeRequest();
1560d742d7fc7f0593eb8c6e4ac9dd4c0f6a80374e46Jesse Wilson        assertEquals("POST /page1 HTTP/1.1", page1.getRequestLine());
1561d742d7fc7f0593eb8c6e4ac9dd4c0f6a80374e46Jesse Wilson        assertEquals(Arrays.toString(requestBody), Arrays.toString(page1.getBody()));
1562d742d7fc7f0593eb8c6e4ac9dd4c0f6a80374e46Jesse Wilson
1563d742d7fc7f0593eb8c6e4ac9dd4c0f6a80374e46Jesse Wilson        RecordedRequest page2 = server.takeRequest();
1564d742d7fc7f0593eb8c6e4ac9dd4c0f6a80374e46Jesse Wilson        assertEquals("GET /page2 HTTP/1.1", page2.getRequestLine());
1565d742d7fc7f0593eb8c6e4ac9dd4c0f6a80374e46Jesse Wilson    }
1566d742d7fc7f0593eb8c6e4ac9dd4c0f6a80374e46Jesse Wilson
1567d742d7fc7f0593eb8c6e4ac9dd4c0f6a80374e46Jesse Wilson    public void testResponse305UseProxy() throws Exception {
1568d742d7fc7f0593eb8c6e4ac9dd4c0f6a80374e46Jesse Wilson        server.play();
1569d742d7fc7f0593eb8c6e4ac9dd4c0f6a80374e46Jesse Wilson        server.enqueue(new MockResponse()
1570d742d7fc7f0593eb8c6e4ac9dd4c0f6a80374e46Jesse Wilson                .setResponseCode(HttpURLConnection.HTTP_USE_PROXY)
1571d742d7fc7f0593eb8c6e4ac9dd4c0f6a80374e46Jesse Wilson                .addHeader("Location: " + server.getUrl("/"))
1572d742d7fc7f0593eb8c6e4ac9dd4c0f6a80374e46Jesse Wilson                .setBody("This page has moved!"));
1573d742d7fc7f0593eb8c6e4ac9dd4c0f6a80374e46Jesse Wilson        server.enqueue(new MockResponse().setBody("Proxy Response"));
1574d742d7fc7f0593eb8c6e4ac9dd4c0f6a80374e46Jesse Wilson
1575d742d7fc7f0593eb8c6e4ac9dd4c0f6a80374e46Jesse Wilson        HttpURLConnection connection = (HttpURLConnection) server.getUrl("/foo").openConnection();
1576d742d7fc7f0593eb8c6e4ac9dd4c0f6a80374e46Jesse Wilson        // Fails on the RI, which gets "Proxy Response"
1577d742d7fc7f0593eb8c6e4ac9dd4c0f6a80374e46Jesse Wilson        assertEquals("This page has moved!",
1578d742d7fc7f0593eb8c6e4ac9dd4c0f6a80374e46Jesse Wilson                readAscii(connection.getInputStream(), Integer.MAX_VALUE));
1579d742d7fc7f0593eb8c6e4ac9dd4c0f6a80374e46Jesse Wilson
1580d742d7fc7f0593eb8c6e4ac9dd4c0f6a80374e46Jesse Wilson        RecordedRequest page1 = server.takeRequest();
1581d742d7fc7f0593eb8c6e4ac9dd4c0f6a80374e46Jesse Wilson        assertEquals("GET /foo HTTP/1.1", page1.getRequestLine());
1582d742d7fc7f0593eb8c6e4ac9dd4c0f6a80374e46Jesse Wilson        assertEquals(1, server.getRequestCount());
1583d742d7fc7f0593eb8c6e4ac9dd4c0f6a80374e46Jesse Wilson    }
1584d742d7fc7f0593eb8c6e4ac9dd4c0f6a80374e46Jesse Wilson
1585c0372d90016d241ac979faa6fa1731f30b6f2a03Jesse Wilson    public void testHttpsWithCustomTrustManager() throws Exception {
1586c0372d90016d241ac979faa6fa1731f30b6f2a03Jesse Wilson        RecordingHostnameVerifier hostnameVerifier = new RecordingHostnameVerifier();
1587c0372d90016d241ac979faa6fa1731f30b6f2a03Jesse Wilson        RecordingTrustManager trustManager = new RecordingTrustManager();
1588c0372d90016d241ac979faa6fa1731f30b6f2a03Jesse Wilson        SSLContext sc = SSLContext.getInstance("TLS");
1589c0372d90016d241ac979faa6fa1731f30b6f2a03Jesse Wilson        sc.init(null, new TrustManager[] { trustManager }, new java.security.SecureRandom());
1590c0372d90016d241ac979faa6fa1731f30b6f2a03Jesse Wilson
1591c0372d90016d241ac979faa6fa1731f30b6f2a03Jesse Wilson        HostnameVerifier defaultHostnameVerifier = HttpsURLConnection.getDefaultHostnameVerifier();
1592c0372d90016d241ac979faa6fa1731f30b6f2a03Jesse Wilson        HttpsURLConnection.setDefaultHostnameVerifier(hostnameVerifier);
1593c0372d90016d241ac979faa6fa1731f30b6f2a03Jesse Wilson        SSLSocketFactory defaultSSLSocketFactory = HttpsURLConnection.getDefaultSSLSocketFactory();
1594c0372d90016d241ac979faa6fa1731f30b6f2a03Jesse Wilson        HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
1595c0372d90016d241ac979faa6fa1731f30b6f2a03Jesse Wilson        try {
1596c0372d90016d241ac979faa6fa1731f30b6f2a03Jesse Wilson            TestSSLContext testSSLContext = TestSSLContext.create();
1597059dbc04218144f985b20a228bbe98139d400d0cBrian Carlstrom            server.useHttps(testSSLContext.serverContext.getSocketFactory(), false);
1598c0372d90016d241ac979faa6fa1731f30b6f2a03Jesse Wilson            server.enqueue(new MockResponse().setBody("ABC"));
1599c0372d90016d241ac979faa6fa1731f30b6f2a03Jesse Wilson            server.enqueue(new MockResponse().setBody("DEF"));
1600c0372d90016d241ac979faa6fa1731f30b6f2a03Jesse Wilson            server.enqueue(new MockResponse().setBody("GHI"));
1601c0372d90016d241ac979faa6fa1731f30b6f2a03Jesse Wilson            server.play();
1602c0372d90016d241ac979faa6fa1731f30b6f2a03Jesse Wilson
1603c0372d90016d241ac979faa6fa1731f30b6f2a03Jesse Wilson            URL url = server.getUrl("/");
1604c0372d90016d241ac979faa6fa1731f30b6f2a03Jesse Wilson            assertEquals("ABC", readAscii(url.openStream(), Integer.MAX_VALUE));
1605c0372d90016d241ac979faa6fa1731f30b6f2a03Jesse Wilson            assertEquals("DEF", readAscii(url.openStream(), Integer.MAX_VALUE));
1606c0372d90016d241ac979faa6fa1731f30b6f2a03Jesse Wilson            assertEquals("GHI", readAscii(url.openStream(), Integer.MAX_VALUE));
1607c0372d90016d241ac979faa6fa1731f30b6f2a03Jesse Wilson
16080c2fd828abec671333b8b88281825fd27a783723Jesse Wilson            assertEquals(Arrays.asList("verify " + hostName), hostnameVerifier.calls);
16094559b1d37edcb5d7f1da086cf2e3290388d74f46Brian Carlstrom            assertEquals(Arrays.asList("checkServerTrusted ["
16100c2fd828abec671333b8b88281825fd27a783723Jesse Wilson                    + "CN=" + hostName + " 1, "
1611b7f4d6c3968c372767b2510f38a3d506067aced6Jesse Wilson                    + "CN=Test Intermediate Certificate Authority 1, "
1612b7f4d6c3968c372767b2510f38a3d506067aced6Jesse Wilson                    + "CN=Test Root Certificate Authority 1"
1613b7f4d6c3968c372767b2510f38a3d506067aced6Jesse Wilson                    + "] RSA"),
1614c0372d90016d241ac979faa6fa1731f30b6f2a03Jesse Wilson                    trustManager.calls);
1615c0372d90016d241ac979faa6fa1731f30b6f2a03Jesse Wilson        } finally {
1616c0372d90016d241ac979faa6fa1731f30b6f2a03Jesse Wilson            HttpsURLConnection.setDefaultHostnameVerifier(defaultHostnameVerifier);
1617c0372d90016d241ac979faa6fa1731f30b6f2a03Jesse Wilson            HttpsURLConnection.setDefaultSSLSocketFactory(defaultSSLSocketFactory);
1618c0372d90016d241ac979faa6fa1731f30b6f2a03Jesse Wilson        }
1619c0372d90016d241ac979faa6fa1731f30b6f2a03Jesse Wilson    }
1620c0372d90016d241ac979faa6fa1731f30b6f2a03Jesse Wilson
16212d9fa917aae6a6da38e9d1eda05841ffdf8855bbJesse Wilson    /**
16222d9fa917aae6a6da38e9d1eda05841ffdf8855bbJesse Wilson     * Test that the timeout period is honored. The timeout may be doubled!
16232d9fa917aae6a6da38e9d1eda05841ffdf8855bbJesse Wilson     * HttpURLConnection will wait the full timeout for each of the server's IP
16242d9fa917aae6a6da38e9d1eda05841ffdf8855bbJesse Wilson     * addresses. This is typically one IPv4 address and one IPv6 address.
16252d9fa917aae6a6da38e9d1eda05841ffdf8855bbJesse Wilson     */
1626eafede536f2059bb6c869e7a5f07fd7ad9758e28Jesse Wilson    public void testConnectTimeouts() throws IOException {
16275fc5dde4c719c1dfdac46b67d5d2e4884d07721eElliott Hughes        StuckServer ss = new StuckServer();
16285fc5dde4c719c1dfdac46b67d5d2e4884d07721eElliott Hughes        int serverPort = ss.getLocalPort();
1629f02c695ed03e708623d9365dec26d533356ef2d0Brian Carlstrom        URLConnection urlConnection = new URL("http://localhost:" + serverPort).openConnection();
1630b7f4d6c3968c372767b2510f38a3d506067aced6Jesse Wilson        int timeout = 1000;
1631b7f4d6c3968c372767b2510f38a3d506067aced6Jesse Wilson        urlConnection.setConnectTimeout(timeout);
1632b7f4d6c3968c372767b2510f38a3d506067aced6Jesse Wilson        long start = System.currentTimeMillis();
1633eafede536f2059bb6c869e7a5f07fd7ad9758e28Jesse Wilson        try {
1634eafede536f2059bb6c869e7a5f07fd7ad9758e28Jesse Wilson            urlConnection.getInputStream();
1635eafede536f2059bb6c869e7a5f07fd7ad9758e28Jesse Wilson            fail();
1636eafede536f2059bb6c869e7a5f07fd7ad9758e28Jesse Wilson        } catch (SocketTimeoutException expected) {
16372d9fa917aae6a6da38e9d1eda05841ffdf8855bbJesse Wilson            long elapsed = System.currentTimeMillis() - start;
16382d9fa917aae6a6da38e9d1eda05841ffdf8855bbJesse Wilson            int attempts = InetAddress.getAllByName("localhost").length; // one per IP address
16392d9fa917aae6a6da38e9d1eda05841ffdf8855bbJesse Wilson            assertTrue("timeout=" +timeout + ", elapsed=" + elapsed + ", attempts=" + attempts,
16402d9fa917aae6a6da38e9d1eda05841ffdf8855bbJesse Wilson                    Math.abs((attempts * timeout) - elapsed) < 500);
16415fc5dde4c719c1dfdac46b67d5d2e4884d07721eElliott Hughes        } finally {
16425fc5dde4c719c1dfdac46b67d5d2e4884d07721eElliott Hughes            ss.close();
1643f02c695ed03e708623d9365dec26d533356ef2d0Brian Carlstrom        }
1644eafede536f2059bb6c869e7a5f07fd7ad9758e28Jesse Wilson    }
1645eafede536f2059bb6c869e7a5f07fd7ad9758e28Jesse Wilson
1646eafede536f2059bb6c869e7a5f07fd7ad9758e28Jesse Wilson    public void testReadTimeouts() throws IOException {
1647eafede536f2059bb6c869e7a5f07fd7ad9758e28Jesse Wilson        /*
1648eafede536f2059bb6c869e7a5f07fd7ad9758e28Jesse Wilson         * This relies on the fact that MockWebServer doesn't close the
1649eafede536f2059bb6c869e7a5f07fd7ad9758e28Jesse Wilson         * connection after a response has been sent. This causes the client to
1650eafede536f2059bb6c869e7a5f07fd7ad9758e28Jesse Wilson         * try to read more bytes than are sent, which results in a timeout.
1651eafede536f2059bb6c869e7a5f07fd7ad9758e28Jesse Wilson         */
1652eafede536f2059bb6c869e7a5f07fd7ad9758e28Jesse Wilson        MockResponse timeout = new MockResponse()
1653eafede536f2059bb6c869e7a5f07fd7ad9758e28Jesse Wilson                .setBody("ABC")
1654eafede536f2059bb6c869e7a5f07fd7ad9758e28Jesse Wilson                .clearHeaders()
1655eafede536f2059bb6c869e7a5f07fd7ad9758e28Jesse Wilson                .addHeader("Content-Length: 4");
1656eafede536f2059bb6c869e7a5f07fd7ad9758e28Jesse Wilson        server.enqueue(timeout);
1657b7f4d6c3968c372767b2510f38a3d506067aced6Jesse Wilson        server.enqueue(new MockResponse().setBody("unused")); // to keep the server alive
1658eafede536f2059bb6c869e7a5f07fd7ad9758e28Jesse Wilson        server.play();
1659eafede536f2059bb6c869e7a5f07fd7ad9758e28Jesse Wilson
1660eafede536f2059bb6c869e7a5f07fd7ad9758e28Jesse Wilson        URLConnection urlConnection = server.getUrl("/").openConnection();
1661eafede536f2059bb6c869e7a5f07fd7ad9758e28Jesse Wilson        urlConnection.setReadTimeout(1000);
1662eafede536f2059bb6c869e7a5f07fd7ad9758e28Jesse Wilson        InputStream in = urlConnection.getInputStream();
1663eafede536f2059bb6c869e7a5f07fd7ad9758e28Jesse Wilson        assertEquals('A', in.read());
1664eafede536f2059bb6c869e7a5f07fd7ad9758e28Jesse Wilson        assertEquals('B', in.read());
1665eafede536f2059bb6c869e7a5f07fd7ad9758e28Jesse Wilson        assertEquals('C', in.read());
1666eafede536f2059bb6c869e7a5f07fd7ad9758e28Jesse Wilson        try {
1667eafede536f2059bb6c869e7a5f07fd7ad9758e28Jesse Wilson            in.read(); // if Content-Length was accurate, this would return -1 immediately
1668eafede536f2059bb6c869e7a5f07fd7ad9758e28Jesse Wilson            fail();
1669eafede536f2059bb6c869e7a5f07fd7ad9758e28Jesse Wilson        } catch (SocketTimeoutException expected) {
1670eafede536f2059bb6c869e7a5f07fd7ad9758e28Jesse Wilson        }
1671eafede536f2059bb6c869e7a5f07fd7ad9758e28Jesse Wilson    }
1672eafede536f2059bb6c869e7a5f07fd7ad9758e28Jesse Wilson
1673125f068f0a6cd739beac97821c9421cf8317cc87Jesse Wilson    public void testSetChunkedEncodingAsRequestProperty() throws IOException, InterruptedException {
1674125f068f0a6cd739beac97821c9421cf8317cc87Jesse Wilson        server.enqueue(new MockResponse());
1675125f068f0a6cd739beac97821c9421cf8317cc87Jesse Wilson        server.play();
1676125f068f0a6cd739beac97821c9421cf8317cc87Jesse Wilson
1677125f068f0a6cd739beac97821c9421cf8317cc87Jesse Wilson        HttpURLConnection urlConnection = (HttpURLConnection) server.getUrl("/").openConnection();
1678125f068f0a6cd739beac97821c9421cf8317cc87Jesse Wilson        urlConnection.setRequestProperty("Transfer-encoding", "chunked");
1679125f068f0a6cd739beac97821c9421cf8317cc87Jesse Wilson        urlConnection.setDoOutput(true);
1680125f068f0a6cd739beac97821c9421cf8317cc87Jesse Wilson        urlConnection.getOutputStream().write("ABC".getBytes("UTF-8"));
1681125f068f0a6cd739beac97821c9421cf8317cc87Jesse Wilson        assertEquals(200, urlConnection.getResponseCode());
1682125f068f0a6cd739beac97821c9421cf8317cc87Jesse Wilson
1683125f068f0a6cd739beac97821c9421cf8317cc87Jesse Wilson        RecordedRequest request = server.takeRequest();
1684125f068f0a6cd739beac97821c9421cf8317cc87Jesse Wilson        assertEquals("ABC", new String(request.getBody(), "UTF-8"));
1685125f068f0a6cd739beac97821c9421cf8317cc87Jesse Wilson    }
1686125f068f0a6cd739beac97821c9421cf8317cc87Jesse Wilson
1687f418bf447fd007cd2ec2d45b4b0399a11904e9b4Jesse Wilson    public void testConnectionCloseInRequest() throws IOException, InterruptedException {
1688f418bf447fd007cd2ec2d45b4b0399a11904e9b4Jesse Wilson        server.enqueue(new MockResponse()); // server doesn't honor the connection: close header!
1689f418bf447fd007cd2ec2d45b4b0399a11904e9b4Jesse Wilson        server.enqueue(new MockResponse());
1690f418bf447fd007cd2ec2d45b4b0399a11904e9b4Jesse Wilson        server.play();
1691f418bf447fd007cd2ec2d45b4b0399a11904e9b4Jesse Wilson
1692f418bf447fd007cd2ec2d45b4b0399a11904e9b4Jesse Wilson        HttpURLConnection a = (HttpURLConnection) server.getUrl("/").openConnection();
1693f418bf447fd007cd2ec2d45b4b0399a11904e9b4Jesse Wilson        a.setRequestProperty("Connection", "close");
1694f418bf447fd007cd2ec2d45b4b0399a11904e9b4Jesse Wilson        assertEquals(200, a.getResponseCode());
1695f418bf447fd007cd2ec2d45b4b0399a11904e9b4Jesse Wilson
1696f418bf447fd007cd2ec2d45b4b0399a11904e9b4Jesse Wilson        HttpURLConnection b = (HttpURLConnection) server.getUrl("/").openConnection();
1697f418bf447fd007cd2ec2d45b4b0399a11904e9b4Jesse Wilson        assertEquals(200, b.getResponseCode());
1698f418bf447fd007cd2ec2d45b4b0399a11904e9b4Jesse Wilson
1699f418bf447fd007cd2ec2d45b4b0399a11904e9b4Jesse Wilson        assertEquals(0, server.takeRequest().getSequenceNumber());
1700f418bf447fd007cd2ec2d45b4b0399a11904e9b4Jesse Wilson        assertEquals("When connection: close is used, each request should get its own connection",
1701f418bf447fd007cd2ec2d45b4b0399a11904e9b4Jesse Wilson                0, server.takeRequest().getSequenceNumber());
1702f418bf447fd007cd2ec2d45b4b0399a11904e9b4Jesse Wilson    }
1703f418bf447fd007cd2ec2d45b4b0399a11904e9b4Jesse Wilson
1704f418bf447fd007cd2ec2d45b4b0399a11904e9b4Jesse Wilson    public void testConnectionCloseInResponse() throws IOException, InterruptedException {
1705f418bf447fd007cd2ec2d45b4b0399a11904e9b4Jesse Wilson        server.enqueue(new MockResponse().addHeader("Connection: close"));
1706f418bf447fd007cd2ec2d45b4b0399a11904e9b4Jesse Wilson        server.enqueue(new MockResponse());
1707f418bf447fd007cd2ec2d45b4b0399a11904e9b4Jesse Wilson        server.play();
1708f418bf447fd007cd2ec2d45b4b0399a11904e9b4Jesse Wilson
1709f418bf447fd007cd2ec2d45b4b0399a11904e9b4Jesse Wilson        HttpURLConnection a = (HttpURLConnection) server.getUrl("/").openConnection();
1710f418bf447fd007cd2ec2d45b4b0399a11904e9b4Jesse Wilson        assertEquals(200, a.getResponseCode());
1711f418bf447fd007cd2ec2d45b4b0399a11904e9b4Jesse Wilson
1712f418bf447fd007cd2ec2d45b4b0399a11904e9b4Jesse Wilson        HttpURLConnection b = (HttpURLConnection) server.getUrl("/").openConnection();
1713f418bf447fd007cd2ec2d45b4b0399a11904e9b4Jesse Wilson        assertEquals(200, b.getResponseCode());
1714f418bf447fd007cd2ec2d45b4b0399a11904e9b4Jesse Wilson
1715f418bf447fd007cd2ec2d45b4b0399a11904e9b4Jesse Wilson        assertEquals(0, server.takeRequest().getSequenceNumber());
1716f418bf447fd007cd2ec2d45b4b0399a11904e9b4Jesse Wilson        assertEquals("When connection: close is used, each request should get its own connection",
1717f418bf447fd007cd2ec2d45b4b0399a11904e9b4Jesse Wilson                0, server.takeRequest().getSequenceNumber());
1718f418bf447fd007cd2ec2d45b4b0399a11904e9b4Jesse Wilson    }
1719f418bf447fd007cd2ec2d45b4b0399a11904e9b4Jesse Wilson
1720f418bf447fd007cd2ec2d45b4b0399a11904e9b4Jesse Wilson    public void testConnectionCloseWithRedirect() throws IOException, InterruptedException {
1721f418bf447fd007cd2ec2d45b4b0399a11904e9b4Jesse Wilson        MockResponse response = new MockResponse()
1722f418bf447fd007cd2ec2d45b4b0399a11904e9b4Jesse Wilson                .setResponseCode(HttpURLConnection.HTTP_MOVED_TEMP)
1723f418bf447fd007cd2ec2d45b4b0399a11904e9b4Jesse Wilson                .addHeader("Location: /foo")
1724f418bf447fd007cd2ec2d45b4b0399a11904e9b4Jesse Wilson                .addHeader("Connection: close");
1725f418bf447fd007cd2ec2d45b4b0399a11904e9b4Jesse Wilson        server.enqueue(response);
1726f418bf447fd007cd2ec2d45b4b0399a11904e9b4Jesse Wilson        server.enqueue(new MockResponse().setBody("This is the new location!"));
1727f418bf447fd007cd2ec2d45b4b0399a11904e9b4Jesse Wilson        server.play();
1728f418bf447fd007cd2ec2d45b4b0399a11904e9b4Jesse Wilson
1729f418bf447fd007cd2ec2d45b4b0399a11904e9b4Jesse Wilson        URLConnection connection = server.getUrl("/").openConnection();
1730f418bf447fd007cd2ec2d45b4b0399a11904e9b4Jesse Wilson        assertEquals("This is the new location!",
1731f418bf447fd007cd2ec2d45b4b0399a11904e9b4Jesse Wilson                readAscii(connection.getInputStream(), Integer.MAX_VALUE));
1732f418bf447fd007cd2ec2d45b4b0399a11904e9b4Jesse Wilson
1733f418bf447fd007cd2ec2d45b4b0399a11904e9b4Jesse Wilson        assertEquals(0, server.takeRequest().getSequenceNumber());
1734f418bf447fd007cd2ec2d45b4b0399a11904e9b4Jesse Wilson        assertEquals("When connection: close is used, each request should get its own connection",
1735f418bf447fd007cd2ec2d45b4b0399a11904e9b4Jesse Wilson                0, server.takeRequest().getSequenceNumber());
1736f418bf447fd007cd2ec2d45b4b0399a11904e9b4Jesse Wilson    }
1737f418bf447fd007cd2ec2d45b4b0399a11904e9b4Jesse Wilson
173865d890eb22aeba9b009ee642ffd4fff48a6f98aeJesse Wilson    public void testResponseCodeDisagreesWithHeaders() throws IOException, InterruptedException {
173965d890eb22aeba9b009ee642ffd4fff48a6f98aeJesse Wilson        server.enqueue(new MockResponse()
174065d890eb22aeba9b009ee642ffd4fff48a6f98aeJesse Wilson                .setResponseCode(HttpURLConnection.HTTP_NO_CONTENT)
174165d890eb22aeba9b009ee642ffd4fff48a6f98aeJesse Wilson                .setBody("This body is not allowed!"));
174265d890eb22aeba9b009ee642ffd4fff48a6f98aeJesse Wilson        server.play();
174365d890eb22aeba9b009ee642ffd4fff48a6f98aeJesse Wilson
174465d890eb22aeba9b009ee642ffd4fff48a6f98aeJesse Wilson        URLConnection connection = server.getUrl("/").openConnection();
174565d890eb22aeba9b009ee642ffd4fff48a6f98aeJesse Wilson        assertEquals("This body is not allowed!",
174665d890eb22aeba9b009ee642ffd4fff48a6f98aeJesse Wilson                readAscii(connection.getInputStream(), Integer.MAX_VALUE));
174765d890eb22aeba9b009ee642ffd4fff48a6f98aeJesse Wilson    }
174865d890eb22aeba9b009ee642ffd4fff48a6f98aeJesse Wilson
1749ef66494dce45a0b7ec22ec3fb20c60096517a4e3Jesse Wilson    public void testSingleByteReadIsSigned() throws IOException {
1750ef66494dce45a0b7ec22ec3fb20c60096517a4e3Jesse Wilson        server.enqueue(new MockResponse().setBody(new byte[] { -2, -1 }));
1751ef66494dce45a0b7ec22ec3fb20c60096517a4e3Jesse Wilson        server.play();
1752ef66494dce45a0b7ec22ec3fb20c60096517a4e3Jesse Wilson
1753ef66494dce45a0b7ec22ec3fb20c60096517a4e3Jesse Wilson        URLConnection connection = server.getUrl("/").openConnection();
1754ef66494dce45a0b7ec22ec3fb20c60096517a4e3Jesse Wilson        InputStream in = connection.getInputStream();
1755ef66494dce45a0b7ec22ec3fb20c60096517a4e3Jesse Wilson        assertEquals(254, in.read());
1756ef66494dce45a0b7ec22ec3fb20c60096517a4e3Jesse Wilson        assertEquals(255, in.read());
1757ef66494dce45a0b7ec22ec3fb20c60096517a4e3Jesse Wilson        assertEquals(-1, in.read());
1758ef66494dce45a0b7ec22ec3fb20c60096517a4e3Jesse Wilson    }
1759ef66494dce45a0b7ec22ec3fb20c60096517a4e3Jesse Wilson
1760f29ad8a60254345d1943d1b3836482395a7c916fJesse Wilson    public void testFlushAfterStreamTransmittedWithChunkedEncoding() throws IOException {
1761f29ad8a60254345d1943d1b3836482395a7c916fJesse Wilson        testFlushAfterStreamTransmitted(TransferKind.CHUNKED);
1762f29ad8a60254345d1943d1b3836482395a7c916fJesse Wilson    }
1763f29ad8a60254345d1943d1b3836482395a7c916fJesse Wilson
1764f29ad8a60254345d1943d1b3836482395a7c916fJesse Wilson    public void testFlushAfterStreamTransmittedWithFixedLength() throws IOException {
1765f29ad8a60254345d1943d1b3836482395a7c916fJesse Wilson        testFlushAfterStreamTransmitted(TransferKind.FIXED_LENGTH);
1766f29ad8a60254345d1943d1b3836482395a7c916fJesse Wilson    }
1767f29ad8a60254345d1943d1b3836482395a7c916fJesse Wilson
1768f29ad8a60254345d1943d1b3836482395a7c916fJesse Wilson    public void testFlushAfterStreamTransmittedWithNoLengthHeaders() throws IOException {
1769f29ad8a60254345d1943d1b3836482395a7c916fJesse Wilson        testFlushAfterStreamTransmitted(TransferKind.END_OF_STREAM);
1770f29ad8a60254345d1943d1b3836482395a7c916fJesse Wilson    }
1771f29ad8a60254345d1943d1b3836482395a7c916fJesse Wilson
1772f29ad8a60254345d1943d1b3836482395a7c916fJesse Wilson    /**
1773f29ad8a60254345d1943d1b3836482395a7c916fJesse Wilson     * We explicitly permit apps to close the upload stream even after it has
1774f29ad8a60254345d1943d1b3836482395a7c916fJesse Wilson     * been transmitted.  We also permit flush so that buffered streams can
1775f29ad8a60254345d1943d1b3836482395a7c916fJesse Wilson     * do a no-op flush when they are closed. http://b/3038470
1776f29ad8a60254345d1943d1b3836482395a7c916fJesse Wilson     */
1777f29ad8a60254345d1943d1b3836482395a7c916fJesse Wilson    private void testFlushAfterStreamTransmitted(TransferKind transferKind) throws IOException {
1778f29ad8a60254345d1943d1b3836482395a7c916fJesse Wilson        server.enqueue(new MockResponse().setBody("abc"));
1779f29ad8a60254345d1943d1b3836482395a7c916fJesse Wilson        server.play();
1780f29ad8a60254345d1943d1b3836482395a7c916fJesse Wilson
1781f29ad8a60254345d1943d1b3836482395a7c916fJesse Wilson        HttpURLConnection connection = (HttpURLConnection) server.getUrl("/").openConnection();
1782f29ad8a60254345d1943d1b3836482395a7c916fJesse Wilson        connection.setDoOutput(true);
1783f29ad8a60254345d1943d1b3836482395a7c916fJesse Wilson        byte[] upload = "def".getBytes("UTF-8");
1784f29ad8a60254345d1943d1b3836482395a7c916fJesse Wilson
1785f29ad8a60254345d1943d1b3836482395a7c916fJesse Wilson        if (transferKind == TransferKind.CHUNKED) {
1786f29ad8a60254345d1943d1b3836482395a7c916fJesse Wilson            connection.setChunkedStreamingMode(0);
1787f29ad8a60254345d1943d1b3836482395a7c916fJesse Wilson        } else if (transferKind == TransferKind.FIXED_LENGTH) {
1788f29ad8a60254345d1943d1b3836482395a7c916fJesse Wilson            connection.setFixedLengthStreamingMode(upload.length);
1789f29ad8a60254345d1943d1b3836482395a7c916fJesse Wilson        }
1790f29ad8a60254345d1943d1b3836482395a7c916fJesse Wilson
1791f29ad8a60254345d1943d1b3836482395a7c916fJesse Wilson        OutputStream out = connection.getOutputStream();
1792f29ad8a60254345d1943d1b3836482395a7c916fJesse Wilson        out.write(upload);
1793f29ad8a60254345d1943d1b3836482395a7c916fJesse Wilson        assertEquals("abc", readAscii(connection.getInputStream(), Integer.MAX_VALUE));
1794f29ad8a60254345d1943d1b3836482395a7c916fJesse Wilson
1795f29ad8a60254345d1943d1b3836482395a7c916fJesse Wilson        out.flush(); // dubious but permitted
1796f29ad8a60254345d1943d1b3836482395a7c916fJesse Wilson        try {
1797f29ad8a60254345d1943d1b3836482395a7c916fJesse Wilson            out.write("ghi".getBytes("UTF-8"));
1798f29ad8a60254345d1943d1b3836482395a7c916fJesse Wilson            fail();
1799f29ad8a60254345d1943d1b3836482395a7c916fJesse Wilson        } catch (IOException expected) {
1800f29ad8a60254345d1943d1b3836482395a7c916fJesse Wilson        }
1801f29ad8a60254345d1943d1b3836482395a7c916fJesse Wilson    }
1802f29ad8a60254345d1943d1b3836482395a7c916fJesse Wilson
1803c6dae581716b9362a5c7f166c80a7f2b46ed1124Jesse Wilson    public void testGetHeadersThrows() throws IOException {
1804e942f46f10bb9384a1b186b3d7b74f9704c57090Jesse Wilson        server.enqueue(new MockResponse().setSocketPolicy(DISCONNECT_AT_START));
1805c6dae581716b9362a5c7f166c80a7f2b46ed1124Jesse Wilson        server.play();
1806c6dae581716b9362a5c7f166c80a7f2b46ed1124Jesse Wilson
1807c6dae581716b9362a5c7f166c80a7f2b46ed1124Jesse Wilson        HttpURLConnection connection = (HttpURLConnection) server.getUrl("/").openConnection();
1808c6dae581716b9362a5c7f166c80a7f2b46ed1124Jesse Wilson        try {
1809c6dae581716b9362a5c7f166c80a7f2b46ed1124Jesse Wilson            connection.getInputStream();
1810c6dae581716b9362a5c7f166c80a7f2b46ed1124Jesse Wilson            fail();
1811c6dae581716b9362a5c7f166c80a7f2b46ed1124Jesse Wilson        } catch (IOException expected) {
1812c6dae581716b9362a5c7f166c80a7f2b46ed1124Jesse Wilson        }
1813c6dae581716b9362a5c7f166c80a7f2b46ed1124Jesse Wilson
1814c6dae581716b9362a5c7f166c80a7f2b46ed1124Jesse Wilson        try {
1815c6dae581716b9362a5c7f166c80a7f2b46ed1124Jesse Wilson            connection.getInputStream();
1816c6dae581716b9362a5c7f166c80a7f2b46ed1124Jesse Wilson            fail();
1817f29ad8a60254345d1943d1b3836482395a7c916fJesse Wilson        } catch (IOException expected) {
1818f29ad8a60254345d1943d1b3836482395a7c916fJesse Wilson        }
1819f29ad8a60254345d1943d1b3836482395a7c916fJesse Wilson    }
1820f29ad8a60254345d1943d1b3836482395a7c916fJesse Wilson
1821b7f4d6c3968c372767b2510f38a3d506067aced6Jesse Wilson    public void testGetKeepAlive() throws Exception {
1822b7f4d6c3968c372767b2510f38a3d506067aced6Jesse Wilson        MockWebServer server = new MockWebServer();
1823b7f4d6c3968c372767b2510f38a3d506067aced6Jesse Wilson        server.enqueue(new MockResponse().setBody("ABC"));
1824b7f4d6c3968c372767b2510f38a3d506067aced6Jesse Wilson        server.play();
1825b7f4d6c3968c372767b2510f38a3d506067aced6Jesse Wilson
1826b7f4d6c3968c372767b2510f38a3d506067aced6Jesse Wilson        // The request should work once and then fail
1827b7f4d6c3968c372767b2510f38a3d506067aced6Jesse Wilson        URLConnection connection = server.getUrl("").openConnection();
1828b7f4d6c3968c372767b2510f38a3d506067aced6Jesse Wilson        InputStream input = connection.getInputStream();
1829b7f4d6c3968c372767b2510f38a3d506067aced6Jesse Wilson        assertEquals("ABC", readAscii(input, Integer.MAX_VALUE));
1830b7f4d6c3968c372767b2510f38a3d506067aced6Jesse Wilson        input.close();
1831b7f4d6c3968c372767b2510f38a3d506067aced6Jesse Wilson        try {
1832b7f4d6c3968c372767b2510f38a3d506067aced6Jesse Wilson            server.getUrl("").openConnection().getInputStream();
1833b7f4d6c3968c372767b2510f38a3d506067aced6Jesse Wilson            fail();
1834b7f4d6c3968c372767b2510f38a3d506067aced6Jesse Wilson        } catch (ConnectException expected) {
1835b7f4d6c3968c372767b2510f38a3d506067aced6Jesse Wilson        }
1836b7f4d6c3968c372767b2510f38a3d506067aced6Jesse Wilson    }
1837b7f4d6c3968c372767b2510f38a3d506067aced6Jesse Wilson
1838b7f4d6c3968c372767b2510f38a3d506067aced6Jesse Wilson    /**
1839d1b5e5da828434388e486a388710d21e4306dae0Jesse Wilson     * This test goes through the exhaustive set of interesting ASCII characters
1840d1b5e5da828434388e486a388710d21e4306dae0Jesse Wilson     * because most of those characters are interesting in some way according to
1841d1b5e5da828434388e486a388710d21e4306dae0Jesse Wilson     * RFC 2396 and RFC 2732. http://b/1158780
1842b7f4d6c3968c372767b2510f38a3d506067aced6Jesse Wilson     */
1843d1b5e5da828434388e486a388710d21e4306dae0Jesse Wilson    public void testLenientUrlToUri() throws Exception {
1844d1b5e5da828434388e486a388710d21e4306dae0Jesse Wilson        // alphanum
1845d1b5e5da828434388e486a388710d21e4306dae0Jesse Wilson        testUrlToUriMapping("abzABZ09", "abzABZ09", "abzABZ09", "abzABZ09", "abzABZ09");
1846d1b5e5da828434388e486a388710d21e4306dae0Jesse Wilson
1847d1b5e5da828434388e486a388710d21e4306dae0Jesse Wilson        // control characters
1848d1b5e5da828434388e486a388710d21e4306dae0Jesse Wilson        testUrlToUriMapping("\u0001", "%01", "%01", "%01", "%01");
1849d1b5e5da828434388e486a388710d21e4306dae0Jesse Wilson        testUrlToUriMapping("\u001f", "%1F", "%1F", "%1F", "%1F");
1850d1b5e5da828434388e486a388710d21e4306dae0Jesse Wilson
1851d1b5e5da828434388e486a388710d21e4306dae0Jesse Wilson        // ascii characters
1852d1b5e5da828434388e486a388710d21e4306dae0Jesse Wilson        testUrlToUriMapping("%20", "%20", "%20", "%20", "%20");
1853d1b5e5da828434388e486a388710d21e4306dae0Jesse Wilson        testUrlToUriMapping("%20", "%20", "%20", "%20", "%20");
1854d1b5e5da828434388e486a388710d21e4306dae0Jesse Wilson        testUrlToUriMapping(" ", "%20", "%20", "%20", "%20");
1855d1b5e5da828434388e486a388710d21e4306dae0Jesse Wilson        testUrlToUriMapping("!", "!", "!", "!", "!");
1856d1b5e5da828434388e486a388710d21e4306dae0Jesse Wilson        testUrlToUriMapping("\"", "%22", "%22", "%22", "%22");
1857d1b5e5da828434388e486a388710d21e4306dae0Jesse Wilson        testUrlToUriMapping("#", null, null, null, "%23");
1858d1b5e5da828434388e486a388710d21e4306dae0Jesse Wilson        testUrlToUriMapping("$", "$", "$", "$", "$");
1859d1b5e5da828434388e486a388710d21e4306dae0Jesse Wilson        testUrlToUriMapping("&", "&", "&", "&", "&");
1860d1b5e5da828434388e486a388710d21e4306dae0Jesse Wilson        testUrlToUriMapping("'", "'", "'", "'", "'");
1861d1b5e5da828434388e486a388710d21e4306dae0Jesse Wilson        testUrlToUriMapping("(", "(", "(", "(", "(");
1862d1b5e5da828434388e486a388710d21e4306dae0Jesse Wilson        testUrlToUriMapping(")", ")", ")", ")", ")");
1863d1b5e5da828434388e486a388710d21e4306dae0Jesse Wilson        testUrlToUriMapping("*", "*", "*", "*", "*");
1864d1b5e5da828434388e486a388710d21e4306dae0Jesse Wilson        testUrlToUriMapping("+", "+", "+", "+", "+");
1865d1b5e5da828434388e486a388710d21e4306dae0Jesse Wilson        testUrlToUriMapping(",", ",", ",", ",", ",");
1866d1b5e5da828434388e486a388710d21e4306dae0Jesse Wilson        testUrlToUriMapping("-", "-", "-", "-", "-");
1867d1b5e5da828434388e486a388710d21e4306dae0Jesse Wilson        testUrlToUriMapping(".", ".", ".", ".", ".");
1868d1b5e5da828434388e486a388710d21e4306dae0Jesse Wilson        testUrlToUriMapping("/", null, "/", "/", "/");
1869d1b5e5da828434388e486a388710d21e4306dae0Jesse Wilson        testUrlToUriMapping(":", null, ":", ":", ":");
1870d1b5e5da828434388e486a388710d21e4306dae0Jesse Wilson        testUrlToUriMapping(";", ";", ";", ";", ";");
1871d1b5e5da828434388e486a388710d21e4306dae0Jesse Wilson        testUrlToUriMapping("<", "%3C", "%3C", "%3C", "%3C");
1872d1b5e5da828434388e486a388710d21e4306dae0Jesse Wilson        testUrlToUriMapping("=", "=", "=", "=", "=");
1873d1b5e5da828434388e486a388710d21e4306dae0Jesse Wilson        testUrlToUriMapping(">", "%3E", "%3E", "%3E", "%3E");
1874d1b5e5da828434388e486a388710d21e4306dae0Jesse Wilson        testUrlToUriMapping("?", null, null, "?", "?");
1875d1b5e5da828434388e486a388710d21e4306dae0Jesse Wilson        testUrlToUriMapping("@", "@", "@", "@", "@");
1876d1b5e5da828434388e486a388710d21e4306dae0Jesse Wilson        testUrlToUriMapping("[", null, "%5B", null, "%5B");
1877d1b5e5da828434388e486a388710d21e4306dae0Jesse Wilson        testUrlToUriMapping("\\", "%5C", "%5C", "%5C", "%5C");
1878d1b5e5da828434388e486a388710d21e4306dae0Jesse Wilson        testUrlToUriMapping("]", null, "%5D", null, "%5D");
1879d1b5e5da828434388e486a388710d21e4306dae0Jesse Wilson        testUrlToUriMapping("^", "%5E", "%5E", "%5E", "%5E");
1880d1b5e5da828434388e486a388710d21e4306dae0Jesse Wilson        testUrlToUriMapping("_", "_", "_", "_", "_");
1881d1b5e5da828434388e486a388710d21e4306dae0Jesse Wilson        testUrlToUriMapping("`", "%60", "%60", "%60", "%60");
1882d1b5e5da828434388e486a388710d21e4306dae0Jesse Wilson        testUrlToUriMapping("{", "%7B", "%7B", "%7B", "%7B");
1883d1b5e5da828434388e486a388710d21e4306dae0Jesse Wilson        testUrlToUriMapping("|", "%7C", "%7C", "%7C", "%7C");
1884d1b5e5da828434388e486a388710d21e4306dae0Jesse Wilson        testUrlToUriMapping("}", "%7D", "%7D", "%7D", "%7D");
1885d1b5e5da828434388e486a388710d21e4306dae0Jesse Wilson        testUrlToUriMapping("~", "~", "~", "~", "~");
1886d1b5e5da828434388e486a388710d21e4306dae0Jesse Wilson        testUrlToUriMapping("~", "~", "~", "~", "~");
1887d1b5e5da828434388e486a388710d21e4306dae0Jesse Wilson        testUrlToUriMapping("\u007f", "%7F", "%7F", "%7F", "%7F");
1888d1b5e5da828434388e486a388710d21e4306dae0Jesse Wilson
1889d1b5e5da828434388e486a388710d21e4306dae0Jesse Wilson        // beyond ascii
1890d1b5e5da828434388e486a388710d21e4306dae0Jesse Wilson        testUrlToUriMapping("\u0080", "%C2%80", "%C2%80", "%C2%80", "%C2%80");
1891d1b5e5da828434388e486a388710d21e4306dae0Jesse Wilson        testUrlToUriMapping("\u20ac", "\u20ac", "\u20ac", "\u20ac", "\u20ac");
189232559028b14b9b321b10eede050afd554a376569Jesse Wilson        testUrlToUriMapping("\ud842\udf9f",
189332559028b14b9b321b10eede050afd554a376569Jesse Wilson                "\ud842\udf9f", "\ud842\udf9f", "\ud842\udf9f", "\ud842\udf9f");
1894d1b5e5da828434388e486a388710d21e4306dae0Jesse Wilson    }
1895d1b5e5da828434388e486a388710d21e4306dae0Jesse Wilson
1896d1b5e5da828434388e486a388710d21e4306dae0Jesse Wilson    public void testLenientUrlToUriNul() throws Exception {
1897d1b5e5da828434388e486a388710d21e4306dae0Jesse Wilson        testUrlToUriMapping("\u0000", "%00", "%00", "%00", "%00"); // RI fails this
1898d1b5e5da828434388e486a388710d21e4306dae0Jesse Wilson    }
1899d1b5e5da828434388e486a388710d21e4306dae0Jesse Wilson
1900d1b5e5da828434388e486a388710d21e4306dae0Jesse Wilson    private void testUrlToUriMapping(String string, String asAuthority, String asFile,
1901d1b5e5da828434388e486a388710d21e4306dae0Jesse Wilson            String asQuery, String asFragment) throws Exception {
1902d1b5e5da828434388e486a388710d21e4306dae0Jesse Wilson        if (asAuthority != null) {
1903d1b5e5da828434388e486a388710d21e4306dae0Jesse Wilson            assertEquals("http://host" + asAuthority + ".tld/",
1904d1b5e5da828434388e486a388710d21e4306dae0Jesse Wilson                    backdoorUrlToUri(new URL("http://host" + string + ".tld/")).toString());
1905d1b5e5da828434388e486a388710d21e4306dae0Jesse Wilson        }
1906d1b5e5da828434388e486a388710d21e4306dae0Jesse Wilson        if (asFile != null) {
1907d1b5e5da828434388e486a388710d21e4306dae0Jesse Wilson            assertEquals("http://host.tld/file" + asFile + "/",
1908d1b5e5da828434388e486a388710d21e4306dae0Jesse Wilson                    backdoorUrlToUri(new URL("http://host.tld/file" + string + "/")).toString());
1909d1b5e5da828434388e486a388710d21e4306dae0Jesse Wilson        }
1910d1b5e5da828434388e486a388710d21e4306dae0Jesse Wilson        if (asQuery != null) {
1911d1b5e5da828434388e486a388710d21e4306dae0Jesse Wilson            assertEquals("http://host.tld/file?q" + asQuery + "=x",
1912d1b5e5da828434388e486a388710d21e4306dae0Jesse Wilson                    backdoorUrlToUri(new URL("http://host.tld/file?q" + string + "=x")).toString());
1913d1b5e5da828434388e486a388710d21e4306dae0Jesse Wilson        }
1914d1b5e5da828434388e486a388710d21e4306dae0Jesse Wilson        assertEquals("http://host.tld/file#" + asFragment + "-x",
1915d1b5e5da828434388e486a388710d21e4306dae0Jesse Wilson                backdoorUrlToUri(new URL("http://host.tld/file#" + asFragment + "-x")).toString());
1916d1b5e5da828434388e486a388710d21e4306dae0Jesse Wilson    }
1917b7f4d6c3968c372767b2510f38a3d506067aced6Jesse Wilson
1918d1b5e5da828434388e486a388710d21e4306dae0Jesse Wilson    /**
1919d1b5e5da828434388e486a388710d21e4306dae0Jesse Wilson     * Exercises HttpURLConnection to convert URL to a URI. Unlike URL#toURI,
1920d1b5e5da828434388e486a388710d21e4306dae0Jesse Wilson     * HttpURLConnection recovers from URLs with unescaped but unsupported URI
1921d1b5e5da828434388e486a388710d21e4306dae0Jesse Wilson     * characters like '{' and '|' by escaping these characters.
1922d1b5e5da828434388e486a388710d21e4306dae0Jesse Wilson     */
1923d1b5e5da828434388e486a388710d21e4306dae0Jesse Wilson    private URI backdoorUrlToUri(URL url) throws Exception {
1924d1b5e5da828434388e486a388710d21e4306dae0Jesse Wilson        final AtomicReference<URI> uriReference = new AtomicReference<URI>();
1925d1b5e5da828434388e486a388710d21e4306dae0Jesse Wilson
1926d1b5e5da828434388e486a388710d21e4306dae0Jesse Wilson        ResponseCache.setDefault(new ResponseCache() {
1927d1b5e5da828434388e486a388710d21e4306dae0Jesse Wilson            @Override public CacheRequest put(URI uri, URLConnection connection) throws IOException {
1928d1b5e5da828434388e486a388710d21e4306dae0Jesse Wilson                return null;
1929d1b5e5da828434388e486a388710d21e4306dae0Jesse Wilson            }
1930d1b5e5da828434388e486a388710d21e4306dae0Jesse Wilson            @Override public CacheResponse get(URI uri, String requestMethod,
1931d1b5e5da828434388e486a388710d21e4306dae0Jesse Wilson                    Map<String, List<String>> requestHeaders) throws IOException {
1932d1b5e5da828434388e486a388710d21e4306dae0Jesse Wilson                uriReference.set(uri);
1933d1b5e5da828434388e486a388710d21e4306dae0Jesse Wilson                throw new UnsupportedOperationException();
1934d1b5e5da828434388e486a388710d21e4306dae0Jesse Wilson            }
1935d1b5e5da828434388e486a388710d21e4306dae0Jesse Wilson        });
1936d1b5e5da828434388e486a388710d21e4306dae0Jesse Wilson
1937d1b5e5da828434388e486a388710d21e4306dae0Jesse Wilson        try {
1938d1b5e5da828434388e486a388710d21e4306dae0Jesse Wilson            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
1939d1b5e5da828434388e486a388710d21e4306dae0Jesse Wilson            connection.getResponseCode();
1940d1b5e5da828434388e486a388710d21e4306dae0Jesse Wilson        } catch (Exception expected) {
1941d1b5e5da828434388e486a388710d21e4306dae0Jesse Wilson        }
1942d1b5e5da828434388e486a388710d21e4306dae0Jesse Wilson
1943d1b5e5da828434388e486a388710d21e4306dae0Jesse Wilson        return uriReference.get();
1944b7f4d6c3968c372767b2510f38a3d506067aced6Jesse Wilson    }
1945b7f4d6c3968c372767b2510f38a3d506067aced6Jesse Wilson
1946afd9b157f467b7c4f2f0b5592dca72f18d844602Jesse Wilson    /**
1947afd9b157f467b7c4f2f0b5592dca72f18d844602Jesse Wilson     * Don't explode if the cache returns a null body. http://b/3373699
1948afd9b157f467b7c4f2f0b5592dca72f18d844602Jesse Wilson     */
1949afd9b157f467b7c4f2f0b5592dca72f18d844602Jesse Wilson    public void testResponseCacheReturnsNullOutputStream() throws Exception {
1950afd9b157f467b7c4f2f0b5592dca72f18d844602Jesse Wilson        final AtomicBoolean aborted = new AtomicBoolean();
1951afd9b157f467b7c4f2f0b5592dca72f18d844602Jesse Wilson        ResponseCache.setDefault(new ResponseCache() {
1952afd9b157f467b7c4f2f0b5592dca72f18d844602Jesse Wilson            @Override public CacheResponse get(URI uri, String requestMethod,
1953afd9b157f467b7c4f2f0b5592dca72f18d844602Jesse Wilson                    Map<String, List<String>> requestHeaders) throws IOException {
1954afd9b157f467b7c4f2f0b5592dca72f18d844602Jesse Wilson                return null;
1955afd9b157f467b7c4f2f0b5592dca72f18d844602Jesse Wilson            }
1956afd9b157f467b7c4f2f0b5592dca72f18d844602Jesse Wilson            @Override public CacheRequest put(URI uri, URLConnection connection) throws IOException {
1957afd9b157f467b7c4f2f0b5592dca72f18d844602Jesse Wilson                return new CacheRequest() {
1958afd9b157f467b7c4f2f0b5592dca72f18d844602Jesse Wilson                    @Override public void abort() {
1959afd9b157f467b7c4f2f0b5592dca72f18d844602Jesse Wilson                        aborted.set(true);
1960afd9b157f467b7c4f2f0b5592dca72f18d844602Jesse Wilson                    }
1961afd9b157f467b7c4f2f0b5592dca72f18d844602Jesse Wilson                    @Override public OutputStream getBody() throws IOException {
1962afd9b157f467b7c4f2f0b5592dca72f18d844602Jesse Wilson                        return null;
1963afd9b157f467b7c4f2f0b5592dca72f18d844602Jesse Wilson                    }
1964afd9b157f467b7c4f2f0b5592dca72f18d844602Jesse Wilson                };
1965afd9b157f467b7c4f2f0b5592dca72f18d844602Jesse Wilson            }
1966afd9b157f467b7c4f2f0b5592dca72f18d844602Jesse Wilson        });
1967afd9b157f467b7c4f2f0b5592dca72f18d844602Jesse Wilson
1968afd9b157f467b7c4f2f0b5592dca72f18d844602Jesse Wilson        server.enqueue(new MockResponse().setBody("abcdef"));
1969afd9b157f467b7c4f2f0b5592dca72f18d844602Jesse Wilson        server.play();
1970afd9b157f467b7c4f2f0b5592dca72f18d844602Jesse Wilson
1971afd9b157f467b7c4f2f0b5592dca72f18d844602Jesse Wilson        HttpURLConnection connection = (HttpURLConnection) server.getUrl("/").openConnection();
1972afd9b157f467b7c4f2f0b5592dca72f18d844602Jesse Wilson        InputStream in = connection.getInputStream();
1973afd9b157f467b7c4f2f0b5592dca72f18d844602Jesse Wilson        assertEquals("abc", readAscii(in, 3));
1974afd9b157f467b7c4f2f0b5592dca72f18d844602Jesse Wilson        in.close();
1975afd9b157f467b7c4f2f0b5592dca72f18d844602Jesse Wilson        assertFalse(aborted.get()); // The best behavior is ambiguous, but RI 6 doesn't abort here
1976afd9b157f467b7c4f2f0b5592dca72f18d844602Jesse Wilson    }
1977d1b5e5da828434388e486a388710d21e4306dae0Jesse Wilson
19785e8b5a55eda914b67c62b4e77152922d5c77eb68Jesse Wilson
19795e8b5a55eda914b67c62b4e77152922d5c77eb68Jesse Wilson    /**
19805e8b5a55eda914b67c62b4e77152922d5c77eb68Jesse Wilson     * http://code.google.com/p/android/issues/detail?id=14562
19815e8b5a55eda914b67c62b4e77152922d5c77eb68Jesse Wilson     */
19825e8b5a55eda914b67c62b4e77152922d5c77eb68Jesse Wilson    public void testReadAfterLastByte() throws Exception {
19835e8b5a55eda914b67c62b4e77152922d5c77eb68Jesse Wilson        server.enqueue(new MockResponse()
19845e8b5a55eda914b67c62b4e77152922d5c77eb68Jesse Wilson                .setBody("ABC")
19855e8b5a55eda914b67c62b4e77152922d5c77eb68Jesse Wilson                .clearHeaders()
19865e8b5a55eda914b67c62b4e77152922d5c77eb68Jesse Wilson                .addHeader("Connection: close")
19875e8b5a55eda914b67c62b4e77152922d5c77eb68Jesse Wilson                .setSocketPolicy(SocketPolicy.DISCONNECT_AT_END));
19885e8b5a55eda914b67c62b4e77152922d5c77eb68Jesse Wilson        server.play();
19895e8b5a55eda914b67c62b4e77152922d5c77eb68Jesse Wilson
19905e8b5a55eda914b67c62b4e77152922d5c77eb68Jesse Wilson        HttpURLConnection connection = (HttpURLConnection) server.getUrl("/").openConnection();
19915e8b5a55eda914b67c62b4e77152922d5c77eb68Jesse Wilson        InputStream in = connection.getInputStream();
19925e8b5a55eda914b67c62b4e77152922d5c77eb68Jesse Wilson        assertEquals("ABC", readAscii(in, 3));
19935e8b5a55eda914b67c62b4e77152922d5c77eb68Jesse Wilson        assertEquals(-1, in.read());
1994bc4c79c6a2059003f695f7ad204de36700e8d701Jesse Wilson        assertEquals(-1, in.read()); // throws IOException in Gingerbread
1995bc4c79c6a2059003f695f7ad204de36700e8d701Jesse Wilson    }
1996bc4c79c6a2059003f695f7ad204de36700e8d701Jesse Wilson
1997ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson    public void testGetContent() throws Exception {
1998ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson        server.enqueue(new MockResponse().setBody("A"));
1999ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson        server.play();
2000ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson        HttpURLConnection connection = (HttpURLConnection) server.getUrl("/").openConnection();
2001ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson        InputStream in = (InputStream) connection.getContent();
2002ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson        assertEquals("A", readAscii(in, Integer.MAX_VALUE));
2003ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson    }
2004ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson
2005ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson    public void testGetContentOfType() throws Exception {
2006ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson        server.enqueue(new MockResponse().setBody("A"));
2007ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson        server.play();
2008ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson        HttpURLConnection connection = (HttpURLConnection) server.getUrl("/").openConnection();
2009ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson        try {
2010ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson            connection.getContent(null);
2011ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson            fail();
2012ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson        } catch (NullPointerException expected) {
2013ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson        }
2014ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson        try {
2015ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson            connection.getContent(new Class[] { null });
2016ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson            fail();
2017ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson        } catch (NullPointerException expected) {
2018ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson        }
2019ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson        assertNull(connection.getContent(new Class[] { getClass() }));
2020ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson        connection.disconnect();
2021ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson    }
2022ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson
2023ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson    public void testGetOutputStreamOnGetFails() throws Exception {
2024ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson        server.enqueue(new MockResponse());
2025ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson        server.play();
2026ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson        HttpURLConnection connection = (HttpURLConnection) server.getUrl("/").openConnection();
2027ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson        try {
2028ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson            connection.getOutputStream();
2029ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson            fail();
2030ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson        } catch (ProtocolException expected) {
2031ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson        }
2032ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson    }
2033ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson
2034ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson    public void testGetOutputAfterGetInputStreamFails() throws Exception {
2035ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson        server.enqueue(new MockResponse());
2036ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson        server.play();
2037ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson        HttpURLConnection connection = (HttpURLConnection) server.getUrl("/").openConnection();
2038ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson        connection.setDoOutput(true);
2039ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson        try {
2040ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson            connection.getInputStream();
2041ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson            connection.getOutputStream();
2042ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson            fail();
2043ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson        } catch (ProtocolException expected) {
2044ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson        }
2045ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson    }
2046ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson
2047ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson    public void testSetDoOutputOrDoInputAfterConnectFails() throws Exception {
2048ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson        server.enqueue(new MockResponse());
2049ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson        server.play();
2050ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson        HttpURLConnection connection = (HttpURLConnection) server.getUrl("/").openConnection();
2051ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson        connection.connect();
2052ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson        try {
2053ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson            connection.setDoOutput(true);
2054ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson            fail();
2055ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson        } catch (IllegalStateException expected) {
2056ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson        }
2057ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson        try {
2058ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson            connection.setDoInput(true);
2059ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson            fail();
2060ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson        } catch (IllegalStateException expected) {
2061ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson        }
2062ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson        connection.disconnect();
2063ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson    }
2064ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson
2065ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson    public void testClientSendsContentLength() throws Exception {
2066ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson        server.enqueue(new MockResponse().setBody("A"));
2067ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson        server.play();
2068ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson        HttpURLConnection connection = (HttpURLConnection) server.getUrl("/").openConnection();
2069ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson        connection.setDoOutput(true);
2070ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson        OutputStream out = connection.getOutputStream();
2071ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson        out.write(new byte[] { 'A', 'B', 'C' });
2072ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson        out.close();
2073ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson        assertEquals("A", readAscii(connection.getInputStream(), Integer.MAX_VALUE));
2074ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson        RecordedRequest request = server.takeRequest();
2075ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson        assertContains(request.getHeaders(), "Content-Length: 3");
2076ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson    }
2077ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson
2078ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson    public void testGetContentLengthConnects() throws Exception {
2079ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson        server.enqueue(new MockResponse().setBody("ABC"));
2080ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson        server.play();
2081ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson        HttpURLConnection connection = (HttpURLConnection) server.getUrl("/").openConnection();
2082ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson        assertEquals(3, connection.getContentLength());
2083ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson        connection.disconnect();
2084ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson    }
2085ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson
2086ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson    public void testGetContentTypeConnects() throws Exception {
2087ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson        server.enqueue(new MockResponse()
2088ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson                .addHeader("Content-Type: text/plain")
2089ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson                .setBody("ABC"));
2090ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson        server.play();
2091ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson        HttpURLConnection connection = (HttpURLConnection) server.getUrl("/").openConnection();
2092ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson        assertEquals("text/plain", connection.getContentType());
2093ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson        connection.disconnect();
2094ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson    }
2095ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson
2096ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson    public void testGetContentEncodingConnects() throws Exception {
2097ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson        server.enqueue(new MockResponse()
2098ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson                .addHeader("Content-Encoding: identity")
2099ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson                .setBody("ABC"));
2100ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson        server.play();
2101ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson        HttpURLConnection connection = (HttpURLConnection) server.getUrl("/").openConnection();
2102ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson        assertEquals("identity", connection.getContentEncoding());
2103ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson        connection.disconnect();
2104ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson    }
2105ec6163ceac64902ccde3259e8a426f0f9ad6a88cJesse Wilson
21065292410e4ebf7fb5149eefd2f52fcb94c46690a6Jesse Wilson    // http://b/4361656
21075292410e4ebf7fb5149eefd2f52fcb94c46690a6Jesse Wilson    public void testUrlContainsQueryButNoPath() throws Exception {
21085292410e4ebf7fb5149eefd2f52fcb94c46690a6Jesse Wilson        server.enqueue(new MockResponse().setBody("A"));
21095292410e4ebf7fb5149eefd2f52fcb94c46690a6Jesse Wilson        server.play();
21105292410e4ebf7fb5149eefd2f52fcb94c46690a6Jesse Wilson        URL url = new URL("http", server.getHostName(), server.getPort(), "?query");
21115292410e4ebf7fb5149eefd2f52fcb94c46690a6Jesse Wilson        assertEquals("A", readAscii(url.openConnection().getInputStream(), Integer.MAX_VALUE));
21125292410e4ebf7fb5149eefd2f52fcb94c46690a6Jesse Wilson        RecordedRequest request = server.takeRequest();
21135292410e4ebf7fb5149eefd2f52fcb94c46690a6Jesse Wilson        assertEquals("GET /?query HTTP/1.1", request.getRequestLine());
21145292410e4ebf7fb5149eefd2f52fcb94c46690a6Jesse Wilson    }
21155292410e4ebf7fb5149eefd2f52fcb94c46690a6Jesse Wilson
211625a753691a80186cd4d7086b12c0e52225d95897Jesse Wilson    // http://code.google.com/p/android/issues/detail?id=20442
211725a753691a80186cd4d7086b12c0e52225d95897Jesse Wilson    public void testInputStreamAvailableWithChunkedEncoding() throws Exception {
211825a753691a80186cd4d7086b12c0e52225d95897Jesse Wilson        testInputStreamAvailable(TransferKind.CHUNKED);
211925a753691a80186cd4d7086b12c0e52225d95897Jesse Wilson    }
212025a753691a80186cd4d7086b12c0e52225d95897Jesse Wilson
212125a753691a80186cd4d7086b12c0e52225d95897Jesse Wilson    public void testInputStreamAvailableWithContentLengthHeader() throws Exception {
212225a753691a80186cd4d7086b12c0e52225d95897Jesse Wilson        testInputStreamAvailable(TransferKind.FIXED_LENGTH);
212325a753691a80186cd4d7086b12c0e52225d95897Jesse Wilson    }
212425a753691a80186cd4d7086b12c0e52225d95897Jesse Wilson
212525a753691a80186cd4d7086b12c0e52225d95897Jesse Wilson    public void testInputStreamAvailableWithNoLengthHeaders() throws Exception {
212625a753691a80186cd4d7086b12c0e52225d95897Jesse Wilson        testInputStreamAvailable(TransferKind.END_OF_STREAM);
212725a753691a80186cd4d7086b12c0e52225d95897Jesse Wilson    }
212825a753691a80186cd4d7086b12c0e52225d95897Jesse Wilson
212925a753691a80186cd4d7086b12c0e52225d95897Jesse Wilson    private void testInputStreamAvailable(TransferKind transferKind) throws IOException {
213025a753691a80186cd4d7086b12c0e52225d95897Jesse Wilson        String body = "ABCDEFGH";
213125a753691a80186cd4d7086b12c0e52225d95897Jesse Wilson        MockResponse response = new MockResponse();
213225a753691a80186cd4d7086b12c0e52225d95897Jesse Wilson        transferKind.setBody(response, body, 4);
213325a753691a80186cd4d7086b12c0e52225d95897Jesse Wilson        server.enqueue(response);
213425a753691a80186cd4d7086b12c0e52225d95897Jesse Wilson        server.play();
213525a753691a80186cd4d7086b12c0e52225d95897Jesse Wilson        URLConnection connection = server.getUrl("/").openConnection();
213625a753691a80186cd4d7086b12c0e52225d95897Jesse Wilson        InputStream in = connection.getInputStream();
213725a753691a80186cd4d7086b12c0e52225d95897Jesse Wilson        for (int i = 0; i < body.length(); i++) {
213825a753691a80186cd4d7086b12c0e52225d95897Jesse Wilson            assertTrue(in.available() >= 0);
213925a753691a80186cd4d7086b12c0e52225d95897Jesse Wilson            assertEquals(body.charAt(i), in.read());
214025a753691a80186cd4d7086b12c0e52225d95897Jesse Wilson        }
214125a753691a80186cd4d7086b12c0e52225d95897Jesse Wilson        assertEquals(0, in.available());
214225a753691a80186cd4d7086b12c0e52225d95897Jesse Wilson        assertEquals(-1, in.read());
214325a753691a80186cd4d7086b12c0e52225d95897Jesse Wilson    }
214425a753691a80186cd4d7086b12c0e52225d95897Jesse Wilson
2145deb26711801f9bfafcd5cad20963b3c3913404fdElliott Hughes    // http://code.google.com/p/android/issues/detail?id=28095
2146deb26711801f9bfafcd5cad20963b3c3913404fdElliott Hughes    public void testInvalidIpv4Address() throws Exception {
2147deb26711801f9bfafcd5cad20963b3c3913404fdElliott Hughes        try {
2148deb26711801f9bfafcd5cad20963b3c3913404fdElliott Hughes            URI uri = new URI("http://1111.111.111.111/index.html");
2149deb26711801f9bfafcd5cad20963b3c3913404fdElliott Hughes            uri.toURL().openConnection().connect();
2150deb26711801f9bfafcd5cad20963b3c3913404fdElliott Hughes            fail();
2151deb26711801f9bfafcd5cad20963b3c3913404fdElliott Hughes        } catch (UnknownHostException expected) {
2152deb26711801f9bfafcd5cad20963b3c3913404fdElliott Hughes        }
2153deb26711801f9bfafcd5cad20963b3c3913404fdElliott Hughes    }
2154deb26711801f9bfafcd5cad20963b3c3913404fdElliott Hughes
2155d0d626655f1d452070d3116678037e8759f807f4Jesse Wilson    // http://code.google.com/p/android/issues/detail?id=16895
2156d0d626655f1d452070d3116678037e8759f807f4Jesse Wilson    public void testUrlWithSpaceInHost() throws Exception {
2157d0d626655f1d452070d3116678037e8759f807f4Jesse Wilson        URLConnection urlConnection = new URL("http://and roid.com/").openConnection();
2158d0d626655f1d452070d3116678037e8759f807f4Jesse Wilson        try {
2159d0d626655f1d452070d3116678037e8759f807f4Jesse Wilson            urlConnection.getInputStream();
2160d0d626655f1d452070d3116678037e8759f807f4Jesse Wilson            fail();
2161d0d626655f1d452070d3116678037e8759f807f4Jesse Wilson        } catch (UnknownHostException expected) {
2162d0d626655f1d452070d3116678037e8759f807f4Jesse Wilson        }
2163d0d626655f1d452070d3116678037e8759f807f4Jesse Wilson    }
2164d0d626655f1d452070d3116678037e8759f807f4Jesse Wilson
2165d0d626655f1d452070d3116678037e8759f807f4Jesse Wilson    public void testUrlWithSpaceInHostViaHttpProxy() throws Exception {
2166d0d626655f1d452070d3116678037e8759f807f4Jesse Wilson        server.enqueue(new MockResponse());
2167d0d626655f1d452070d3116678037e8759f807f4Jesse Wilson        server.play();
2168d0d626655f1d452070d3116678037e8759f807f4Jesse Wilson        URLConnection urlConnection = new URL("http://and roid.com/")
2169d0d626655f1d452070d3116678037e8759f807f4Jesse Wilson                .openConnection(server.toProxyAddress());
2170d0d626655f1d452070d3116678037e8759f807f4Jesse Wilson        try {
2171d0d626655f1d452070d3116678037e8759f807f4Jesse Wilson            urlConnection.getInputStream();
2172d0d626655f1d452070d3116678037e8759f807f4Jesse Wilson            fail(); // the RI makes a bogus proxy request for "GET http://and roid.com/ HTTP/1.1"
2173d0d626655f1d452070d3116678037e8759f807f4Jesse Wilson        } catch (UnknownHostException expected) {
2174d0d626655f1d452070d3116678037e8759f807f4Jesse Wilson        }
2175d0d626655f1d452070d3116678037e8759f807f4Jesse Wilson    }
2176d0d626655f1d452070d3116678037e8759f807f4Jesse Wilson
2177abe4e615f473b387b1c00a738062a7c428f05a33Jesse Wilson    public void testSslFallback() throws Exception {
2178abe4e615f473b387b1c00a738062a7c428f05a33Jesse Wilson        TestSSLContext testSSLContext = TestSSLContext.create();
2179abe4e615f473b387b1c00a738062a7c428f05a33Jesse Wilson        server.useHttps(testSSLContext.serverContext.getSocketFactory(), false);
2180abe4e615f473b387b1c00a738062a7c428f05a33Jesse Wilson        server.enqueue(new MockResponse().setSocketPolicy(SocketPolicy.FAIL_HANDSHAKE));
2181abe4e615f473b387b1c00a738062a7c428f05a33Jesse Wilson        server.enqueue(new MockResponse().setBody("This required a 2nd handshake"));
2182abe4e615f473b387b1c00a738062a7c428f05a33Jesse Wilson        server.play();
2183abe4e615f473b387b1c00a738062a7c428f05a33Jesse Wilson
2184abe4e615f473b387b1c00a738062a7c428f05a33Jesse Wilson        HttpsURLConnection connection = (HttpsURLConnection) server.getUrl("/").openConnection();
2185abe4e615f473b387b1c00a738062a7c428f05a33Jesse Wilson        connection.setSSLSocketFactory(testSSLContext.clientContext.getSocketFactory());
2186abe4e615f473b387b1c00a738062a7c428f05a33Jesse Wilson        assertEquals("This required a 2nd handshake",
2187abe4e615f473b387b1c00a738062a7c428f05a33Jesse Wilson                readAscii(connection.getInputStream(), Integer.MAX_VALUE));
2188abe4e615f473b387b1c00a738062a7c428f05a33Jesse Wilson
2189abe4e615f473b387b1c00a738062a7c428f05a33Jesse Wilson        RecordedRequest first = server.takeRequest();
2190abe4e615f473b387b1c00a738062a7c428f05a33Jesse Wilson        assertEquals(0, first.getSequenceNumber());
2191abe4e615f473b387b1c00a738062a7c428f05a33Jesse Wilson        RecordedRequest retry = server.takeRequest();
2192abe4e615f473b387b1c00a738062a7c428f05a33Jesse Wilson        assertEquals(0, retry.getSequenceNumber());
2193abe4e615f473b387b1c00a738062a7c428f05a33Jesse Wilson        assertEquals("SSLv3", retry.getSslProtocol());
2194abe4e615f473b387b1c00a738062a7c428f05a33Jesse Wilson    }
2195abe4e615f473b387b1c00a738062a7c428f05a33Jesse Wilson
2196a468471e8ccc2f642d5b2ae3c75873a74267ece2Jesse Wilson    public void testInspectSslBeforeConnect() throws Exception {
2197a468471e8ccc2f642d5b2ae3c75873a74267ece2Jesse Wilson        TestSSLContext testSSLContext = TestSSLContext.create();
2198a468471e8ccc2f642d5b2ae3c75873a74267ece2Jesse Wilson        server.useHttps(testSSLContext.serverContext.getSocketFactory(), false);
2199a468471e8ccc2f642d5b2ae3c75873a74267ece2Jesse Wilson        server.enqueue(new MockResponse());
2200a468471e8ccc2f642d5b2ae3c75873a74267ece2Jesse Wilson        server.play();
2201a468471e8ccc2f642d5b2ae3c75873a74267ece2Jesse Wilson
2202a468471e8ccc2f642d5b2ae3c75873a74267ece2Jesse Wilson        HttpsURLConnection connection = (HttpsURLConnection) server.getUrl("/").openConnection();
2203a468471e8ccc2f642d5b2ae3c75873a74267ece2Jesse Wilson        connection.setSSLSocketFactory(testSSLContext.clientContext.getSocketFactory());
2204a468471e8ccc2f642d5b2ae3c75873a74267ece2Jesse Wilson        assertNotNull(connection.getHostnameVerifier());
2205a468471e8ccc2f642d5b2ae3c75873a74267ece2Jesse Wilson        try {
2206a468471e8ccc2f642d5b2ae3c75873a74267ece2Jesse Wilson            connection.getLocalCertificates();
2207a468471e8ccc2f642d5b2ae3c75873a74267ece2Jesse Wilson            fail();
2208a468471e8ccc2f642d5b2ae3c75873a74267ece2Jesse Wilson        } catch (IllegalStateException expected) {
2209a468471e8ccc2f642d5b2ae3c75873a74267ece2Jesse Wilson        }
2210a468471e8ccc2f642d5b2ae3c75873a74267ece2Jesse Wilson        try {
2211a468471e8ccc2f642d5b2ae3c75873a74267ece2Jesse Wilson            connection.getServerCertificates();
2212a468471e8ccc2f642d5b2ae3c75873a74267ece2Jesse Wilson            fail();
2213a468471e8ccc2f642d5b2ae3c75873a74267ece2Jesse Wilson        } catch (IllegalStateException expected) {
2214a468471e8ccc2f642d5b2ae3c75873a74267ece2Jesse Wilson        }
2215a468471e8ccc2f642d5b2ae3c75873a74267ece2Jesse Wilson        try {
2216a468471e8ccc2f642d5b2ae3c75873a74267ece2Jesse Wilson            connection.getCipherSuite();
2217a468471e8ccc2f642d5b2ae3c75873a74267ece2Jesse Wilson            fail();
2218a468471e8ccc2f642d5b2ae3c75873a74267ece2Jesse Wilson        } catch (IllegalStateException expected) {
2219a468471e8ccc2f642d5b2ae3c75873a74267ece2Jesse Wilson        }
2220a468471e8ccc2f642d5b2ae3c75873a74267ece2Jesse Wilson        try {
2221a468471e8ccc2f642d5b2ae3c75873a74267ece2Jesse Wilson            connection.getPeerPrincipal();
2222a468471e8ccc2f642d5b2ae3c75873a74267ece2Jesse Wilson            fail();
2223a468471e8ccc2f642d5b2ae3c75873a74267ece2Jesse Wilson        } catch (IllegalStateException expected) {
2224a468471e8ccc2f642d5b2ae3c75873a74267ece2Jesse Wilson        }
2225a468471e8ccc2f642d5b2ae3c75873a74267ece2Jesse Wilson    }
2226a468471e8ccc2f642d5b2ae3c75873a74267ece2Jesse Wilson
2227a468471e8ccc2f642d5b2ae3c75873a74267ece2Jesse Wilson    /**
2228a468471e8ccc2f642d5b2ae3c75873a74267ece2Jesse Wilson     * Test that we can inspect the SSL session after connect().
2229a468471e8ccc2f642d5b2ae3c75873a74267ece2Jesse Wilson     * http://code.google.com/p/android/issues/detail?id=24431
2230a468471e8ccc2f642d5b2ae3c75873a74267ece2Jesse Wilson     */
2231a468471e8ccc2f642d5b2ae3c75873a74267ece2Jesse Wilson    public void testInspectSslAfterConnect() throws Exception {
2232a468471e8ccc2f642d5b2ae3c75873a74267ece2Jesse Wilson        TestSSLContext testSSLContext = TestSSLContext.create();
2233a468471e8ccc2f642d5b2ae3c75873a74267ece2Jesse Wilson        server.useHttps(testSSLContext.serverContext.getSocketFactory(), false);
2234a468471e8ccc2f642d5b2ae3c75873a74267ece2Jesse Wilson        server.enqueue(new MockResponse());
2235a468471e8ccc2f642d5b2ae3c75873a74267ece2Jesse Wilson        server.play();
2236a468471e8ccc2f642d5b2ae3c75873a74267ece2Jesse Wilson
2237a468471e8ccc2f642d5b2ae3c75873a74267ece2Jesse Wilson        HttpsURLConnection connection = (HttpsURLConnection) server.getUrl("/").openConnection();
2238a468471e8ccc2f642d5b2ae3c75873a74267ece2Jesse Wilson        connection.setSSLSocketFactory(testSSLContext.clientContext.getSocketFactory());
2239a468471e8ccc2f642d5b2ae3c75873a74267ece2Jesse Wilson        connection.connect();
2240a468471e8ccc2f642d5b2ae3c75873a74267ece2Jesse Wilson        assertNotNull(connection.getHostnameVerifier());
2241a468471e8ccc2f642d5b2ae3c75873a74267ece2Jesse Wilson        assertNull(connection.getLocalCertificates());
2242a468471e8ccc2f642d5b2ae3c75873a74267ece2Jesse Wilson        assertNotNull(connection.getServerCertificates());
2243a468471e8ccc2f642d5b2ae3c75873a74267ece2Jesse Wilson        assertNotNull(connection.getCipherSuite());
2244a468471e8ccc2f642d5b2ae3c75873a74267ece2Jesse Wilson        assertNotNull(connection.getPeerPrincipal());
2245a468471e8ccc2f642d5b2ae3c75873a74267ece2Jesse Wilson    }
2246a468471e8ccc2f642d5b2ae3c75873a74267ece2Jesse Wilson
2247bc4c79c6a2059003f695f7ad204de36700e8d701Jesse Wilson    /**
22480c59055dd24e1659f85d9ff7e2148883f663bd62Jesse Wilson     * Returns a gzipped copy of {@code bytes}.
2249deb236fb06f2a14861e7d40dea959f181cd5cf28Jesse Wilson     */
2250deb236fb06f2a14861e7d40dea959f181cd5cf28Jesse Wilson    public byte[] gzip(byte[] bytes) throws IOException {
2251deb236fb06f2a14861e7d40dea959f181cd5cf28Jesse Wilson        ByteArrayOutputStream bytesOut = new ByteArrayOutputStream();
2252deb236fb06f2a14861e7d40dea959f181cd5cf28Jesse Wilson        OutputStream gzippedOut = new GZIPOutputStream(bytesOut);
2253deb236fb06f2a14861e7d40dea959f181cd5cf28Jesse Wilson        gzippedOut.write(bytes);
2254deb236fb06f2a14861e7d40dea959f181cd5cf28Jesse Wilson        gzippedOut.close();
2255deb236fb06f2a14861e7d40dea959f181cd5cf28Jesse Wilson        return bytesOut.toByteArray();
2256deb236fb06f2a14861e7d40dea959f181cd5cf28Jesse Wilson    }
2257deb236fb06f2a14861e7d40dea959f181cd5cf28Jesse Wilson
2258c8977f474b30c5f3807398859a6b16687af6fc7bJesse Wilson    /**
2259c8977f474b30c5f3807398859a6b16687af6fc7bJesse Wilson     * Reads at most {@code limit} characters from {@code in} and asserts that
2260c8977f474b30c5f3807398859a6b16687af6fc7bJesse Wilson     * content equals {@code expected}.
2261c8977f474b30c5f3807398859a6b16687af6fc7bJesse Wilson     */
2262c8977f474b30c5f3807398859a6b16687af6fc7bJesse Wilson    private void assertContent(String expected, URLConnection connection, int limit)
2263c8977f474b30c5f3807398859a6b16687af6fc7bJesse Wilson            throws IOException {
2264f02c695ed03e708623d9365dec26d533356ef2d0Brian Carlstrom        connection.connect();
226551e468abf2628ce964d3657042f3ac8f2c947504Jesse Wilson        assertEquals(expected, readAscii(connection.getInputStream(), limit));
2266c8977f474b30c5f3807398859a6b16687af6fc7bJesse Wilson        ((HttpURLConnection) connection).disconnect();
2267c8977f474b30c5f3807398859a6b16687af6fc7bJesse Wilson    }
2268c8977f474b30c5f3807398859a6b16687af6fc7bJesse Wilson
2269c8977f474b30c5f3807398859a6b16687af6fc7bJesse Wilson    private void assertContent(String expected, URLConnection connection) throws IOException {
2270c8977f474b30c5f3807398859a6b16687af6fc7bJesse Wilson        assertContent(expected, connection, Integer.MAX_VALUE);
2271c8977f474b30c5f3807398859a6b16687af6fc7bJesse Wilson    }
2272c8977f474b30c5f3807398859a6b16687af6fc7bJesse Wilson
227360476787f0e0f052366d8031c74e507ffd3d16a3Jesse Wilson    private void assertContains(List<String> headers, String header) {
227460476787f0e0f052366d8031c74e507ffd3d16a3Jesse Wilson        assertTrue(headers.toString(), headers.contains(header));
227560476787f0e0f052366d8031c74e507ffd3d16a3Jesse Wilson    }
227651e468abf2628ce964d3657042f3ac8f2c947504Jesse Wilson
2277ffd579b668428272b78f5c6c64f9c89766f37c1aJesse Wilson    private void assertContainsNoneMatching(List<String> headers, String pattern) {
2278ffd579b668428272b78f5c6c64f9c89766f37c1aJesse Wilson        for (String header : headers) {
2279ffd579b668428272b78f5c6c64f9c89766f37c1aJesse Wilson            if (header.matches(pattern)) {
2280ffd579b668428272b78f5c6c64f9c89766f37c1aJesse Wilson                fail("Header " + header + " matches " + pattern);
2281ffd579b668428272b78f5c6c64f9c89766f37c1aJesse Wilson            }
2282ffd579b668428272b78f5c6c64f9c89766f37c1aJesse Wilson        }
2283ffd579b668428272b78f5c6c64f9c89766f37c1aJesse Wilson    }
2284ffd579b668428272b78f5c6c64f9c89766f37c1aJesse Wilson
2285eafede536f2059bb6c869e7a5f07fd7ad9758e28Jesse Wilson    private Set<String> newSet(String... elements) {
228683a47d4d0c536e06fc53eda9d5a1a5d93f9accc6Jesse Wilson        return new HashSet<String>(Arrays.asList(elements));
228783a47d4d0c536e06fc53eda9d5a1a5d93f9accc6Jesse Wilson    }
228883a47d4d0c536e06fc53eda9d5a1a5d93f9accc6Jesse Wilson
228951e468abf2628ce964d3657042f3ac8f2c947504Jesse Wilson    enum TransferKind {
229051e468abf2628ce964d3657042f3ac8f2c947504Jesse Wilson        CHUNKED() {
2291deb236fb06f2a14861e7d40dea959f181cd5cf28Jesse Wilson            @Override void setBody(MockResponse response, byte[] content, int chunkSize)
229251e468abf2628ce964d3657042f3ac8f2c947504Jesse Wilson                    throws IOException {
229351e468abf2628ce964d3657042f3ac8f2c947504Jesse Wilson                response.setChunkedBody(content, chunkSize);
229451e468abf2628ce964d3657042f3ac8f2c947504Jesse Wilson            }
229551e468abf2628ce964d3657042f3ac8f2c947504Jesse Wilson        },
229651e468abf2628ce964d3657042f3ac8f2c947504Jesse Wilson        FIXED_LENGTH() {
2297deb236fb06f2a14861e7d40dea959f181cd5cf28Jesse Wilson            @Override void setBody(MockResponse response, byte[] content, int chunkSize) {
229851e468abf2628ce964d3657042f3ac8f2c947504Jesse Wilson                response.setBody(content);
229951e468abf2628ce964d3657042f3ac8f2c947504Jesse Wilson            }
230051e468abf2628ce964d3657042f3ac8f2c947504Jesse Wilson        },
230151e468abf2628ce964d3657042f3ac8f2c947504Jesse Wilson        END_OF_STREAM() {
2302deb236fb06f2a14861e7d40dea959f181cd5cf28Jesse Wilson            @Override void setBody(MockResponse response, byte[] content, int chunkSize) {
230351e468abf2628ce964d3657042f3ac8f2c947504Jesse Wilson                response.setBody(content);
2304e942f46f10bb9384a1b186b3d7b74f9704c57090Jesse Wilson                response.setSocketPolicy(DISCONNECT_AT_END);
230551e468abf2628ce964d3657042f3ac8f2c947504Jesse Wilson                for (Iterator<String> h = response.getHeaders().iterator(); h.hasNext(); ) {
230651e468abf2628ce964d3657042f3ac8f2c947504Jesse Wilson                    if (h.next().startsWith("Content-Length:")) {
230751e468abf2628ce964d3657042f3ac8f2c947504Jesse Wilson                        h.remove();
230851e468abf2628ce964d3657042f3ac8f2c947504Jesse Wilson                        break;
230951e468abf2628ce964d3657042f3ac8f2c947504Jesse Wilson                    }
231051e468abf2628ce964d3657042f3ac8f2c947504Jesse Wilson                }
231151e468abf2628ce964d3657042f3ac8f2c947504Jesse Wilson            }
231251e468abf2628ce964d3657042f3ac8f2c947504Jesse Wilson        };
231351e468abf2628ce964d3657042f3ac8f2c947504Jesse Wilson
2314deb236fb06f2a14861e7d40dea959f181cd5cf28Jesse Wilson        abstract void setBody(MockResponse response, byte[] content, int chunkSize)
231551e468abf2628ce964d3657042f3ac8f2c947504Jesse Wilson                throws IOException;
2316deb236fb06f2a14861e7d40dea959f181cd5cf28Jesse Wilson
2317deb236fb06f2a14861e7d40dea959f181cd5cf28Jesse Wilson        void setBody(MockResponse response, String content, int chunkSize) throws IOException {
2318deb236fb06f2a14861e7d40dea959f181cd5cf28Jesse Wilson            setBody(response, content.getBytes("UTF-8"), chunkSize);
2319deb236fb06f2a14861e7d40dea959f181cd5cf28Jesse Wilson        }
232051e468abf2628ce964d3657042f3ac8f2c947504Jesse Wilson    }
2321c0372d90016d241ac979faa6fa1731f30b6f2a03Jesse Wilson
2322984fcff696380abd6ea14e80030f9fd2d09dbad0Jesse Wilson    enum ProxyConfig {
2323f02c695ed03e708623d9365dec26d533356ef2d0Brian Carlstrom        NO_PROXY() {
2324f02c695ed03e708623d9365dec26d533356ef2d0Brian Carlstrom            @Override public HttpURLConnection connect(MockWebServer server, URL url)
2325f02c695ed03e708623d9365dec26d533356ef2d0Brian Carlstrom                    throws IOException {
2326f02c695ed03e708623d9365dec26d533356ef2d0Brian Carlstrom                return (HttpURLConnection) url.openConnection(Proxy.NO_PROXY);
2327f02c695ed03e708623d9365dec26d533356ef2d0Brian Carlstrom            }
2328f02c695ed03e708623d9365dec26d533356ef2d0Brian Carlstrom        },
2329f02c695ed03e708623d9365dec26d533356ef2d0Brian Carlstrom
2330984fcff696380abd6ea14e80030f9fd2d09dbad0Jesse Wilson        CREATE_ARG() {
2331984fcff696380abd6ea14e80030f9fd2d09dbad0Jesse Wilson            @Override public HttpURLConnection connect(MockWebServer server, URL url)
2332984fcff696380abd6ea14e80030f9fd2d09dbad0Jesse Wilson                    throws IOException {
2333984fcff696380abd6ea14e80030f9fd2d09dbad0Jesse Wilson                return (HttpURLConnection) url.openConnection(server.toProxyAddress());
2334984fcff696380abd6ea14e80030f9fd2d09dbad0Jesse Wilson            }
2335984fcff696380abd6ea14e80030f9fd2d09dbad0Jesse Wilson        },
2336984fcff696380abd6ea14e80030f9fd2d09dbad0Jesse Wilson
2337984fcff696380abd6ea14e80030f9fd2d09dbad0Jesse Wilson        PROXY_SYSTEM_PROPERTY() {
2338984fcff696380abd6ea14e80030f9fd2d09dbad0Jesse Wilson            @Override public HttpURLConnection connect(MockWebServer server, URL url)
2339984fcff696380abd6ea14e80030f9fd2d09dbad0Jesse Wilson                    throws IOException {
2340984fcff696380abd6ea14e80030f9fd2d09dbad0Jesse Wilson                System.setProperty("proxyHost", "localhost");
2341984fcff696380abd6ea14e80030f9fd2d09dbad0Jesse Wilson                System.setProperty("proxyPort", Integer.toString(server.getPort()));
2342984fcff696380abd6ea14e80030f9fd2d09dbad0Jesse Wilson                return (HttpURLConnection) url.openConnection();
2343984fcff696380abd6ea14e80030f9fd2d09dbad0Jesse Wilson            }
2344984fcff696380abd6ea14e80030f9fd2d09dbad0Jesse Wilson        },
2345984fcff696380abd6ea14e80030f9fd2d09dbad0Jesse Wilson
2346984fcff696380abd6ea14e80030f9fd2d09dbad0Jesse Wilson        HTTP_PROXY_SYSTEM_PROPERTY() {
2347984fcff696380abd6ea14e80030f9fd2d09dbad0Jesse Wilson            @Override public HttpURLConnection connect(MockWebServer server, URL url)
2348984fcff696380abd6ea14e80030f9fd2d09dbad0Jesse Wilson                    throws IOException {
2349984fcff696380abd6ea14e80030f9fd2d09dbad0Jesse Wilson                System.setProperty("http.proxyHost", "localhost");
2350984fcff696380abd6ea14e80030f9fd2d09dbad0Jesse Wilson                System.setProperty("http.proxyPort", Integer.toString(server.getPort()));
2351984fcff696380abd6ea14e80030f9fd2d09dbad0Jesse Wilson                return (HttpURLConnection) url.openConnection();
2352984fcff696380abd6ea14e80030f9fd2d09dbad0Jesse Wilson            }
2353984fcff696380abd6ea14e80030f9fd2d09dbad0Jesse Wilson        },
2354984fcff696380abd6ea14e80030f9fd2d09dbad0Jesse Wilson
2355984fcff696380abd6ea14e80030f9fd2d09dbad0Jesse Wilson        HTTPS_PROXY_SYSTEM_PROPERTY() {
2356984fcff696380abd6ea14e80030f9fd2d09dbad0Jesse Wilson            @Override public HttpURLConnection connect(MockWebServer server, URL url)
2357984fcff696380abd6ea14e80030f9fd2d09dbad0Jesse Wilson                    throws IOException {
2358984fcff696380abd6ea14e80030f9fd2d09dbad0Jesse Wilson                System.setProperty("https.proxyHost", "localhost");
2359984fcff696380abd6ea14e80030f9fd2d09dbad0Jesse Wilson                System.setProperty("https.proxyPort", Integer.toString(server.getPort()));
2360984fcff696380abd6ea14e80030f9fd2d09dbad0Jesse Wilson                return (HttpURLConnection) url.openConnection();
2361984fcff696380abd6ea14e80030f9fd2d09dbad0Jesse Wilson            }
2362984fcff696380abd6ea14e80030f9fd2d09dbad0Jesse Wilson        };
2363984fcff696380abd6ea14e80030f9fd2d09dbad0Jesse Wilson
2364984fcff696380abd6ea14e80030f9fd2d09dbad0Jesse Wilson        public abstract HttpURLConnection connect(MockWebServer server, URL url) throws IOException;
2365984fcff696380abd6ea14e80030f9fd2d09dbad0Jesse Wilson    }
2366984fcff696380abd6ea14e80030f9fd2d09dbad0Jesse Wilson
2367c0372d90016d241ac979faa6fa1731f30b6f2a03Jesse Wilson    private static class RecordingTrustManager implements X509TrustManager {
2368c0372d90016d241ac979faa6fa1731f30b6f2a03Jesse Wilson        private final List<String> calls = new ArrayList<String>();
2369c0372d90016d241ac979faa6fa1731f30b6f2a03Jesse Wilson
2370c0372d90016d241ac979faa6fa1731f30b6f2a03Jesse Wilson        public X509Certificate[] getAcceptedIssuers() {
2371c0372d90016d241ac979faa6fa1731f30b6f2a03Jesse Wilson            calls.add("getAcceptedIssuers");
2372c0372d90016d241ac979faa6fa1731f30b6f2a03Jesse Wilson            return new X509Certificate[] {};
2373c0372d90016d241ac979faa6fa1731f30b6f2a03Jesse Wilson        }
2374c0372d90016d241ac979faa6fa1731f30b6f2a03Jesse Wilson
2375c0372d90016d241ac979faa6fa1731f30b6f2a03Jesse Wilson        public void checkClientTrusted(X509Certificate[] chain, String authType)
2376c0372d90016d241ac979faa6fa1731f30b6f2a03Jesse Wilson                throws CertificateException {
2377c0372d90016d241ac979faa6fa1731f30b6f2a03Jesse Wilson            calls.add("checkClientTrusted " + certificatesToString(chain) + " " + authType);
2378c0372d90016d241ac979faa6fa1731f30b6f2a03Jesse Wilson        }
2379c0372d90016d241ac979faa6fa1731f30b6f2a03Jesse Wilson
2380c0372d90016d241ac979faa6fa1731f30b6f2a03Jesse Wilson        public void checkServerTrusted(X509Certificate[] chain, String authType)
2381c0372d90016d241ac979faa6fa1731f30b6f2a03Jesse Wilson                throws CertificateException {
2382c0372d90016d241ac979faa6fa1731f30b6f2a03Jesse Wilson            calls.add("checkServerTrusted " + certificatesToString(chain) + " " + authType);
2383c0372d90016d241ac979faa6fa1731f30b6f2a03Jesse Wilson        }
2384c0372d90016d241ac979faa6fa1731f30b6f2a03Jesse Wilson
2385c0372d90016d241ac979faa6fa1731f30b6f2a03Jesse Wilson        private String certificatesToString(X509Certificate[] certificates) {
2386c0372d90016d241ac979faa6fa1731f30b6f2a03Jesse Wilson            List<String> result = new ArrayList<String>();
2387c0372d90016d241ac979faa6fa1731f30b6f2a03Jesse Wilson            for (X509Certificate certificate : certificates) {
2388c0372d90016d241ac979faa6fa1731f30b6f2a03Jesse Wilson                result.add(certificate.getSubjectDN() + " " + certificate.getSerialNumber());
2389c0372d90016d241ac979faa6fa1731f30b6f2a03Jesse Wilson            }
2390c0372d90016d241ac979faa6fa1731f30b6f2a03Jesse Wilson            return result.toString();
2391c0372d90016d241ac979faa6fa1731f30b6f2a03Jesse Wilson        }
2392c0372d90016d241ac979faa6fa1731f30b6f2a03Jesse Wilson    }
2393c0372d90016d241ac979faa6fa1731f30b6f2a03Jesse Wilson
2394c0372d90016d241ac979faa6fa1731f30b6f2a03Jesse Wilson    private static class RecordingHostnameVerifier implements HostnameVerifier {
2395c0372d90016d241ac979faa6fa1731f30b6f2a03Jesse Wilson        private final List<String> calls = new ArrayList<String>();
2396c0372d90016d241ac979faa6fa1731f30b6f2a03Jesse Wilson
2397c0372d90016d241ac979faa6fa1731f30b6f2a03Jesse Wilson        public boolean verify(String hostname, SSLSession session) {
2398c0372d90016d241ac979faa6fa1731f30b6f2a03Jesse Wilson            calls.add("verify " + hostname);
2399c0372d90016d241ac979faa6fa1731f30b6f2a03Jesse Wilson            return true;
2400c0372d90016d241ac979faa6fa1731f30b6f2a03Jesse Wilson        }
2401c0372d90016d241ac979faa6fa1731f30b6f2a03Jesse Wilson    }
24025757cb35ad2e58d7accb7f5d3db6f2d5e72f097dJesse Wilson
24035757cb35ad2e58d7accb7f5d3db6f2d5e72f097dJesse Wilson    private static class SimpleAuthenticator extends Authenticator {
24045757cb35ad2e58d7accb7f5d3db6f2d5e72f097dJesse Wilson        /** base64("username:password") */
24055757cb35ad2e58d7accb7f5d3db6f2d5e72f097dJesse Wilson        private static final String BASE_64_CREDENTIALS = "dXNlcm5hbWU6cGFzc3dvcmQ=";
24065757cb35ad2e58d7accb7f5d3db6f2d5e72f097dJesse Wilson
24075757cb35ad2e58d7accb7f5d3db6f2d5e72f097dJesse Wilson        private String expectedPrompt;
24085757cb35ad2e58d7accb7f5d3db6f2d5e72f097dJesse Wilson        private RequestorType requestorType;
24095757cb35ad2e58d7accb7f5d3db6f2d5e72f097dJesse Wilson        private int requestingPort;
24105757cb35ad2e58d7accb7f5d3db6f2d5e72f097dJesse Wilson        private InetAddress requestingSite;
24115757cb35ad2e58d7accb7f5d3db6f2d5e72f097dJesse Wilson        private String requestingPrompt;
24125757cb35ad2e58d7accb7f5d3db6f2d5e72f097dJesse Wilson        private String requestingProtocol;
24135757cb35ad2e58d7accb7f5d3db6f2d5e72f097dJesse Wilson        private String requestingScheme;
24145757cb35ad2e58d7accb7f5d3db6f2d5e72f097dJesse Wilson
24155757cb35ad2e58d7accb7f5d3db6f2d5e72f097dJesse Wilson        protected PasswordAuthentication getPasswordAuthentication() {
24165757cb35ad2e58d7accb7f5d3db6f2d5e72f097dJesse Wilson            requestorType = getRequestorType();
24175757cb35ad2e58d7accb7f5d3db6f2d5e72f097dJesse Wilson            requestingPort = getRequestingPort();
24185757cb35ad2e58d7accb7f5d3db6f2d5e72f097dJesse Wilson            requestingSite = getRequestingSite();
24195757cb35ad2e58d7accb7f5d3db6f2d5e72f097dJesse Wilson            requestingPrompt = getRequestingPrompt();
24205757cb35ad2e58d7accb7f5d3db6f2d5e72f097dJesse Wilson            requestingProtocol = getRequestingProtocol();
24215757cb35ad2e58d7accb7f5d3db6f2d5e72f097dJesse Wilson            requestingScheme = getRequestingScheme();
24225757cb35ad2e58d7accb7f5d3db6f2d5e72f097dJesse Wilson            return (expectedPrompt == null || expectedPrompt.equals(requestingPrompt))
24235757cb35ad2e58d7accb7f5d3db6f2d5e72f097dJesse Wilson                    ? new PasswordAuthentication("username", "password".toCharArray())
24245757cb35ad2e58d7accb7f5d3db6f2d5e72f097dJesse Wilson                    : null;
24255757cb35ad2e58d7accb7f5d3db6f2d5e72f097dJesse Wilson        }
24265757cb35ad2e58d7accb7f5d3db6f2d5e72f097dJesse Wilson    }
2427e40c9e3935a5024c0f3ebfb3f1441fcd5c48ed86Elliott Hughes}
2428