1
0
mirror of https://github.com/square/okhttp.git synced 2026-01-25 16:01:38 +03:00

Switch to a builder for HttpURLConnection instances.

The builder has two upsides:
 - It allows us to use the same base classes from java.net
   as the base API.
 - It gives us a place to stash configuration in a place other
   than static fields. This will be useful for the connection
   pool, cookie manager, response cache, etc.
This commit is contained in:
jwilson
2012-12-15 16:17:18 -05:00
parent 3deadab31b
commit 7f7aa90bc5
12 changed files with 198 additions and 1281 deletions

View File

@@ -0,0 +1,43 @@
/*
* Copyright (C) 2012 Square, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.squareup.okhttp;
import java.net.HttpURLConnection;
import java.net.Proxy;
import java.net.URL;
/**
* Configures and creates HTTP connections.
*/
public final class OkHttpClient {
private Proxy proxy;
public OkHttpClient setProxy(Proxy proxy) {
this.proxy = proxy;
return this;
}
public HttpURLConnection open(URL url) {
String protocol = url.getProtocol();
if (protocol.equals("http")) {
return new libcore.net.http.HttpURLConnectionImpl(url, 80, proxy);
} else if (protocol.equals("https")) {
return new libcore.net.http.HttpsURLConnectionImpl(url, 443, proxy);
} else {
throw new IllegalArgumentException();
}
}
}

View File

@@ -1,829 +0,0 @@
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.squareup.okhttp;
import java.io.IOException;
import java.io.InputStream;
import java.net.ProtocolException;
import java.net.Proxy;
import java.net.SocketPermission;
import java.net.URL;
import java.net.URLConnection;
import java.util.Arrays;
import libcore.net.http.HttpEngine;
/**
* An {@link java.net.URLConnection} for HTTP (<a
* href="http://tools.ietf.org/html/rfc2616">RFC 2616</a>) used to send and
* receive data over the web. Data may be of any type and length. This class may
* be used to send and receive streaming data whose length is not known in
* advance.
*
* <p>Uses of this class follow a pattern:
* <ol>
* <li>Obtain a new {@code HttpURLConnection} by calling {@link
* java.net.URL#openConnection() URL.openConnection()} and casting the result to
* {@code HttpURLConnection}.
* <li>Prepare the request. The primary property of a request is its URI.
* Request headers may also include metadata such as credentials, preferred
* content types, and session cookies.
* <li>Optionally upload a request body. Instances must be configured with
* {@link #setDoOutput(boolean) setDoOutput(true)} if they include a
* request body. Transmit data by writing to the stream returned by {@link
* #getOutputStream()}.
* <li>Read the response. Response headers typically include metadata such as
* the response body's content type and length, modified dates and session
* cookies. The response body may be read from the stream returned by {@link
* #getInputStream()}. If the response has no body, that method returns an
* empty stream.
* <li>Disconnect. Once the response body has been read, the {@code
* HttpURLConnection} should be closed by calling {@link #disconnect()}.
* Disconnecting releases the resources held by a connection so they may
* be closed or reused.
* </ol>
*
* <p>For example, to retrieve the webpage at {@code http://www.android.com/}:
* <pre> {@code
* URL url = new URL("http://www.android.com/");
* HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
* try {
* InputStream in = new BufferedInputStream(urlConnection.getInputStream());
* readStream(in);
* } finally {
* urlConnection.disconnect();
* }
* }</pre>
*
* <h3>Secure Communication with HTTPS</h3>
* Calling {@link java.net.URL#openConnection()} on a URL with the "https"
* scheme will return an {@code HttpsURLConnection}, which allows for
* overriding the default {@link javax.net.ssl.HostnameVerifier
* HostnameVerifier} and {@link javax.net.ssl.SSLSocketFactory
* SSLSocketFactory}. An application-supplied {@code SSLSocketFactory}
* created from an {@link javax.net.ssl.SSLContext SSLContext} can
* provide a custom {@link javax.net.ssl.X509TrustManager
* X509TrustManager} for verifying certificate chains and a custom
* {@link javax.net.ssl.X509KeyManager X509KeyManager} for supplying
* client certificates. See {@link OkHttpsConnection HttpsURLConnection} for
* more details.
*
* <h3>Response Handling</h3>
* {@code HttpURLConnection} will follow up to five HTTP redirects. It will
* follow redirects from one origin server to another. This implementation
* doesn't follow redirects from HTTPS to HTTP or vice versa.
*
* <p>If the HTTP response indicates that an error occurred, {@link
* #getInputStream()} will throw an {@link java.io.IOException}. Use {@link
* #getErrorStream()} to read the error response. The headers can be read in
* the normal way using {@link #getHeaderFields()},
*
* <h3>Posting Content</h3>
* To upload data to a web server, configure the connection for output using
* {@link #setDoOutput(boolean) setDoOutput(true)}.
*
* <p>For best performance, you should call either {@link
* #setFixedLengthStreamingMode(int)} when the body length is known in advance,
* or {@link #setChunkedStreamingMode(int)} when it is not. Otherwise {@code
* HttpURLConnection} will be forced to buffer the complete request body in
* memory before it is transmitted, wasting (and possibly exhausting) heap and
* increasing latency.
*
* <p>For example, to perform an upload: <pre> {@code
* HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
* try {
* urlConnection.setDoOutput(true);
* urlConnection.setChunkedStreamingMode(0);
*
* OutputStream out = new BufferedOutputStream(urlConnection.getOutputStream());
* writeStream(out);
*
* InputStream in = new BufferedInputStream(urlConnection.getInputStream());
* readStream(in);
* } finally {
* urlConnection.disconnect();
* }
* }</pre>
*
* <h3>Performance</h3>
* The input and output streams returned by this class are <strong>not
* buffered</strong>. Most callers should wrap the returned streams with {@link
* java.io.BufferedInputStream BufferedInputStream} or {@link
* java.io.BufferedOutputStream BufferedOutputStream}. Callers that do only bulk
* reads or writes may omit buffering.
*
* <p>When transferring large amounts of data to or from a server, use streams
* to limit how much data is in memory at once. Unless you need the entire
* body to be in memory at once, process it as a stream (rather than storing
* the complete body as a single byte array or string).
*
* <p>To reduce latency, this class may reuse the same underlying {@code Socket}
* for multiple request/response pairs. As a result, HTTP connections may be
* held open longer than necessary. Calls to {@link #disconnect()} may return
* the socket to a pool of connected sockets. This behavior can be disabled by
* setting the {@code http.keepAlive} system property to {@code false} before
* issuing any HTTP requests. The {@code http.maxConnections} property may be
* used to control how many idle connections to each server will be held.
*
* <p>By default, this implementation of {@code HttpURLConnection} requests that
* servers use gzip compression. Since {@link #getContentLength()} returns the
* number of bytes transmitted, you cannot use that method to predict how many
* bytes can be read from {@link #getInputStream()}. Instead, read that stream
* until it is exhausted: when {@link java.io.InputStream#read} returns -1. Gzip
* compression can be disabled by setting the acceptable encodings in the
* request header: <pre> {@code
* urlConnection.setRequestProperty("Accept-Encoding", "identity");
* }</pre>
*
* <h3>Handling Network Sign-On</h3>
* Some Wi-Fi networks block Internet access until the user clicks through a
* sign-on page. Such sign-on pages are typically presented by using HTTP
* redirects. You can use {@link #getURL()} to test if your connection has been
* unexpectedly redirected. This check is not valid until <strong>after</strong>
* the response headers have been received, which you can trigger by calling
* {@link #getHeaderFields()} or {@link #getInputStream()}. For example, to
* check that a response was not redirected to an unexpected host:
* <pre> {@code
* HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
* try {
* InputStream in = new BufferedInputStream(urlConnection.getInputStream());
* if (!url.getHost().equals(urlConnection.getURL().getHost())) {
* // we were redirected! Kick the user out to the browser to sign on?
* }
* ...
* } finally {
* urlConnection.disconnect();
* }
* }</pre>
*
* <h3>HTTP Authentication</h3>
* {@code HttpURLConnection} supports <a
* href="http://www.ietf.org/rfc/rfc2617">HTTP basic authentication</a>. Use
* {@link java.net.Authenticator} to set the VM-wide authentication handler:
* <pre> {@code
* Authenticator.setDefault(new Authenticator() {
* protected PasswordAuthentication getPasswordAuthentication() {
* return new PasswordAuthentication(username, password.toCharArray());
* }
* });
* }</pre>
* Unless paired with HTTPS, this is <strong>not</strong> a secure mechanism for
* user authentication. In particular, the username, password, request and
* response are all transmitted over the network without encryption.
*
* <h3>Sessions with Cookies</h3>
* To establish and maintain a potentially long-lived session between client
* and server, {@code HttpURLConnection} includes an extensible cookie manager.
* Enable VM-wide cookie management using {@link java.net.CookieHandler} and {@link
* java.net.CookieManager}: <pre> {@code
* CookieManager cookieManager = new CookieManager();
* CookieHandler.setDefault(cookieManager);
* }</pre>
* By default, {@code CookieManager} accepts cookies from the <a
* href="http://www.w3.org/Protocols/rfc2616/rfc2616-sec1.html">origin
* server</a> only. Two other policies are included: {@link
* java.net.CookiePolicy#ACCEPT_ALL} and {@link java.net.CookiePolicy#ACCEPT_NONE}. Implement
* {@link java.net.CookiePolicy} to define a custom policy.
*
* <p>The default {@code CookieManager} keeps all accepted cookies in memory. It
* will forget these cookies when the VM exits. Implement {@link java.net.CookieStore} to
* define a custom cookie store.
*
* <p>In addition to the cookies set by HTTP responses, you may set cookies
* programmatically. To be included in HTTP request headers, cookies must have
* the domain and path properties set.
*
* <p>By default, new instances of {@code HttpCookie} work only with servers
* that support <a href="http://www.ietf.org/rfc/rfc2965.txt">RFC 2965</a>
* cookies. Many web servers support only the older specification, <a
* href="http://www.ietf.org/rfc/rfc2109.txt">RFC 2109</a>. For compatibility
* with the most web servers, set the cookie version to 0.
*
* <p>For example, to receive {@code www.twitter.com} in French: <pre> {@code
* HttpCookie cookie = new HttpCookie("lang", "fr");
* cookie.setDomain("twitter.com");
* cookie.setPath("/");
* cookie.setVersion(0);
* cookieManager.getCookieStore().add(new URI("http://twitter.com/"), cookie);
* }</pre>
*
* <h3>HTTP Methods</h3>
* <p>{@code HttpURLConnection} uses the {@code GET} method by default. It will
* use {@code POST} if {@link #setDoOutput setDoOutput(true)} has been called.
* Other HTTP methods ({@code OPTIONS}, {@code HEAD}, {@code PUT}, {@code
* DELETE} and {@code TRACE}) can be used with {@link #setRequestMethod}.
*
* <h3>Proxies</h3>
* By default, this class will connect directly to the <a
* href="http://www.w3.org/Protocols/rfc2616/rfc2616-sec1.html">origin
* server</a>. It can also connect via an {@link java.net.Proxy.Type#HTTP HTTP} or {@link
* java.net.Proxy.Type#SOCKS SOCKS} proxy. To use a proxy, use {@link
* java.net.URL#openConnection(java.net.Proxy) URL.openConnection(Proxy)} when creating the
* connection.
*
* <h3>IPv6 Support</h3>
* <p>This class includes transparent support for IPv6. For hosts with both IPv4
* and IPv6 addresses, it will attempt to connect to each of a host's addresses
* until a connection is established.
*
* <h3>Response Caching</h3>
* Android 4.0 (Ice Cream Sandwich) includes a response cache. See {@code
* android.net.http.HttpResponseCache} for instructions on enabling HTTP caching
* in your application.
*
* <h3>Avoiding Bugs In Earlier Releases</h3>
* Prior to Android 2.2 (Froyo), this class had some frustrating bugs. In
* particular, calling {@code close()} on a readable {@code InputStream} could
* <a href="http://code.google.com/p/android/issues/detail?id=2939">poison the
* connection pool</a>. Work around this by disabling connection pooling:
* <pre> {@code
* private void disableConnectionReuseIfNecessary() {
* // Work around pre-Froyo bugs in HTTP connection reuse.
* if (Integer.parseInt(Build.VERSION.SDK) < Build.VERSION_CODES.FROYO) {
* System.setProperty("http.keepAlive", "false");
* }
* }}</pre>
*
* <p>Each instance of {@code HttpURLConnection} may be used for one
* request/response pair. Instances of this class are not thread safe.
*/
public abstract class OkHttpConnection extends URLConnection {
/**
* The subset of HTTP methods that the user may select via {@link
* #setRequestMethod(String)}.
*/
private static final String[] PERMITTED_USER_METHODS = {
HttpEngine.OPTIONS,
HttpEngine.GET,
HttpEngine.HEAD,
HttpEngine.POST,
HttpEngine.PUT,
HttpEngine.DELETE,
HttpEngine.TRACE
// Note: we don't allow users to specify "CONNECT"
};
/**
* The HTTP request method of this {@code HttpURLConnection}. The default
* value is {@code "GET"}.
*/
protected String method = HttpEngine.GET;
/**
* The status code of the response obtained from the HTTP request. The
* default value is {@code -1}.
* <p>
* <li>1xx: Informational</li>
* <li>2xx: Success</li>
* <li>3xx: Relocation/Redirection</li>
* <li>4xx: Client Error</li>
* <li>5xx: Server Error</li>
*/
protected int responseCode = -1;
/**
* The HTTP response message which corresponds to the response code.
*/
protected String responseMessage;
/**
* Flag to define whether the protocol will automatically follow redirects
* or not. The default value is {@code true}.
*/
protected boolean instanceFollowRedirects = followRedirects;
private static boolean followRedirects = true;
/**
* If the HTTP chunked encoding is enabled this parameter defines the
* chunk-length. Default value is {@code -1} that means the chunked encoding
* mode is disabled.
*/
protected int chunkLength = -1;
/**
* If using HTTP fixed-length streaming mode this parameter defines the
* fixed length of content. Default value is {@code -1} that means the
* fixed-length streaming mode is disabled.
*/
protected int fixedContentLength = -1;
// 2XX: generally "OK"
// 3XX: relocation/redirect
// 4XX: client error
// 5XX: server error
/**
* Numeric status code, 202: Accepted.
*/
public static final int HTTP_ACCEPTED = 202;
/**
* Numeric status code, 502: Bad Gateway.
*/
public static final int HTTP_BAD_GATEWAY = 502;
/**
* Numeric status code, 405: Bad Method.
*/
public static final int HTTP_BAD_METHOD = 405;
/**
* Numeric status code, 400: Bad Request.
*/
public static final int HTTP_BAD_REQUEST = 400;
/**
* Numeric status code, 408: Client Timeout.
*/
public static final int HTTP_CLIENT_TIMEOUT = 408;
/**
* Numeric status code, 409: Conflict.
*/
public static final int HTTP_CONFLICT = 409;
/**
* Numeric status code, 201: Created.
*/
public static final int HTTP_CREATED = 201;
/**
* Numeric status code, 413: Entity too large.
*/
public static final int HTTP_ENTITY_TOO_LARGE = 413;
/**
* Numeric status code, 403: Forbidden.
*/
public static final int HTTP_FORBIDDEN = 403;
/**
* Numeric status code, 504: Gateway timeout.
*/
public static final int HTTP_GATEWAY_TIMEOUT = 504;
/**
* Numeric status code, 410: Gone.
*/
public static final int HTTP_GONE = 410;
/**
* Numeric status code, 500: Internal error.
*/
public static final int HTTP_INTERNAL_ERROR = 500;
/**
* Numeric status code, 411: Length required.
*/
public static final int HTTP_LENGTH_REQUIRED = 411;
/**
* Numeric status code, 301 Moved permanently.
*/
public static final int HTTP_MOVED_PERM = 301;
/**
* Numeric status code, 302: Moved temporarily.
*/
public static final int HTTP_MOVED_TEMP = 302;
/**
* Numeric status code, 300: Multiple choices.
*/
public static final int HTTP_MULT_CHOICE = 300;
/**
* Numeric status code, 204: No content.
*/
public static final int HTTP_NO_CONTENT = 204;
/**
* Numeric status code, 406: Not acceptable.
*/
public static final int HTTP_NOT_ACCEPTABLE = 406;
/**
* Numeric status code, 203: Not authoritative.
*/
public static final int HTTP_NOT_AUTHORITATIVE = 203;
/**
* Numeric status code, 404: Not found.
*/
public static final int HTTP_NOT_FOUND = 404;
/**
* Numeric status code, 501: Not implemented.
*/
public static final int HTTP_NOT_IMPLEMENTED = 501;
/**
* Numeric status code, 304: Not modified.
*/
public static final int HTTP_NOT_MODIFIED = 304;
/**
* Numeric status code, 200: OK.
*/
public static final int HTTP_OK = 200;
/**
* Numeric status code, 206: Partial.
*/
public static final int HTTP_PARTIAL = 206;
/**
* Numeric status code, 402: Payment required.
*/
public static final int HTTP_PAYMENT_REQUIRED = 402;
/**
* Numeric status code, 412: Precondition failed.
*/
public static final int HTTP_PRECON_FAILED = 412;
/**
* Numeric status code, 407: Proxy authentication required.
*/
public static final int HTTP_PROXY_AUTH = 407;
/**
* Numeric status code, 414: Request too long.
*/
public static final int HTTP_REQ_TOO_LONG = 414;
/**
* Numeric status code, 205: Reset.
*/
public static final int HTTP_RESET = 205;
/**
* Numeric status code, 303: See other.
*/
public static final int HTTP_SEE_OTHER = 303;
/**
* Numeric status code, 500: Internal error.
*
* @deprecated Use {@link #HTTP_INTERNAL_ERROR}
*/
@Deprecated
public static final int HTTP_SERVER_ERROR = 500;
/**
* Numeric status code, 305: Use proxy.
*
* <p>Like Firefox and Chrome, this class doesn't honor this response code.
* Other implementations respond to this status code by retrying the request
* using the HTTP proxy named by the response's Location header field.
*/
public static final int HTTP_USE_PROXY = 305;
/**
* Numeric status code, 401: Unauthorized.
*/
public static final int HTTP_UNAUTHORIZED = 401;
/**
* Numeric status code, 415: Unsupported type.
*/
public static final int HTTP_UNSUPPORTED_TYPE = 415;
/**
* Numeric status code, 503: Unavailable.
*/
public static final int HTTP_UNAVAILABLE = 503;
/**
* Numeric status code, 505: Version not supported.
*/
public static final int HTTP_VERSION = 505;
/**
* Returns a new OkHttpConnection or OkHttpsConnection to {@code url}.
*/
public static OkHttpConnection open(URL url) {
String protocol = url.getProtocol();
if (protocol.equals("http")) {
return new libcore.net.http.HttpURLConnectionImpl(url, 80);
} else if (protocol.equals("https")) {
return new libcore.net.http.HttpsURLConnectionImpl(url, 443);
} else {
throw new IllegalArgumentException();
}
}
/**
* Returns a new OkHttpConnection or OkHttpsConnection to {@code url} that
* connects via {@code proxy}.
*/
public static OkHttpConnection open(URL url, Proxy proxy) {
String protocol = url.getProtocol();
if (protocol.equals("http")) {
return new libcore.net.http.HttpURLConnectionImpl(url, 80, proxy);
} else if (protocol.equals("https")) {
return new libcore.net.http.HttpsURLConnectionImpl(url, 443, proxy);
} else {
throw new IllegalArgumentException();
}
}
/**
* Constructs a new {@code HttpURLConnection} instance pointing to the
* resource specified by the {@code url}.
*
* @param url
* the URL of this connection.
* @see java.net.URL
* @see java.net.URLConnection
*/
protected OkHttpConnection(URL url) {
super(url);
}
/**
* Releases this connection so that its resources may be either reused or
* closed.
*
* <p>Unlike other Java implementations, this will not necessarily close
* socket connections that can be reused. You can disable all connection
* reuse by setting the {@code http.keepAlive} system property to {@code
* false} before issuing any HTTP requests.
*/
public abstract void disconnect();
/**
* Returns an input stream from the server in the case of an error such as
* the requested file has not been found on the remote server. This stream
* can be used to read the data the server will send back.
*
* @return the error input stream returned by the server.
*/
public InputStream getErrorStream() {
return null;
}
/**
* Returns the value of {@code followRedirects} which indicates if this
* connection follows a different URL redirected by the server. It is
* enabled by default.
*
* @return the value of the flag.
* @see #setFollowRedirects
*/
public static boolean getFollowRedirects() {
return followRedirects;
}
/**
* Returns the permission object (in this case {@code SocketPermission})
* with the host and the port number as the target name and {@code
* "resolve, connect"} as the action list. If the port number of this URL
* instance is lower than {@code 0} the port will be set to {@code 80}.
*
* @return the permission object required for this connection.
* @throws java.io.IOException
* if an IO exception occurs during the creation of the
* permission object.
*/
@Override
public java.security.Permission getPermission() throws IOException {
int port = url.getPort();
if (port < 0) {
port = 80;
}
return new SocketPermission(url.getHost() + ":" + port,
"connect, resolve");
}
/**
* Returns the request method which will be used to make the request to the
* remote HTTP server. All possible methods of this HTTP implementation is
* listed in the class definition.
*
* @return the request method string.
* @see #method
* @see #setRequestMethod
*/
public String getRequestMethod() {
return method;
}
/**
* Returns the response code returned by the remote HTTP server.
*
* @return the response code, -1 if no valid response code.
* @throws java.io.IOException
* if there is an IO error during the retrieval.
* @see #getResponseMessage
*/
public int getResponseCode() throws IOException {
// Call getInputStream() first since getHeaderField() doesn't return
// exceptions
getInputStream();
String response = getHeaderField(0);
if (response == null) {
return -1;
}
response = response.trim();
int mark = response.indexOf(" ") + 1;
if (mark == 0) {
return -1;
}
int last = mark + 3;
if (last > response.length()) {
last = response.length();
}
responseCode = Integer.parseInt(response.substring(mark, last));
if (last + 1 <= response.length()) {
responseMessage = response.substring(last + 1);
}
return responseCode;
}
/**
* Returns the response message returned by the remote HTTP server.
*
* @return the response message. {@code null} if no such response exists.
* @throws java.io.IOException
* if there is an error during the retrieval.
* @see #getResponseCode()
*/
public String getResponseMessage() throws IOException {
if (responseMessage != null) {
return responseMessage;
}
getResponseCode();
return responseMessage;
}
/**
* Sets the flag of whether this connection will follow redirects returned
* by the remote server.
*
* @param auto
* the value to enable or disable this option.
*/
public static void setFollowRedirects(boolean auto) {
followRedirects = auto;
}
/**
* Sets the request command which will be sent to the remote HTTP server.
* This method can only be called before the connection is made.
*
* @param method
* the string representing the method to be used.
* @throws java.net.ProtocolException
* if this is called after connected, or the method is not
* supported by this HTTP implementation.
* @see #getRequestMethod()
* @see #method
*/
public void setRequestMethod(String method) throws ProtocolException {
if (connected) {
throw new ProtocolException("Connection already established");
}
for (String permittedUserMethod : PERMITTED_USER_METHODS) {
if (permittedUserMethod.equals(method)) {
// if there is a supported method that matches the desired
// method, then set the current method and return
this.method = permittedUserMethod;
return;
}
}
// if none matches, then throw ProtocolException
throw new ProtocolException("Unknown method '" + method + "'; must be one of "
+ Arrays.toString(PERMITTED_USER_METHODS));
}
/**
* Returns whether this connection uses a proxy server or not.
*
* @return {@code true} if this connection passes a proxy server, false
* otherwise.
*/
public abstract boolean usingProxy();
/**
* Returns the encoding used to transmit the response body over the network.
* This is null or "identity" if the content was not encoded, or "gzip" if
* the body was gzip compressed. Most callers will be more interested in the
* {@link #getContentType() content type}, which may also include the
* content's character encoding.
*/
@Override public String getContentEncoding() {
return super.getContentEncoding(); // overridden for Javadoc only
}
/**
* Returns whether this connection follows redirects.
*
* @return {@code true} if this connection follows redirects, false
* otherwise.
*/
public boolean getInstanceFollowRedirects() {
return instanceFollowRedirects;
}
/**
* Sets whether this connection follows redirects.
*
* @param followRedirects
* {@code true} if this connection will follows redirects, false
* otherwise.
*/
public void setInstanceFollowRedirects(boolean followRedirects) {
instanceFollowRedirects = followRedirects;
}
/**
* Returns the date value in milliseconds since {@code 01.01.1970, 00:00h}
* corresponding to the header field {@code field}. The {@code defaultValue}
* will be returned if no such field can be found in the response header.
*
* @param field
* the header field name.
* @param defaultValue
* the default value to use if the specified header field wont be
* found.
* @return the header field represented in milliseconds since January 1,
* 1970 GMT.
*/
@Override
public long getHeaderFieldDate(String field, long defaultValue) {
return super.getHeaderFieldDate(field, defaultValue);
}
/**
* If the length of a HTTP request body is known ahead, sets fixed length to
* enable streaming without buffering. Sets after connection will cause an
* exception.
*
* @see #setChunkedStreamingMode
* @param contentLength
* the fixed length of the HTTP request body.
* @throws IllegalStateException
* if already connected or another mode already set.
* @throws IllegalArgumentException
* if {@code contentLength} is less than zero.
*/
public void setFixedLengthStreamingMode(int contentLength) {
if (super.connected) {
throw new IllegalStateException("Already connected");
}
if (chunkLength > 0) {
throw new IllegalStateException("Already in chunked mode");
}
if (contentLength < 0) {
throw new IllegalArgumentException("contentLength < 0");
}
this.fixedContentLength = contentLength;
}
/**
* Stream a request body whose length is not known in advance. Old HTTP/1.0
* only servers may not support this mode.
*
* <p>When HTTP chunked encoding is used, the stream is divided into
* chunks, each prefixed with a header containing the chunk's size. Setting
* a large chunk length requires a large internal buffer, potentially
* wasting memory. Setting a small chunk length increases the number of
* bytes that must be transmitted because of the header on every chunk.
* Most caller should use {@code 0} to get the system default.
*
* @see #setFixedLengthStreamingMode
* @param chunkLength the length to use, or {@code 0} for the default chunk
* length.
* @throws IllegalStateException if already connected or another mode
* already set.
*/
public void setChunkedStreamingMode(int chunkLength) {
if (super.connected) {
throw new IllegalStateException("Already connected");
}
if (fixedContentLength >= 0) {
throw new IllegalStateException("Already in fixed-length mode");
}
if (chunkLength <= 0) {
this.chunkLength = HttpEngine.DEFAULT_CHUNK_LENGTH;
} else {
this.chunkLength = chunkLength;
}
}
}

View File

@@ -1,296 +0,0 @@
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.squareup.okhttp;
import java.net.URL;
import java.security.Principal;
import java.security.cert.Certificate;
import java.security.cert.X509Certificate;
import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLPeerUnverifiedException;
import javax.net.ssl.SSLSocketFactory;
/**
* An {@link java.net.HttpURLConnection} for HTTPS (<a
* href="http://tools.ietf.org/html/rfc2818">RFC 2818</a>). A
* connected {@code HttpsURLConnection} allows access to the
* negotiated cipher suite, the server certificate chain, and the
* client certificate chain if any.
*
* <h3>Providing an application specific X509TrustManager</h3>
*
* If an application wants to trust Certificate Authority (CA)
* certificates that are not part of the system, it should specify its
* own {@code X509TrustManager} via a {@code SSLSocketFactory} set on
* the {@code HttpsURLConnection}. The {@code X509TrustManager} can be
* created based on a {@code KeyStore} using a {@code
* TrustManagerFactory} to supply trusted CA certificates. Note that
* self-signed certificates are effectively their own CA and can be
* trusted by including them in a {@code KeyStore}.
*
* <p>For example, to trust a set of certificates specified by a {@code KeyStore}:
* <pre> {@code
* KeyStore keyStore = ...;
* TrustManagerFactory tmf = TrustManagerFactory.getInstance("X509");
* tmf.init(keyStore);
*
* SSLContext context = SSLContext.getInstance("TLS");
* context.init(null, tmf.getTrustManagers(), null);
*
* URL url = new URL("https://www.example.com/");
* HttpsURLConnection urlConnection = (HttpsURLConnection) url.openConnection();
* urlConnection.setSSLSocketFactory(context.getSocketFactory());
* InputStream in = urlConnection.getInputStream();
* }</pre>
*
* <p>It is possible to implement {@code X509TrustManager} directly
* instead of using one created by a {@code
* TrustManagerFactory}. While this is straightforward in the insecure
* case of allowing all certificate chains to pass verification,
* writing a proper implementation will usually want to take advantage
* of {@link java.security.cert.CertPathValidator
* CertPathValidator}. In general, it might be better to write a
* custom {@code KeyStore} implementation to pass to the {@code
* TrustManagerFactory} than to try and write a custom {@code
* X509TrustManager}.
*
* <h3>Providing an application specific X509KeyManager</h3>
*
* A custom {@code X509KeyManager} can be used to supply a client
* certificate and its associated private key to authenticate a
* connection to the server. The {@code X509KeyManager} can be created
* based on a {@code KeyStore} using a {@code KeyManagerFactory}.
*
* <p>For example, to supply client certificates from a {@code KeyStore}:
* <pre> {@code
* KeyStore keyStore = ...;
* KeyManagerFactory kmf = KeyManagerFactory.getInstance("X509");
* kmf.init(keyStore);
*
* SSLContext context = SSLContext.getInstance("TLS");
* context.init(kmf.getKeyManagers(), null, null);
*
* URL url = new URL("https://www.example.com/");
* HttpsURLConnection urlConnection = (HttpsURLConnection) url.openConnection();
* urlConnection.setSSLSocketFactory(context.getSocketFactory());
* InputStream in = urlConnection.getInputStream();
* }</pre>
*
* <p>A {@code X509KeyManager} can also be implemented directly. This
* can allow an application to return a certificate and private key
* from a non-{@code KeyStore} source or to specify its own logic for
* selecting a specific credential to use when many may be present in
* a single {@code KeyStore}.
*
* <h3>TLS Intolerance Support</h3>
*
* This class attempts to create secure connections using common TLS
* extensions and SSL deflate compression. Should that fail, the
* connection will be retried with SSLv3 only.
*/
public abstract class OkHttpsConnection extends OkHttpConnection {
private static HostnameVerifier defaultHostnameVerifier
= HttpsURLConnection.getDefaultHostnameVerifier();
private static SSLSocketFactory defaultSSLSocketFactory = (SSLSocketFactory) SSLSocketFactory
.getDefault();
/**
* Sets the default hostname verifier to be used by new instances.
*
* @param v
* the new default hostname verifier
* @throws IllegalArgumentException
* if the specified verifier is {@code null}.
*/
public static void setDefaultHostnameVerifier(HostnameVerifier v) {
if (v == null) {
throw new IllegalArgumentException("HostnameVerifier is null");
}
defaultHostnameVerifier = v;
}
/**
* Returns the default hostname verifier.
*
* @return the default hostname verifier.
*/
public static HostnameVerifier getDefaultHostnameVerifier() {
return defaultHostnameVerifier;
}
/**
* Sets the default SSL socket factory to be used by new instances.
*
* @param sf
* the new default SSL socket factory.
* @throws IllegalArgumentException
* if the specified socket factory is {@code null}.
*/
public static void setDefaultSSLSocketFactory(SSLSocketFactory sf) {
if (sf == null) {
throw new IllegalArgumentException("SSLSocketFactory is null");
}
defaultSSLSocketFactory = sf;
}
/**
* Returns the default SSL socket factory for new instances.
*
* @return the default SSL socket factory for new instances.
*/
public static SSLSocketFactory getDefaultSSLSocketFactory() {
return defaultSSLSocketFactory;
}
/**
* The host name verifier used by this connection. It is initialized from
* the default hostname verifier
* {@link #setDefaultHostnameVerifier(javax.net.ssl.HostnameVerifier)} or
* {@link #getDefaultHostnameVerifier()}.
*/
protected HostnameVerifier hostnameVerifier;
private SSLSocketFactory sslSocketFactory;
/**
* Creates a new {@code HttpsURLConnection} with the specified {@code URL}.
*
* @param url
* the {@code URL} to connect to.
*/
protected OkHttpsConnection(URL url) {
super(url);
hostnameVerifier = defaultHostnameVerifier;
sslSocketFactory = defaultSSLSocketFactory;
}
/**
* Returns the name of the cipher suite negotiated during the SSL handshake.
*
* @return the name of the cipher suite negotiated during the SSL handshake.
* @throws IllegalStateException
* if no connection has been established yet.
*/
public abstract String getCipherSuite();
/**
* Returns the list of local certificates used during the handshake. These
* certificates were sent to the peer.
*
* @return Returns the list of certificates used during the handshake with
* the local identity certificate followed by CAs, or {@code null}
* if no certificates were used during the handshake.
* @throws IllegalStateException
* if no connection has been established yet.
*/
public abstract Certificate[] getLocalCertificates();
/**
* Return the list of certificates identifying the peer during the
* handshake.
*
* @return the list of certificates identifying the peer with the peer's
* identity certificate followed by CAs.
* @throws javax.net.ssl.SSLPeerUnverifiedException
* if the identity of the peer has not been verified..
* @throws IllegalStateException
* if no connection has been established yet.
*/
public abstract Certificate[] getServerCertificates() throws SSLPeerUnverifiedException;
/**
* Returns the {@code Principal} identifying the peer.
*
* @return the {@code Principal} identifying the peer.
* @throws javax.net.ssl.SSLPeerUnverifiedException
* if the identity of the peer has not been verified.
* @throws IllegalStateException
* if no connection has been established yet.
*/
public Principal getPeerPrincipal() throws SSLPeerUnverifiedException {
Certificate[] certs = getServerCertificates();
if (certs == null || certs.length == 0 || (!(certs[0] instanceof X509Certificate))) {
throw new SSLPeerUnverifiedException("No server's end-entity certificate");
}
return ((X509Certificate) certs[0]).getSubjectX500Principal();
}
/**
* Returns the {@code Principal} used to identify the local host during the handshake.
*
* @return the {@code Principal} used to identify the local host during the handshake, or
* {@code null} if none was used.
* @throws IllegalStateException
* if no connection has been established yet.
*/
public Principal getLocalPrincipal() {
Certificate[] certs = getLocalCertificates();
if (certs == null || certs.length == 0 || (!(certs[0] instanceof X509Certificate))) {
return null;
}
return ((X509Certificate) certs[0]).getSubjectX500Principal();
}
/**
* Sets the hostname verifier for this instance.
*
* @param v
* the hostname verifier for this instance.
* @throws IllegalArgumentException
* if the specified verifier is {@code null}.
*/
public void setHostnameVerifier(HostnameVerifier v) {
if (v == null) {
throw new IllegalArgumentException("HostnameVerifier is null");
}
hostnameVerifier = v;
}
/**
* Returns the hostname verifier used by this instance.
*/
public HostnameVerifier getHostnameVerifier() {
return hostnameVerifier;
}
/**
* Sets the SSL socket factory for this instance.
*
* @param sf
* the SSL socket factory to be used by this instance.
* @throws IllegalArgumentException
* if the specified socket factory is {@code null}.
*/
public void setSSLSocketFactory(SSLSocketFactory sf) {
if (sf == null) {
throw new IllegalArgumentException("SSLSocketFactory is null");
}
sslSocketFactory = sf;
}
/**
* Returns the SSL socket factory used by this instance.
*/
public SSLSocketFactory getSSLSocketFactory() {
return sslSocketFactory;
}
}

View File

@@ -16,7 +16,7 @@
*/
package libcore;
import com.squareup.okhttp.OkHttpsConnection;
import com.squareup.okhttp.OkHttpClient;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.lang.reflect.Constructor;
@@ -260,7 +260,7 @@ public class Platform {
JettyNpnProvider provider = (JettyNpnProvider) Proxy.getInvocationHandler(
getMethod.invoke(null, socket));
if (!provider.unsupported && provider.selected == null) {
Logger logger = Logger.getLogger(OkHttpsConnection.class.getName());
Logger logger = Logger.getLogger(OkHttpClient.class.getName());
logger.log(Level.INFO, "NPN callback dropped so SPDY is disabled. "
+ "Is npn-boot on the boot class path?");
return null;

View File

@@ -17,7 +17,6 @@
package libcore.net.http;
import com.squareup.okhttp.OkHttpConnection;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
@@ -25,6 +24,7 @@ import java.io.OutputStream;
import java.net.CacheRequest;
import java.net.CacheResponse;
import java.net.CookieHandler;
import java.net.HttpURLConnection;
import java.net.Proxy;
import java.net.ProxySelector;
import java.net.ResponseCache;
@@ -391,7 +391,7 @@ public class HttpEngine {
cacheRequest = responseCache.put(uri, getHttpConnectionToCache());
}
protected OkHttpConnection getHttpConnectionToCache() {
protected HttpURLConnection getHttpConnectionToCache() {
return policy;
}

View File

@@ -16,9 +16,6 @@
package libcore.net.http;
import com.squareup.okhttp.OkHttpConnection;
import com.squareup.okhttp.OkHttpsConnection;
import java.io.BufferedWriter;
import java.io.ByteArrayInputStream;
import java.io.File;
@@ -32,6 +29,7 @@ import java.io.UnsupportedEncodingException;
import java.io.Writer;
import java.net.CacheRequest;
import java.net.CacheResponse;
import java.net.HttpURLConnection;
import java.net.ResponseCache;
import java.net.SecureCacheResponse;
import java.net.URI;
@@ -47,6 +45,7 @@ import java.security.cert.X509Certificate;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLPeerUnverifiedException;
import libcore.io.Base64;
import libcore.io.DiskLruCache;
@@ -121,11 +120,11 @@ public final class HttpResponseCache extends ResponseCache implements ExtendedRe
}
@Override public CacheRequest put(URI uri, URLConnection urlConnection) throws IOException {
if (!(urlConnection instanceof OkHttpConnection)) {
if (!(urlConnection instanceof HttpURLConnection)) {
return null;
}
OkHttpConnection httpConnection = (OkHttpConnection) urlConnection;
HttpURLConnection httpConnection = (HttpURLConnection) urlConnection;
String requestMethod = httpConnection.getRequestMethod();
String key = uriToKey(uri);
@@ -181,8 +180,8 @@ public final class HttpResponseCache extends ResponseCache implements ExtendedRe
* not updated. If the stored response has changed since {@code
* conditionalCacheHit} was returned, this does nothing.
*/
@Override public void update(CacheResponse conditionalCacheHit, OkHttpConnection httpConnection)
throws IOException {
@Override public void update(CacheResponse conditionalCacheHit,
HttpURLConnection httpConnection) throws IOException {
HttpEngine httpEngine = getHttpEngine(httpConnection);
URI uri = httpEngine.getUri();
ResponseHeaders response = httpEngine.getResponseHeaders();
@@ -408,7 +407,7 @@ public final class HttpResponseCache extends ResponseCache implements ExtendedRe
}
}
public Entry(URI uri, RawHeaders varyHeaders, OkHttpConnection httpConnection)
public Entry(URI uri, RawHeaders varyHeaders, HttpURLConnection httpConnection)
throws IOException {
this.uri = uri.toString();
this.varyHeaders = varyHeaders;
@@ -416,8 +415,7 @@ public final class HttpResponseCache extends ResponseCache implements ExtendedRe
this.responseHeaders = RawHeaders.fromMultimap(httpConnection.getHeaderFields(), true);
if (isHttps()) {
OkHttpsConnection httpsConnection
= (OkHttpsConnection) httpConnection;
HttpsURLConnection httpsConnection = (HttpsURLConnection) httpConnection;
cipherSuite = httpsConnection.getCipherSuite();
Certificate[] peerCertificatesNonFinal = null;
try {

View File

@@ -17,12 +17,12 @@
package libcore.net.http;
import com.squareup.okhttp.OkHttpConnection;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpRetryException;
import java.net.HttpURLConnection;
import java.net.InetSocketAddress;
import java.net.ProtocolException;
import java.net.Proxy;
@@ -50,7 +50,7 @@ import libcore.util.Libcore;
* connection} field on this class for null/non-null to determine of an instance
* is currently connected to a server.
*/
public class HttpURLConnectionImpl extends OkHttpConnection {
public class HttpURLConnectionImpl extends HttpURLConnection {
/**
* HTTP 1.1 doesn't specify how many redirects to follow, but HTTP/1.0
* recommended 5. http://www.w3.org/Protocols/HTTP/1.0/spec.html#Code3xx

View File

@@ -16,12 +16,11 @@
*/
package libcore.net.http;
import com.squareup.okhttp.OkHttpConnection;
import com.squareup.okhttp.OkHttpsConnection;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.CacheResponse;
import java.net.HttpURLConnection;
import java.net.ProtocolException;
import java.net.Proxy;
import java.net.SecureCacheResponse;
@@ -32,11 +31,12 @@ import java.security.cert.Certificate;
import java.util.List;
import java.util.Map;
import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLPeerUnverifiedException;
import javax.net.ssl.SSLSocket;
import javax.net.ssl.SSLSocketFactory;
public final class HttpsURLConnectionImpl extends OkHttpsConnection {
public final class HttpsURLConnectionImpl extends HttpsURLConnection {
/** HttpUrlConnectionDelegate allows reuse of HttpURLConnectionImpl. */
private final HttpUrlConnectionDelegate delegate;
@@ -439,7 +439,7 @@ public final class HttpsURLConnectionImpl extends OkHttpsConnection {
return enclosing.getHostnameVerifier();
}
@Override protected OkHttpConnection getHttpConnectionToCache() {
@Override protected HttpURLConnection getHttpConnectionToCache() {
return enclosing;
}

View File

@@ -16,9 +16,9 @@
package libcore.util;
import com.squareup.okhttp.OkHttpConnection;
import java.io.IOException;
import java.net.CacheResponse;
import java.net.HttpURLConnection;
/**
* A response cache that supports statistics tracking and updating stored
@@ -51,5 +51,6 @@ public interface ExtendedResponseCache {
* Updates stored HTTP headers using a hit on a conditional GET.
* @hide
*/
void update(CacheResponse conditionalCacheHit, OkHttpConnection httpConnection) throws IOException;
void update(CacheResponse conditionalCacheHit, HttpURLConnection httpConnection)
throws IOException;
}

View File

@@ -16,18 +16,18 @@
package libcore.net.http;
import com.squareup.okhttp.OkHttpConnection;
import com.squareup.okhttp.OkHttpsConnection;
import com.squareup.okhttp.OkHttpClient;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.URL;
import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLSession;
public final class ExternalSpdyExample {
public static void main(String[] args) throws Exception {
URL url = new URL("https://www.google.ca/");
OkHttpsConnection connection = (OkHttpsConnection) OkHttpConnection.open(url);
HttpsURLConnection connection = (HttpsURLConnection) new OkHttpClient().open(url);
connection.setHostnameVerifier(new HostnameVerifier() {
@Override public boolean verify(String s, SSLSession sslSession) {

View File

@@ -19,7 +19,7 @@ package libcore.net.http;
import com.google.mockwebserver.MockResponse;
import com.google.mockwebserver.MockWebServer;
import com.google.mockwebserver.RecordedRequest;
import com.squareup.okhttp.OkHttpConnection;
import com.squareup.okhttp.OkHttpClient;
import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.File;
@@ -89,8 +89,8 @@ public final class HttpResponseCacheTest extends TestCase {
super.tearDown();
}
private static OkHttpConnection openConnection(URL url) {
return OkHttpConnection.open(url);
private static HttpURLConnection openConnection(URL url) {
return new OkHttpClient().open(url);
}
/**
@@ -142,7 +142,7 @@ public final class HttpResponseCacheTest extends TestCase {
server.play();
URL url = server.getUrl("/");
OkHttpConnection conn = openConnection(url);
HttpURLConnection conn = openConnection(url);
try {
conn.getResponseCode();
fail();
@@ -172,7 +172,7 @@ public final class HttpResponseCacheTest extends TestCase {
server.play();
URL url = server.getUrl("/");
OkHttpConnection conn = openConnection(url);
HttpURLConnection conn = openConnection(url);
assertEquals(responseCode, conn.getResponseCode());
// exhaust the content stream
@@ -209,7 +209,7 @@ public final class HttpResponseCacheTest extends TestCase {
return null;
}
@Override public CacheRequest put(URI uri, URLConnection conn) throws IOException {
OkHttpConnection httpConnection = (OkHttpConnection) conn;
HttpURLConnection httpConnection = (HttpURLConnection) conn;
try {
httpConnection.getRequestProperties();
fail();
@@ -238,7 +238,7 @@ public final class HttpResponseCacheTest extends TestCase {
});
URL url = server.getUrl("/");
OkHttpConnection connection = openConnection(url);
HttpURLConnection connection = openConnection(url);
assertEquals(body, readAscii(connection));
assertEquals(1, cacheCount.get());
}
@@ -270,7 +270,7 @@ public final class HttpResponseCacheTest extends TestCase {
server.play();
// Make sure that calling skip() doesn't omit bytes from the cache.
OkHttpConnection urlConnection = openConnection(server.getUrl("/"));
HttpURLConnection urlConnection = openConnection(server.getUrl("/"));
InputStream in = urlConnection.getInputStream();
assertEquals("I love ", readAscii(urlConnection, "I love ".length()));
reliableSkip(in, "puppies but hate ".length());
@@ -361,7 +361,7 @@ public final class HttpResponseCacheTest extends TestCase {
server.enqueue(new MockResponse().setBody("DEF"));
server.play();
OkHttpConnection connection = openConnection(server.getUrl("/"));
HttpURLConnection connection = openConnection(server.getUrl("/"));
assertEquals("ABC", readAscii(connection));
connection = openConnection(server.getUrl("/")); // cached!
@@ -721,7 +721,7 @@ public final class HttpResponseCacheTest extends TestCase {
URL url = server.getUrl("/");
OkHttpConnection request1 = (OkHttpConnection) openConnection(url);
HttpURLConnection request1 = (HttpURLConnection) openConnection(url);
request1.setRequestMethod(requestMethod);
addRequestBodyIfNecessary(requestMethod, request1);
assertEquals("1", request1.getHeaderField("X-Response-ID"));
@@ -762,7 +762,7 @@ public final class HttpResponseCacheTest extends TestCase {
assertEquals("A", readAscii(openConnection(url)));
OkHttpConnection invalidate = openConnection(url);
HttpURLConnection invalidate = openConnection(url);
invalidate.setRequestMethod(requestMethod);
addRequestBodyIfNecessary(requestMethod, invalidate);
assertEquals("B", readAscii(invalidate));
@@ -960,7 +960,7 @@ public final class HttpResponseCacheTest extends TestCase {
// (no responses enqueued)
server.play();
OkHttpConnection connection = openConnection(server.getUrl("/"));
HttpURLConnection connection = openConnection(server.getUrl("/"));
connection.addRequestProperty("Cache-Control", "only-if-cached");
assertGatewayTimeout(connection);
}
@@ -984,7 +984,7 @@ public final class HttpResponseCacheTest extends TestCase {
server.play();
assertEquals("A", readAscii(openConnection(server.getUrl("/"))));
OkHttpConnection connection = openConnection(server.getUrl("/"));
HttpURLConnection connection = openConnection(server.getUrl("/"));
connection.addRequestProperty("Cache-Control", "only-if-cached");
assertGatewayTimeout(connection);
}
@@ -994,7 +994,7 @@ public final class HttpResponseCacheTest extends TestCase {
server.play();
assertEquals("A", readAscii(openConnection(server.getUrl("/"))));
OkHttpConnection connection = openConnection(server.getUrl("/"));
HttpURLConnection connection = openConnection(server.getUrl("/"));
connection.addRequestProperty("Cache-Control", "only-if-cached");
assertGatewayTimeout(connection);
}
@@ -1065,7 +1065,7 @@ public final class HttpResponseCacheTest extends TestCase {
URL url = server.getUrl("/");
assertEquals("A", readAscii(openConnection(url)));
OkHttpConnection connection = openConnection(url);
HttpURLConnection connection = openConnection(url);
connection.addRequestProperty(conditionName, conditionValue);
assertEquals(HttpURLConnection.HTTP_NOT_MODIFIED, connection.getResponseCode());
assertEquals("", readAscii(connection));
@@ -1092,7 +1092,7 @@ public final class HttpResponseCacheTest extends TestCase {
.setResponseCode(HttpURLConnection.HTTP_NOT_MODIFIED));
server.play();
OkHttpConnection connection = openConnection(server.getUrl("/"));
HttpURLConnection connection = openConnection(server.getUrl("/"));
String clientIfModifiedSince = formatDate(-24, TimeUnit.HOURS);
connection.addRequestProperty("If-Modified-Since", clientIfModifiedSince);
assertEquals(HttpURLConnection.HTTP_NOT_MODIFIED, connection.getResponseCode());
@@ -1281,11 +1281,11 @@ public final class HttpResponseCacheTest extends TestCase {
server.play();
URL url = server.getUrl("/");
OkHttpConnection frConnection = openConnection(url);
HttpURLConnection frConnection = openConnection(url);
frConnection.addRequestProperty("Accept-Language", "fr-CA");
assertEquals("A", readAscii(frConnection));
OkHttpConnection enConnection = openConnection(url);
HttpURLConnection enConnection = openConnection(url);
enConnection.addRequestProperty("Accept-Language", "en-US");
assertEquals("B", readAscii(enConnection));
}
@@ -1635,18 +1635,18 @@ public final class HttpResponseCacheTest extends TestCase {
server.play();
// cache miss; seed the cache
OkHttpConnection connection1 = openConnection(server.getUrl("/a"));
HttpURLConnection connection1 = openConnection(server.getUrl("/a"));
assertEquals("A", readAscii(connection1));
assertEquals(null, connection1.getHeaderField("Allow"));
// conditional cache hit; update the cache
OkHttpConnection connection2 = openConnection(server.getUrl("/a"));
HttpURLConnection connection2 = openConnection(server.getUrl("/a"));
assertEquals(HttpURLConnection.HTTP_OK, connection2.getResponseCode());
assertEquals("A", readAscii(connection2));
assertEquals("GET, HEAD", connection2.getHeaderField("Allow"));
// full cache hit
OkHttpConnection connection3 = openConnection(server.getUrl("/a"));
HttpURLConnection connection3 = openConnection(server.getUrl("/a"));
assertEquals("A", readAscii(connection3));
assertEquals("GET, HEAD", connection3.getHeaderField("Allow"));
@@ -1668,7 +1668,7 @@ public final class HttpResponseCacheTest extends TestCase {
return rfc1123.format(date);
}
private void addRequestBodyIfNecessary(String requestMethod, OkHttpConnection invalidate)
private void addRequestBodyIfNecessary(String requestMethod, HttpURLConnection invalidate)
throws IOException {
if (requestMethod.equals("POST") || requestMethod.equals("PUT")) {
invalidate.setDoOutput(true);
@@ -1728,21 +1728,21 @@ public final class HttpResponseCacheTest extends TestCase {
server.play();
URL valid = server.getUrl("/valid");
OkHttpConnection connection1 = openConnection(valid);
HttpURLConnection connection1 = openConnection(valid);
assertEquals("A", readAscii(connection1));
assertEquals(HttpURLConnection.HTTP_OK, connection1.getResponseCode());
assertEquals("A-OK", connection1.getResponseMessage());
OkHttpConnection connection2 = openConnection(valid);
HttpURLConnection connection2 = openConnection(valid);
assertEquals("A", readAscii(connection2));
assertEquals(HttpURLConnection.HTTP_OK, connection2.getResponseCode());
assertEquals("A-OK", connection2.getResponseMessage());
URL invalid = server.getUrl("/invalid");
OkHttpConnection connection3 = openConnection(invalid);
HttpURLConnection connection3 = openConnection(invalid);
assertEquals("B", readAscii(connection3));
assertEquals(HttpURLConnection.HTTP_OK, connection3.getResponseCode());
assertEquals("B-OK", connection3.getResponseMessage());
OkHttpConnection connection4 = openConnection(invalid);
HttpURLConnection connection4 = openConnection(invalid);
assertEquals("C", readAscii(connection4));
assertEquals(HttpURLConnection.HTTP_OK, connection4.getResponseCode());
assertEquals("C-OK", connection4.getResponseMessage());
@@ -1781,7 +1781,7 @@ public final class HttpResponseCacheTest extends TestCase {
* characters are returned and the stream is closed.
*/
private String readAscii(URLConnection connection, int count) throws IOException {
OkHttpConnection httpConnection = (OkHttpConnection) connection;
HttpURLConnection httpConnection = (HttpURLConnection) connection;
InputStream in = httpConnection.getResponseCode() < HttpURLConnection.HTTP_BAD_REQUEST
? connection.getInputStream()
: httpConnection.getErrorStream();
@@ -1807,7 +1807,7 @@ public final class HttpResponseCacheTest extends TestCase {
}
}
private void assertGatewayTimeout(OkHttpConnection connection) throws IOException {
private void assertGatewayTimeout(HttpURLConnection connection) throws IOException {
try {
connection.getInputStream();
fail();

View File

@@ -20,8 +20,7 @@ import com.google.mockwebserver.MockResponse;
import com.google.mockwebserver.MockWebServer;
import com.google.mockwebserver.RecordedRequest;
import com.google.mockwebserver.SocketPolicy;
import com.squareup.okhttp.OkHttpConnection;
import com.squareup.okhttp.OkHttpsConnection;
import com.squareup.okhttp.OkHttpClient;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
@@ -63,6 +62,7 @@ import java.util.concurrent.atomic.AtomicReference;
import java.util.zip.GZIPInputStream;
import java.util.zip.GZIPOutputStream;
import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLException;
import javax.net.ssl.SSLSession;
@@ -124,12 +124,12 @@ public final class URLConnectionTest extends TestCase {
super.tearDown();
}
private static OkHttpConnection openConnection(URL url) {
return OkHttpConnection.open(url);
private static HttpURLConnection openConnection(URL url) {
return new OkHttpClient().open(url);
}
private static OkHttpConnection openConnection(URL url, Proxy proxy) {
return OkHttpConnection.open(url, proxy);
private static HttpURLConnection openConnection(URL url, Proxy proxy) {
return new OkHttpClient().setProxy(proxy).open(url);
}
// TODO: test that request bodies are retransmitted on IP address failures
@@ -139,7 +139,7 @@ public final class URLConnectionTest extends TestCase {
server.enqueue(new MockResponse());
server.play();
OkHttpConnection urlConnection = openConnection(server.getUrl("/"));
HttpURLConnection urlConnection = openConnection(server.getUrl("/"));
urlConnection.addRequestProperty("D", "e");
urlConnection.addRequestProperty("D", "f");
assertEquals("f", urlConnection.getRequestProperty("D"));
@@ -200,7 +200,7 @@ public final class URLConnectionTest extends TestCase {
public void testGetRequestPropertyReturnsLastValue() throws Exception {
server.play();
OkHttpConnection urlConnection = openConnection(server.getUrl("/"));
HttpURLConnection urlConnection = openConnection(server.getUrl("/"));
urlConnection.addRequestProperty("A", "value1");
urlConnection.addRequestProperty("A", "value2");
assertEquals("value2", urlConnection.getRequestProperty("A"));
@@ -215,7 +215,7 @@ public final class URLConnectionTest extends TestCase {
.setChunkedBody("ABCDE\nFGHIJ\nKLMNO\nPQR", 8));
server.play();
OkHttpConnection urlConnection = openConnection(server.getUrl("/"));
HttpURLConnection urlConnection = openConnection(server.getUrl("/"));
assertEquals(200, urlConnection.getResponseCode());
assertEquals("Fantastic", urlConnection.getResponseMessage());
assertEquals("HTTP/1.0 200 Fantastic", urlConnection.getHeaderField(null));
@@ -245,7 +245,7 @@ public final class URLConnectionTest extends TestCase {
server.enqueue(new MockResponse().setStatus("HTP/1.1 200 OK"));
server.play();
OkHttpConnection urlConnection = openConnection(server.getUrl("/"));
HttpURLConnection urlConnection = openConnection(server.getUrl("/"));
try {
urlConnection.getResponseCode();
fail();
@@ -257,7 +257,7 @@ public final class URLConnectionTest extends TestCase {
server.enqueue(new MockResponse().setStatus("HTTP/1.1 2147483648 OK"));
server.play();
OkHttpConnection urlConnection = openConnection(server.getUrl("/"));
HttpURLConnection urlConnection = openConnection(server.getUrl("/"));
try {
urlConnection.getResponseCode();
fail();
@@ -269,7 +269,7 @@ public final class URLConnectionTest extends TestCase {
server.enqueue(new MockResponse().setStatus("HTTP/1.1 00a OK"));
server.play();
OkHttpConnection urlConnection = openConnection(server.getUrl("/"));
HttpURLConnection urlConnection = openConnection(server.getUrl("/"));
try {
urlConnection.getResponseCode();
fail();
@@ -281,7 +281,7 @@ public final class URLConnectionTest extends TestCase {
server.enqueue(new MockResponse().setStatus(" HTTP/1.1 2147483648 OK"));
server.play();
OkHttpConnection urlConnection = openConnection(server.getUrl("/"));
HttpURLConnection urlConnection = openConnection(server.getUrl("/"));
try {
urlConnection.getResponseCode();
fail();
@@ -294,7 +294,7 @@ public final class URLConnectionTest extends TestCase {
URL url = server.getUrl("/foo");
server.shutdown();
OkHttpConnection connection = openConnection(url);
HttpURLConnection connection = openConnection(url);
try {
connection.connect();
fail();
@@ -325,7 +325,7 @@ public final class URLConnectionTest extends TestCase {
ProxySelector.setDefault(proxySelector);
server2.shutdown();
OkHttpConnection connection = openConnection(server.getUrl("/def"));
HttpURLConnection connection = openConnection(server.getUrl("/def"));
connection.setDoOutput(true);
transferKind.setForRequest(connection, 4);
connection.getOutputStream().write("body".getBytes("UTF-8"));
@@ -337,14 +337,14 @@ public final class URLConnectionTest extends TestCase {
public void testGetErrorStreamOnSuccessfulRequest() throws Exception {
server.enqueue(new MockResponse().setBody("A"));
server.play();
OkHttpConnection connection = openConnection(server.getUrl("/"));
HttpURLConnection connection = openConnection(server.getUrl("/"));
assertNull(connection.getErrorStream());
}
public void testGetErrorStreamOnUnsuccessfulRequest() throws Exception {
server.enqueue(new MockResponse().setResponseCode(404).setBody("A"));
server.play();
OkHttpConnection connection = openConnection(server.getUrl("/"));
HttpURLConnection connection = openConnection(server.getUrl("/"));
assertEquals("A", readAscii(connection.getErrorStream(), Integer.MAX_VALUE));
}
@@ -460,7 +460,7 @@ public final class URLConnectionTest extends TestCase {
server.enqueue(new MockResponse());
server.play();
OkHttpConnection conn = openConnection(server.getUrl("/"));
HttpURLConnection conn = openConnection(server.getUrl("/"));
conn.setDoOutput(true);
conn.setRequestMethod("POST");
if (uploadKind == TransferKind.CHUNKED) {
@@ -497,7 +497,7 @@ public final class URLConnectionTest extends TestCase {
server.play();
URL url = server.getUrl("/");
OkHttpConnection conn = openConnection(url);
HttpURLConnection conn = openConnection(url);
conn.setDoInput(false);
assertEquals("def", conn.getHeaderField("abc"));
assertEquals(200, conn.getResponseCode());
@@ -513,7 +513,7 @@ public final class URLConnectionTest extends TestCase {
server.enqueue(new MockResponse().setBody("this response comes via HTTPS"));
server.play();
OkHttpsConnection connection = (OkHttpsConnection) openConnection(server.getUrl("/foo"));
HttpsURLConnection connection = (HttpsURLConnection) openConnection(server.getUrl("/foo"));
connection.setSSLSocketFactory(sslContext.getSocketFactory());
connection.setHostnameVerifier(new RecordingHostnameVerifier());
@@ -533,12 +533,12 @@ public final class URLConnectionTest extends TestCase {
SSLSocketFactory clientSocketFactory = sslContext.getSocketFactory();
RecordingHostnameVerifier hostnameVerifier = new RecordingHostnameVerifier();
OkHttpsConnection connection = (OkHttpsConnection) openConnection(server.getUrl("/"));
HttpsURLConnection connection = (HttpsURLConnection) openConnection(server.getUrl("/"));
connection.setSSLSocketFactory(clientSocketFactory);
connection.setHostnameVerifier(hostnameVerifier);
assertContent("this response comes via HTTPS", connection);
connection = (OkHttpsConnection) openConnection(server.getUrl("/"));
connection = (HttpsURLConnection) openConnection(server.getUrl("/"));
connection.setSSLSocketFactory(clientSocketFactory);
connection.setHostnameVerifier(hostnameVerifier);
assertContent("another response via HTTPS", connection);
@@ -555,12 +555,12 @@ public final class URLConnectionTest extends TestCase {
server.play();
// install a custom SSL socket factory so the server can be authorized
OkHttpsConnection connection = (OkHttpsConnection) openConnection(server.getUrl("/"));
HttpsURLConnection connection = (HttpsURLConnection) openConnection(server.getUrl("/"));
connection.setSSLSocketFactory(sslContext.getSocketFactory());
connection.setHostnameVerifier(new RecordingHostnameVerifier());
assertContent("this response comes via HTTPS", connection);
connection = (OkHttpsConnection) openConnection(server.getUrl("/"));
connection = (HttpsURLConnection) openConnection(server.getUrl("/"));
try {
readAscii(connection.getInputStream(), Integer.MAX_VALUE);
fail("without an SSL socket factory, the connection should fail");
@@ -574,7 +574,7 @@ public final class URLConnectionTest extends TestCase {
server.enqueue(new MockResponse().setBody("this response comes via SSL"));
server.play();
OkHttpsConnection connection = (OkHttpsConnection) openConnection(server.getUrl("/foo"));
HttpsURLConnection connection = (HttpsURLConnection) openConnection(server.getUrl("/foo"));
connection.setSSLSocketFactory(sslContext.getSocketFactory());
connection.setHostnameVerifier(new RecordingHostnameVerifier());
@@ -626,7 +626,7 @@ public final class URLConnectionTest extends TestCase {
server.play();
URL url = new URL("http://android.com/foo");
OkHttpConnection connection = proxyConfig.connect(server, url);
HttpURLConnection connection = proxyConfig.connect(server, url);
assertContent("this response comes via a proxy", connection);
RecordedRequest request = server.takeRequest();
@@ -675,7 +675,7 @@ public final class URLConnectionTest extends TestCase {
server.play();
URL url = server.getUrl("/foo");
OkHttpsConnection connection = (OkHttpsConnection) proxyConfig.connect(server, url);
HttpsURLConnection connection = (HttpsURLConnection) proxyConfig.connect(server, url);
connection.setSSLSocketFactory(sslContext.getSocketFactory());
connection.setHostnameVerifier(new RecordingHostnameVerifier());
@@ -716,7 +716,7 @@ public final class URLConnectionTest extends TestCase {
server.play();
URL url = new URL("https://android.com/foo");
OkHttpsConnection connection = (OkHttpsConnection) proxyConfig.connect(server, url);
HttpsURLConnection connection = (HttpsURLConnection) proxyConfig.connect(server, url);
connection.setSSLSocketFactory(sslContext.getSocketFactory());
connection.setHostnameVerifier(hostnameVerifier);
@@ -754,7 +754,7 @@ public final class URLConnectionTest extends TestCase {
server.play();
URL url = new URL("https://android.com/foo");
OkHttpsConnection connection = (OkHttpsConnection) openConnection(
HttpsURLConnection connection = (HttpsURLConnection) openConnection(
url, server.toProxyAddress());
connection.setSSLSocketFactory(sslContext.getSocketFactory());
@@ -795,7 +795,7 @@ public final class URLConnectionTest extends TestCase {
server.play();
URL url = new URL("https://android.com/foo");
OkHttpsConnection connection = (OkHttpsConnection) openConnection(
HttpsURLConnection connection = (HttpsURLConnection) openConnection(
url, server.toProxyAddress());
connection.addRequestProperty("Private", "Secret");
connection.addRequestProperty("Proxy-Authorization", "bar");
@@ -829,7 +829,7 @@ public final class URLConnectionTest extends TestCase {
server.play();
URL url = new URL("https://android.com/foo");
OkHttpsConnection connection = (OkHttpsConnection) openConnection(
HttpsURLConnection connection = (HttpsURLConnection) openConnection(
url, server.toProxyAddress());
connection.setSSLSocketFactory(sslContext.getSocketFactory());
connection.setHostnameVerifier(new RecordingHostnameVerifier());
@@ -859,7 +859,7 @@ public final class URLConnectionTest extends TestCase {
server.play();
URL url = new URL("https://android.com/foo");
OkHttpsConnection connection = (OkHttpsConnection) openConnection(
HttpsURLConnection connection = (HttpsURLConnection) openConnection(
url, server.toProxyAddress());
connection.setRequestProperty("Connection", "close");
connection.setSSLSocketFactory(sslContext.getSocketFactory());
@@ -881,13 +881,13 @@ public final class URLConnectionTest extends TestCase {
server.play();
URL url = new URL("https://android.com/foo");
OkHttpsConnection connection1 = (OkHttpsConnection) openConnection(
HttpsURLConnection connection1 = (HttpsURLConnection) openConnection(
url, server.toProxyAddress());
connection1.setSSLSocketFactory(socketFactory);
connection1.setHostnameVerifier(hostnameVerifier);
assertContent("response 1", connection1);
OkHttpsConnection connection2 = (OkHttpsConnection) openConnection(
HttpsURLConnection connection2 = (HttpsURLConnection) openConnection(
url, server.toProxyAddress());
connection2.setSSLSocketFactory(socketFactory);
connection2.setHostnameVerifier(hostnameVerifier);
@@ -898,7 +898,7 @@ public final class URLConnectionTest extends TestCase {
server.enqueue(new MockResponse().setBody("ABCDEFGHIJKLMNOPQR"));
server.play();
OkHttpConnection connection = openConnection(server.getUrl("/"));
HttpURLConnection connection = openConnection(server.getUrl("/"));
InputStream in = connection.getInputStream();
assertEquals('A', (char) in.read());
connection.disconnect();
@@ -913,7 +913,7 @@ public final class URLConnectionTest extends TestCase {
server.enqueue(new MockResponse().setBody("A"));
server.play();
OkHttpConnection connection = openConnection(server.getUrl("/"));
HttpURLConnection connection = openConnection(server.getUrl("/"));
connection.disconnect();
assertContent("A", connection);
@@ -1035,7 +1035,7 @@ public final class URLConnectionTest extends TestCase {
server.play();
URL url = server.getUrl("/");
OkHttpConnection conn = openConnection(url);
HttpURLConnection conn = openConnection(url);
assertEquals(401, conn.getResponseCode());
assertEquals(401, conn.getResponseCode());
@@ -1165,8 +1165,8 @@ public final class URLConnectionTest extends TestCase {
URLConnection connection = openConnection(server.getUrl("/"));
if (tls) {
((OkHttpsConnection) connection).setSSLSocketFactory(socketFactory);
((OkHttpsConnection) connection).setHostnameVerifier(hostnameVerifier);
((HttpsURLConnection) connection).setSSLSocketFactory(socketFactory);
((HttpsURLConnection) connection).setHostnameVerifier(hostnameVerifier);
}
connection.addRequestProperty("Accept-Encoding", "gzip");
InputStream gunzippedIn = new GZIPInputStream(connection.getInputStream());
@@ -1175,8 +1175,8 @@ public final class URLConnectionTest extends TestCase {
connection = openConnection(server.getUrl("/"));
if (tls) {
((OkHttpsConnection) connection).setSSLSocketFactory(socketFactory);
((OkHttpsConnection) connection).setHostnameVerifier(hostnameVerifier);
((HttpsURLConnection) connection).setSSLSocketFactory(socketFactory);
((HttpsURLConnection) connection).setHostnameVerifier(hostnameVerifier);
}
assertEquals("two (identity)", readAscii(connection.getInputStream(), Integer.MAX_VALUE));
assertEquals(1, server.takeRequest().getSequenceNumber());
@@ -1206,7 +1206,7 @@ public final class URLConnectionTest extends TestCase {
assertEquals("ABCDE", readAscii(in1, 5));
in1.close();
OkHttpConnection connection2 = openConnection(server.getUrl("/"));
HttpURLConnection connection2 = openConnection(server.getUrl("/"));
InputStream in2 = connection2.getInputStream();
assertEquals("LMNOP", readAscii(in2, 5));
in2.close();
@@ -1225,7 +1225,7 @@ public final class URLConnectionTest extends TestCase {
server.enqueue(new MockResponse());
server.play();
OkHttpConnection urlConnection = openConnection(server.getUrl("/"));
HttpURLConnection urlConnection = openConnection(server.getUrl("/"));
urlConnection.setChunkedStreamingMode(8);
urlConnection.setDoOutput(true);
OutputStream outputStream = urlConnection.getOutputStream();
@@ -1254,7 +1254,7 @@ public final class URLConnectionTest extends TestCase {
server.play();
Authenticator.setDefault(new RecordingAuthenticator());
OkHttpConnection connection = openConnection(server.getUrl("/"));
HttpURLConnection connection = openConnection(server.getUrl("/"));
connection.setDoOutput(true);
byte[] requestBody = { 'A', 'B', 'C', 'D' };
if (streamingMode == StreamingMode.FIXED_LENGTH) {
@@ -1345,7 +1345,7 @@ public final class URLConnectionTest extends TestCase {
server.enqueue(pleaseAuthenticate);
server.play();
OkHttpConnection connection = proxy
HttpURLConnection connection = proxy
? openConnection(new URL("http://android.com"), server.toProxyAddress())
: openConnection(server.getUrl("/"));
assertEquals(responseCode, connection.getResponseCode());
@@ -1364,7 +1364,7 @@ public final class URLConnectionTest extends TestCase {
}
private void assertValidRequestMethod(String requestMethod) throws Exception {
OkHttpConnection connection = openConnection(server.getUrl("/"));
HttpURLConnection connection = openConnection(server.getUrl("/"));
connection.setRequestMethod(requestMethod);
assertEquals(requestMethod, connection.getRequestMethod());
}
@@ -1380,7 +1380,7 @@ public final class URLConnectionTest extends TestCase {
}
private void assertInvalidRequestMethod(String requestMethod) throws Exception {
OkHttpConnection connection = openConnection(server.getUrl("/"));
HttpURLConnection connection = openConnection(server.getUrl("/"));
try {
connection.setRequestMethod(requestMethod);
fail();
@@ -1390,7 +1390,7 @@ public final class URLConnectionTest extends TestCase {
public void testCannotSetNegativeFixedLengthStreamingMode() throws Exception {
server.play();
OkHttpConnection connection = openConnection(server.getUrl("/"));
HttpURLConnection connection = openConnection(server.getUrl("/"));
try {
connection.setFixedLengthStreamingMode(-2);
fail();
@@ -1400,14 +1400,14 @@ public final class URLConnectionTest extends TestCase {
public void testCanSetNegativeChunkedStreamingMode() throws Exception {
server.play();
OkHttpConnection connection = openConnection(server.getUrl("/"));
HttpURLConnection connection = openConnection(server.getUrl("/"));
connection.setChunkedStreamingMode(-2);
}
public void testCannotSetFixedLengthStreamingModeAfterConnect() throws Exception {
server.enqueue(new MockResponse().setBody("A"));
server.play();
OkHttpConnection connection = openConnection(server.getUrl("/"));
HttpURLConnection connection = openConnection(server.getUrl("/"));
assertEquals("A", readAscii(connection.getInputStream(), Integer.MAX_VALUE));
try {
connection.setFixedLengthStreamingMode(1);
@@ -1419,7 +1419,7 @@ public final class URLConnectionTest extends TestCase {
public void testCannotSetChunkedStreamingModeAfterConnect() throws Exception {
server.enqueue(new MockResponse().setBody("A"));
server.play();
OkHttpConnection connection = openConnection(server.getUrl("/"));
HttpURLConnection connection = openConnection(server.getUrl("/"));
assertEquals("A", readAscii(connection.getInputStream(), Integer.MAX_VALUE));
try {
connection.setChunkedStreamingMode(1);
@@ -1430,7 +1430,7 @@ public final class URLConnectionTest extends TestCase {
public void testCannotSetFixedLengthStreamingModeAfterChunkedStreamingMode() throws Exception {
server.play();
OkHttpConnection connection = openConnection(server.getUrl("/"));
HttpURLConnection connection = openConnection(server.getUrl("/"));
connection.setChunkedStreamingMode(1);
try {
connection.setFixedLengthStreamingMode(1);
@@ -1441,7 +1441,7 @@ public final class URLConnectionTest extends TestCase {
public void testCannotSetChunkedStreamingModeAfterFixedLengthStreamingMode() throws Exception {
server.play();
OkHttpConnection connection = openConnection(server.getUrl("/"));
HttpURLConnection connection = openConnection(server.getUrl("/"));
connection.setFixedLengthStreamingMode(1);
try {
connection.setChunkedStreamingMode(1);
@@ -1467,7 +1467,7 @@ public final class URLConnectionTest extends TestCase {
server.enqueue(new MockResponse().setBody("Success!"));
server.play();
OkHttpsConnection connection = (OkHttpsConnection) openConnection(server.getUrl("/"));
HttpsURLConnection connection = (HttpsURLConnection) openConnection(server.getUrl("/"));
connection.setSSLSocketFactory(sslContext.getSocketFactory());
connection.setHostnameVerifier(new RecordingHostnameVerifier());
connection.setDoOutput(true);
@@ -1510,7 +1510,7 @@ public final class URLConnectionTest extends TestCase {
server.play();
Authenticator.setDefault(new RecordingAuthenticator());
OkHttpConnection connection = openConnection(server.getUrl("/"));
HttpURLConnection connection = openConnection(server.getUrl("/"));
connection.setDoOutput(true);
byte[] requestBody = { 'A', 'B', 'C', 'D' };
OutputStream outputStream = connection.getOutputStream();
@@ -1545,7 +1545,7 @@ public final class URLConnectionTest extends TestCase {
server.play();
Authenticator.setDefault(new RecordingAuthenticator());
OkHttpConnection connection = openConnection(server.getUrl("/"));
HttpURLConnection connection = openConnection(server.getUrl("/"));
assertEquals("Successful auth!", readAscii(connection.getInputStream(), Integer.MAX_VALUE));
// no authorization header for the first request...
@@ -1574,7 +1574,7 @@ public final class URLConnectionTest extends TestCase {
private void testRedirected(TransferKind transferKind, boolean reuse) throws Exception {
MockResponse response = new MockResponse()
.setResponseCode(OkHttpConnection.HTTP_MOVED_TEMP)
.setResponseCode(HttpURLConnection.HTTP_MOVED_TEMP)
.addHeader("Location: /foo");
transferKind.setBody(response, "This page has moved!", 10);
server.enqueue(response);
@@ -1603,7 +1603,7 @@ public final class URLConnectionTest extends TestCase {
server.enqueue(new MockResponse().setBody("This is the new location!"));
server.play();
OkHttpsConnection connection = (OkHttpsConnection) openConnection(server.getUrl("/"));
HttpsURLConnection connection = (HttpsURLConnection) openConnection(server.getUrl("/"));
connection.setSSLSocketFactory(sslContext.getSocketFactory());
connection.setHostnameVerifier(new RecordingHostnameVerifier());
assertEquals("This is the new location!",
@@ -1624,7 +1624,7 @@ public final class URLConnectionTest extends TestCase {
.setBody("This page has moved!"));
server.play();
OkHttpsConnection connection = (OkHttpsConnection) openConnection(server.getUrl("/"));
HttpsURLConnection connection = (HttpsURLConnection) openConnection(server.getUrl("/"));
connection.setSSLSocketFactory(sslContext.getSocketFactory());
connection.setHostnameVerifier(new RecordingHostnameVerifier());
assertEquals("This page has moved!",
@@ -1633,12 +1633,12 @@ public final class URLConnectionTest extends TestCase {
public void testNotRedirectedFromHttpToHttps() throws IOException, InterruptedException {
server.enqueue(new MockResponse()
.setResponseCode(OkHttpConnection.HTTP_MOVED_TEMP)
.setResponseCode(HttpURLConnection.HTTP_MOVED_TEMP)
.addHeader("Location: https://anyhost/foo")
.setBody("This page has moved!"));
server.play();
OkHttpConnection connection = openConnection(server.getUrl("/"));
HttpURLConnection connection = openConnection(server.getUrl("/"));
assertEquals("This page has moved!",
readAscii(connection.getInputStream(), Integer.MAX_VALUE));
}
@@ -1649,7 +1649,7 @@ public final class URLConnectionTest extends TestCase {
server2.play();
server.enqueue(new MockResponse()
.setResponseCode(OkHttpConnection.HTTP_MOVED_TEMP)
.setResponseCode(HttpURLConnection.HTTP_MOVED_TEMP)
.addHeader("Location: " + server2.getUrl("/").toString())
.setBody("This page has moved!"));
server.enqueue(new MockResponse().setBody("This is the first server again!"));
@@ -1676,19 +1676,19 @@ public final class URLConnectionTest extends TestCase {
public void testResponse300MultipleChoiceWithPost() throws Exception {
// Chrome doesn't follow the redirect, but Firefox and the RI both do
testResponseRedirectedWithPost(OkHttpConnection.HTTP_MULT_CHOICE);
testResponseRedirectedWithPost(HttpURLConnection.HTTP_MULT_CHOICE);
}
public void testResponse301MovedPermanentlyWithPost() throws Exception {
testResponseRedirectedWithPost(OkHttpConnection.HTTP_MOVED_PERM);
testResponseRedirectedWithPost(HttpURLConnection.HTTP_MOVED_PERM);
}
public void testResponse302MovedTemporarilyWithPost() throws Exception {
testResponseRedirectedWithPost(OkHttpConnection.HTTP_MOVED_TEMP);
testResponseRedirectedWithPost(HttpURLConnection.HTTP_MOVED_TEMP);
}
public void testResponse303SeeOtherWithPost() throws Exception {
testResponseRedirectedWithPost(OkHttpConnection.HTTP_SEE_OTHER);
testResponseRedirectedWithPost(HttpURLConnection.HTTP_SEE_OTHER);
}
private void testResponseRedirectedWithPost(int redirectCode) throws Exception {
@@ -1699,7 +1699,7 @@ public final class URLConnectionTest extends TestCase {
server.enqueue(new MockResponse().setBody("Page 2"));
server.play();
OkHttpConnection connection = openConnection(server.getUrl("/page1"));
HttpURLConnection connection = openConnection(server.getUrl("/page1"));
connection.setDoOutput(true);
byte[] requestBody = { 'A', 'B', 'C', 'D' };
OutputStream outputStream = connection.getOutputStream();
@@ -1719,12 +1719,12 @@ public final class URLConnectionTest extends TestCase {
public void testResponse305UseProxy() throws Exception {
server.play();
server.enqueue(new MockResponse()
.setResponseCode(OkHttpConnection.HTTP_USE_PROXY)
.setResponseCode(HttpURLConnection.HTTP_USE_PROXY)
.addHeader("Location: " + server.getUrl("/"))
.setBody("This page has moved!"));
server.enqueue(new MockResponse().setBody("Proxy Response"));
OkHttpConnection connection = openConnection(server.getUrl("/foo"));
HttpURLConnection connection = openConnection(server.getUrl("/foo"));
// Fails on the RI, which gets "Proxy Response"
assertEquals("This page has moved!",
readAscii(connection.getInputStream(), Integer.MAX_VALUE));
@@ -1819,7 +1819,7 @@ public final class URLConnectionTest extends TestCase {
server.enqueue(new MockResponse());
server.play();
OkHttpConnection urlConnection = openConnection(server.getUrl("/"));
HttpURLConnection urlConnection = openConnection(server.getUrl("/"));
urlConnection.setRequestProperty("Transfer-encoding", "chunked");
urlConnection.setDoOutput(true);
urlConnection.getOutputStream().write("ABC".getBytes("UTF-8"));
@@ -1834,11 +1834,11 @@ public final class URLConnectionTest extends TestCase {
server.enqueue(new MockResponse());
server.play();
OkHttpConnection a = openConnection(server.getUrl("/"));
HttpURLConnection a = openConnection(server.getUrl("/"));
a.setRequestProperty("Connection", "close");
assertEquals(200, a.getResponseCode());
OkHttpConnection b = openConnection(server.getUrl("/"));
HttpURLConnection b = openConnection(server.getUrl("/"));
assertEquals(200, b.getResponseCode());
assertEquals(0, server.takeRequest().getSequenceNumber());
@@ -1851,10 +1851,10 @@ public final class URLConnectionTest extends TestCase {
server.enqueue(new MockResponse());
server.play();
OkHttpConnection a = openConnection(server.getUrl("/"));
HttpURLConnection a = openConnection(server.getUrl("/"));
assertEquals(200, a.getResponseCode());
OkHttpConnection b = openConnection(server.getUrl("/"));
HttpURLConnection b = openConnection(server.getUrl("/"));
assertEquals(200, b.getResponseCode());
assertEquals(0, server.takeRequest().getSequenceNumber());
@@ -1864,7 +1864,7 @@ public final class URLConnectionTest extends TestCase {
public void testConnectionCloseWithRedirect() throws IOException, InterruptedException {
MockResponse response = new MockResponse()
.setResponseCode(OkHttpConnection.HTTP_MOVED_TEMP)
.setResponseCode(HttpURLConnection.HTTP_MOVED_TEMP)
.addHeader("Location: /foo")
.addHeader("Connection: close");
server.enqueue(response);
@@ -1882,7 +1882,7 @@ public final class URLConnectionTest extends TestCase {
public void testResponseCodeDisagreesWithHeaders() throws IOException, InterruptedException {
server.enqueue(new MockResponse()
.setResponseCode(OkHttpConnection.HTTP_NO_CONTENT)
.setResponseCode(HttpURLConnection.HTTP_NO_CONTENT)
.setBody("This body is not allowed!"));
server.play();
@@ -1923,7 +1923,7 @@ public final class URLConnectionTest extends TestCase {
server.enqueue(new MockResponse().setBody("abc"));
server.play();
OkHttpConnection connection = openConnection(server.getUrl("/"));
HttpURLConnection connection = openConnection(server.getUrl("/"));
connection.setDoOutput(true);
byte[] upload = "def".getBytes("UTF-8");
@@ -1954,7 +1954,7 @@ public final class URLConnectionTest extends TestCase {
}
server.play();
OkHttpConnection connection = openConnection(server.getUrl("/"));
HttpURLConnection connection = openConnection(server.getUrl("/"));
try {
connection.getInputStream();
fail();
@@ -1969,7 +1969,7 @@ public final class URLConnectionTest extends TestCase {
}
public void testDnsFailureThrowsIOException() throws IOException {
OkHttpConnection connection = openConnection(new URL("http://host.unlikelytld"));
HttpURLConnection connection = openConnection(new URL("http://host.unlikelytld"));
try {
connection.connect();
fail();
@@ -1978,7 +1978,7 @@ public final class URLConnectionTest extends TestCase {
}
public void testMalformedUrlThrowsUnknownHostException() throws IOException {
OkHttpConnection connection = openConnection(new URL("http:///foo.html"));
HttpURLConnection connection = openConnection(new URL("http:///foo.html"));
try {
connection.connect();
fail();
@@ -2103,7 +2103,7 @@ public final class URLConnectionTest extends TestCase {
});
try {
OkHttpConnection connection = openConnection(url);
HttpURLConnection connection = openConnection(url);
connection.getResponseCode();
} catch (Exception expected) {
if (expected.getCause() instanceof URISyntaxException) {
@@ -2139,7 +2139,7 @@ public final class URLConnectionTest extends TestCase {
server.enqueue(new MockResponse().setBody("abcdef"));
server.play();
OkHttpConnection connection = openConnection(server.getUrl("/"));
HttpURLConnection connection = openConnection(server.getUrl("/"));
InputStream in = connection.getInputStream();
assertEquals("abc", readAscii(in, 3));
in.close();
@@ -2158,7 +2158,7 @@ public final class URLConnectionTest extends TestCase {
.setSocketPolicy(SocketPolicy.DISCONNECT_AT_END));
server.play();
OkHttpConnection connection = openConnection(server.getUrl("/"));
HttpURLConnection connection = openConnection(server.getUrl("/"));
InputStream in = connection.getInputStream();
assertEquals("ABC", readAscii(in, 3));
assertEquals(-1, in.read());
@@ -2170,7 +2170,7 @@ public final class URLConnectionTest extends TestCase {
.addHeader("Content-Type: text/plain")
.setBody("A"));
server.play();
OkHttpConnection connection = openConnection(server.getUrl("/"));
HttpURLConnection connection = openConnection(server.getUrl("/"));
InputStream in = (InputStream) connection.getContent();
assertEquals("A", readAscii(in, Integer.MAX_VALUE));
}
@@ -2180,7 +2180,7 @@ public final class URLConnectionTest extends TestCase {
.addHeader("Content-Type: text/plain")
.setBody("A"));
server.play();
OkHttpConnection connection = openConnection(server.getUrl("/"));
HttpURLConnection connection = openConnection(server.getUrl("/"));
try {
connection.getContent(null);
fail();
@@ -2198,7 +2198,7 @@ public final class URLConnectionTest extends TestCase {
public void testGetOutputStreamOnGetFails() throws Exception {
server.enqueue(new MockResponse());
server.play();
OkHttpConnection connection = openConnection(server.getUrl("/"));
HttpURLConnection connection = openConnection(server.getUrl("/"));
try {
connection.getOutputStream();
fail();
@@ -2209,7 +2209,7 @@ public final class URLConnectionTest extends TestCase {
public void testGetOutputAfterGetInputStreamFails() throws Exception {
server.enqueue(new MockResponse());
server.play();
OkHttpConnection connection = openConnection(server.getUrl("/"));
HttpURLConnection connection = openConnection(server.getUrl("/"));
connection.setDoOutput(true);
try {
connection.getInputStream();
@@ -2222,7 +2222,7 @@ public final class URLConnectionTest extends TestCase {
public void testSetDoOutputOrDoInputAfterConnectFails() throws Exception {
server.enqueue(new MockResponse());
server.play();
OkHttpConnection connection = openConnection(server.getUrl("/"));
HttpURLConnection connection = openConnection(server.getUrl("/"));
connection.connect();
try {
connection.setDoOutput(true);
@@ -2240,7 +2240,7 @@ public final class URLConnectionTest extends TestCase {
public void testClientSendsContentLength() throws Exception {
server.enqueue(new MockResponse().setBody("A"));
server.play();
OkHttpConnection connection = openConnection(server.getUrl("/"));
HttpURLConnection connection = openConnection(server.getUrl("/"));
connection.setDoOutput(true);
OutputStream out = connection.getOutputStream();
out.write(new byte[] { 'A', 'B', 'C' });
@@ -2253,7 +2253,7 @@ public final class URLConnectionTest extends TestCase {
public void testGetContentLengthConnects() throws Exception {
server.enqueue(new MockResponse().setBody("ABC"));
server.play();
OkHttpConnection connection = openConnection(server.getUrl("/"));
HttpURLConnection connection = openConnection(server.getUrl("/"));
assertEquals(3, connection.getContentLength());
connection.disconnect();
}
@@ -2263,7 +2263,7 @@ public final class URLConnectionTest extends TestCase {
.addHeader("Content-Type: text/plain")
.setBody("ABC"));
server.play();
OkHttpConnection connection = openConnection(server.getUrl("/"));
HttpURLConnection connection = openConnection(server.getUrl("/"));
assertEquals("text/plain", connection.getContentType());
connection.disconnect();
}
@@ -2273,7 +2273,7 @@ public final class URLConnectionTest extends TestCase {
.addHeader("Content-Encoding: identity")
.setBody("ABC"));
server.play();
OkHttpConnection connection = openConnection(server.getUrl("/"));
HttpURLConnection connection = openConnection(server.getUrl("/"));
assertEquals("identity", connection.getContentEncoding());
connection.disconnect();
}
@@ -2336,7 +2336,7 @@ public final class URLConnectionTest extends TestCase {
throws IOException {
connection.connect();
assertEquals(expected, readAscii(connection.getInputStream(), limit));
((OkHttpConnection) connection).disconnect();
((HttpURLConnection) connection).disconnect();
}
private void assertContent(String expected, URLConnection connection) throws IOException {
@@ -2365,7 +2365,7 @@ public final class URLConnectionTest extends TestCase {
throws IOException {
response.setChunkedBody(content, chunkSize);
}
@Override void setForRequest(OkHttpConnection connection, int contentLength) {
@Override void setForRequest(HttpURLConnection connection, int contentLength) {
connection.setChunkedStreamingMode(5);
}
},
@@ -2373,7 +2373,7 @@ public final class URLConnectionTest extends TestCase {
@Override void setBody(MockResponse response, byte[] content, int chunkSize) {
response.setBody(content);
}
@Override void setForRequest(OkHttpConnection connection, int contentLength) {
@Override void setForRequest(HttpURLConnection connection, int contentLength) {
connection.setChunkedStreamingMode(contentLength);
}
},
@@ -2388,14 +2388,14 @@ public final class URLConnectionTest extends TestCase {
}
}
}
@Override void setForRequest(OkHttpConnection connection, int contentLength) {
@Override void setForRequest(HttpURLConnection connection, int contentLength) {
}
};
abstract void setBody(MockResponse response, byte[] content, int chunkSize)
throws IOException;
abstract void setForRequest(OkHttpConnection connection, int contentLength);
abstract void setForRequest(HttpURLConnection connection, int contentLength);
void setBody(MockResponse response, String content, int chunkSize) throws IOException {
setBody(response, content.getBytes("UTF-8"), chunkSize);
@@ -2404,21 +2404,21 @@ public final class URLConnectionTest extends TestCase {
enum ProxyConfig {
NO_PROXY() {
@Override public OkHttpConnection connect(MockWebServer server, URL url)
@Override public HttpURLConnection connect(MockWebServer server, URL url)
throws IOException {
return openConnection(url, Proxy.NO_PROXY);
}
},
CREATE_ARG() {
@Override public OkHttpConnection connect(MockWebServer server, URL url)
@Override public HttpURLConnection connect(MockWebServer server, URL url)
throws IOException {
return openConnection(url, server.toProxyAddress());
}
},
PROXY_SYSTEM_PROPERTY() {
@Override public OkHttpConnection connect(MockWebServer server, URL url)
@Override public HttpURLConnection connect(MockWebServer server, URL url)
throws IOException {
System.setProperty("proxyHost", "localhost");
System.setProperty("proxyPort", Integer.toString(server.getPort()));
@@ -2427,7 +2427,7 @@ public final class URLConnectionTest extends TestCase {
},
HTTP_PROXY_SYSTEM_PROPERTY() {
@Override public OkHttpConnection connect(MockWebServer server, URL url)
@Override public HttpURLConnection connect(MockWebServer server, URL url)
throws IOException {
System.setProperty("http.proxyHost", "localhost");
System.setProperty("http.proxyPort", Integer.toString(server.getPort()));
@@ -2436,7 +2436,7 @@ public final class URLConnectionTest extends TestCase {
},
HTTPS_PROXY_SYSTEM_PROPERTY() {
@Override public OkHttpConnection connect(MockWebServer server, URL url)
@Override public HttpURLConnection connect(MockWebServer server, URL url)
throws IOException {
System.setProperty("https.proxyHost", "localhost");
System.setProperty("https.proxyPort", Integer.toString(server.getPort()));
@@ -2444,7 +2444,7 @@ public final class URLConnectionTest extends TestCase {
}
};
public abstract OkHttpConnection connect(MockWebServer server, URL url) throws IOException;
public abstract HttpURLConnection connect(MockWebServer server, URL url) throws IOException;
}
private static class RecordingTrustManager implements X509TrustManager {