Class HttpURLConnectionImpl
- java.lang.Object
-
- java.net.URLConnection
-
- java.net.HttpURLConnection
-
- com.squareup.okhttp.internal.huc.HttpURLConnectionImpl
-
public class HttpURLConnectionImpl extends HttpURLConnection
This implementation uses HttpEngine to send requests and receive responses. This class may use multiple HttpEngines to follow redirects, authentication retries, etc. to retrieve the final response body.What does 'connected' mean?
This class inherits aconnectedfield from the superclass. That field is not used to indicate not whether this URLConnection is currently connected. Instead, it indicates whether a connection has ever been attempted. Once a connection has been attempted, certain properties (request header fields, request method, etc.) are immutable.
-
-
Field Summary
Fields Modifier and Type Field Description protected HttpEnginehttpEngineprotected IOExceptionhttpEngineFailure-
Fields inherited from class java.net.HttpURLConnection
chunkLength, fixedContentLengthLong, HTTP_ACCEPTED, HTTP_BAD_GATEWAY, HTTP_BAD_METHOD, HTTP_BAD_REQUEST, HTTP_CLIENT_TIMEOUT, HTTP_CONFLICT, HTTP_CREATED, HTTP_ENTITY_TOO_LARGE, HTTP_FORBIDDEN, HTTP_GATEWAY_TIMEOUT, HTTP_GONE, HTTP_INTERNAL_ERROR, HTTP_LENGTH_REQUIRED, HTTP_MOVED_PERM, HTTP_MOVED_TEMP, HTTP_MULT_CHOICE, HTTP_NO_CONTENT, HTTP_NOT_ACCEPTABLE, HTTP_NOT_AUTHORITATIVE, HTTP_NOT_FOUND, HTTP_NOT_IMPLEMENTED, HTTP_NOT_MODIFIED, HTTP_OK, HTTP_PARTIAL, HTTP_PAYMENT_REQUIRED, HTTP_PRECON_FAILED, HTTP_PROXY_AUTH, HTTP_REQ_TOO_LONG, HTTP_RESET, HTTP_SEE_OTHER, HTTP_SERVER_ERROR, HTTP_UNAUTHORIZED, HTTP_UNAVAILABLE, HTTP_UNSUPPORTED_TYPE, HTTP_USE_PROXY, HTTP_VERSION, instanceFollowRedirects, method, responseCode, responseMessage
-
Fields inherited from class java.net.URLConnection
allowUserInteraction, connected, doInput, doOutput, ifModifiedSince, url, useCaches
-
-
Constructor Summary
Constructors Constructor Description HttpURLConnectionImpl(URL url, OkHttpClient client)
-
Method Summary
All Methods Instance Methods Concrete Methods Modifier and Type Method Description voidaddRequestProperty(String field, String value)Adds the given property to the request header.voidconnect()Opens a connection to the resource.voiddisconnect()Releases this connection so that its resources may be either reused or closed.intgetConnectTimeout()Returns the connect timeout in milliseconds.InputStreamgetErrorStream()Returns an input stream from the server in the case of error such as the requested file (txt, htm, html) is not found on the remote server.StringgetHeaderField(int position)Returns the value of the field atposition.StringgetHeaderField(String fieldName)Returns the value of the field corresponding to thefieldName, or null if there is no such field.StringgetHeaderFieldKey(int position)Returns the name of the header field at the given positionposnornullif there are fewer thanposnfields.Map<String,List<String>>getHeaderFields()Returns an unmodifiable map of the response-header fields and values.InputStreamgetInputStream()Returns anInputStreamfor reading data from the resource pointed by thisURLConnection.OutputStreamgetOutputStream()Returns anOutputStreamfor writing data to thisURLConnection.PermissiongetPermission()Returns the permission object (in this caseSocketPermission) with the host and the port number as the target name and"resolve, connect"as the action list.intgetReadTimeout()Returns the read timeout in milliseconds, or0if reads never timeout.Map<String,List<String>>getRequestProperties()Returns an unmodifiable map of general request properties used by this connection.StringgetRequestProperty(String field)Returns the value of the request header property specified by {code field} ornullif there is no field with this name.intgetResponseCode()Returns the response code returned by the remote HTTP server.StringgetResponseMessage()Returns the response message returned by the remote HTTP server.voidsetConnectTimeout(int timeoutMillis)Sets the maximum time in milliseconds to wait while connecting.voidsetFixedLengthStreamingMode(int contentLength)Equivalent tosetFixedLengthStreamingMode((long) contentLength), but available on earlier versions of Android and limited to 2 GiB.voidsetFixedLengthStreamingMode(long contentLength)Configures this connection to stream the request body with the known fixed byte count ofcontentLength.voidsetIfModifiedSince(long newValue)Sets the point of time since when the data must be modified to be transmitted.voidsetInstanceFollowRedirects(boolean followRedirects)Sets whether this connection follows redirects.voidsetReadTimeout(int timeoutMillis)Sets the maximum time to wait for an input stream read to complete before giving up.voidsetRequestMethod(String method)Sets the request command which will be sent to the remote HTTP server.voidsetRequestProperty(String field, String newValue)Sets the value of the specified request header field.booleanusingProxy()Returns true if either: A specific proxy was explicitly configured for this connection.-
Methods inherited from class java.net.HttpURLConnection
getContentEncoding, getFollowRedirects, getHeaderFieldDate, getInstanceFollowRedirects, getRequestMethod, setChunkedStreamingMode, setFollowRedirects
-
Methods inherited from class java.net.URLConnection
getAllowUserInteraction, getContent, getContent, getContentLength, getContentType, getDate, getDefaultAllowUserInteraction, getDefaultRequestProperty, getDefaultUseCaches, getDoInput, getDoOutput, getExpiration, getFileNameMap, getHeaderFieldInt, getIfModifiedSince, getLastModified, getURL, getUseCaches, guessContentTypeFromName, guessContentTypeFromStream, setAllowUserInteraction, setContentHandlerFactory, setDefaultAllowUserInteraction, setDefaultRequestProperty, setDefaultUseCaches, setDoInput, setDoOutput, setFileNameMap, setUseCaches, toString
-
-
-
-
Field Detail
-
httpEngineFailure
protected IOException httpEngineFailure
-
httpEngine
protected HttpEngine httpEngine
-
-
Constructor Detail
-
HttpURLConnectionImpl
public HttpURLConnectionImpl(URL url, OkHttpClient client)
-
-
Method Detail
-
connect
public final void connect() throws IOExceptionDescription copied from class:URLConnectionOpens a connection to the resource. This method will not reconnect to a resource after the initial connection has been closed.- Specified by:
connectin classURLConnection- Throws:
IOException- if an error occurs while connecting to the resource.
-
disconnect
public final void disconnect()
Description copied from class:HttpURLConnectionReleases this connection so that its resources may be either reused or closed.Unlike other Java implementations, this will not necessarily close socket connections that can be reused. You can disable all connection reuse by setting the
http.keepAlivesystem property tofalsebefore issuing any HTTP requests.- Specified by:
disconnectin classHttpURLConnection
-
getErrorStream
public final InputStream getErrorStream()
Returns an input stream from the server in the case of error such as the requested file (txt, htm, html) is not found on the remote server.- Overrides:
getErrorStreamin classHttpURLConnection- Returns:
- the error input stream returned by the server.
-
getHeaderField
public final String getHeaderField(int position)
Returns the value of the field atposition. Returns null if there are fewer thanpositionheaders.- Overrides:
getHeaderFieldin classURLConnection- Parameters:
position- the field position of the response header.- Returns:
- the value of the field at position
pos.
-
getHeaderField
public final String getHeaderField(String fieldName)
Returns the value of the field corresponding to thefieldName, or null if there is no such field. If the field has multiple values, the last value is returned.- Overrides:
getHeaderFieldin classURLConnection- Parameters:
fieldName- the name of the header field.- Returns:
- the value of the header field.
-
getHeaderFieldKey
public final String getHeaderFieldKey(int position)
Description copied from class:URLConnectionReturns the name of the header field at the given positionposnornullif there are fewer thanposnfields. The base implementation of this method returns alwaysnull.Some implementations (notably
HttpURLConnection) include a mapping for the null key; in HTTP's case, this maps to the HTTP status line and is treated as being at position 0 when indexing into the header fields.- Overrides:
getHeaderFieldKeyin classURLConnection- Parameters:
position- the position of the header field which has to be returned.- Returns:
- the header field name at the given position.
-
getHeaderFields
public final Map<String,List<String>> getHeaderFields()
Description copied from class:URLConnectionReturns an unmodifiable map of the response-header fields and values. The response-header field names are the key values of the map. The map values are lists of header field values associated with a particular key name.Some implementations (notably
HttpURLConnection) include a mapping for the null key; in HTTP's case, this maps to the HTTP status line and is treated as being at position 0 when indexing into the header fields.- Overrides:
getHeaderFieldsin classURLConnection- Returns:
- the response-header representing generic map.
-
getRequestProperties
public final Map<String,List<String>> getRequestProperties()
Description copied from class:URLConnectionReturns an unmodifiable map of general request properties used by this connection. The request property names are the key values of the map. The map values are lists of property values of the corresponding key name.- Overrides:
getRequestPropertiesin classURLConnection- Returns:
- the request-property representing generic map.
-
getInputStream
public final InputStream getInputStream() throws IOException
Description copied from class:URLConnectionReturns anInputStreamfor reading data from the resource pointed by thisURLConnection. It throws an UnknownServiceException by default. This method must be overridden by its subclasses.- Overrides:
getInputStreamin classURLConnection- Returns:
- the InputStream to read data from.
- Throws:
IOException- if no InputStream could be created.
-
getOutputStream
public final OutputStream getOutputStream() throws IOException
Description copied from class:URLConnectionReturns anOutputStreamfor writing data to thisURLConnection. It throws anUnknownServiceExceptionby default. This method must be overridden by its subclasses.- Overrides:
getOutputStreamin classURLConnection- Returns:
- the OutputStream to write data.
- Throws:
IOException- if no OutputStream could be created.
-
getPermission
public final Permission getPermission() throws IOException
Description copied from class:HttpURLConnectionReturns the permission object (in this caseSocketPermission) with the host and the port number as the target name and"resolve, connect"as the action list. If the port number of this URL instance is lower than0the port will be set to80.- Overrides:
getPermissionin classHttpURLConnection- Returns:
- the permission object required for this connection.
- Throws:
IOException- if an IO exception occurs during the creation of the permission object.
-
getRequestProperty
public final String getRequestProperty(String field)
Description copied from class:URLConnectionReturns the value of the request header property specified by {code field} ornullif there is no field with this name. The base implementation of this method returns alwaysnull.- Overrides:
getRequestPropertyin classURLConnection- Parameters:
field- the name of the request header property.- Returns:
- the value of the property.
-
setConnectTimeout
public void setConnectTimeout(int timeoutMillis)
Description copied from class:URLConnectionSets the maximum time in milliseconds to wait while connecting. Connecting to a server will fail with aSocketTimeoutExceptionif the timeout elapses before a connection is established. The default value of0causes us to do a blocking connect. This does not mean we will never time out, but it probably means you'll get a TCP timeout after several minutes.Warning: if the hostname resolves to multiple IP addresses, this client will try each in RFC 3484 order. If connecting to each of these addresses fails, multiple timeouts will elapse before the connect attempt throws an exception. Host names that support both IPv6 and IPv4 always have at least 2 IP addresses.
- Overrides:
setConnectTimeoutin classURLConnection
-
setInstanceFollowRedirects
public void setInstanceFollowRedirects(boolean followRedirects)
Description copied from class:HttpURLConnectionSets whether this connection follows redirects.- Overrides:
setInstanceFollowRedirectsin classHttpURLConnection- Parameters:
followRedirects-trueif this connection will follows redirects, false otherwise.
-
getConnectTimeout
public int getConnectTimeout()
Description copied from class:URLConnectionReturns the connect timeout in milliseconds. (See {#setConnectTimeout}.)- Overrides:
getConnectTimeoutin classURLConnection
-
setReadTimeout
public void setReadTimeout(int timeoutMillis)
Description copied from class:URLConnectionSets the maximum time to wait for an input stream read to complete before giving up. Reading will fail with aSocketTimeoutExceptionif the timeout elapses before data becomes available. The default value of0disables read timeouts; read attempts will block indefinitely.- Overrides:
setReadTimeoutin classURLConnection- Parameters:
timeoutMillis- the read timeout in milliseconds. Non-negative.
-
getReadTimeout
public int getReadTimeout()
Description copied from class:URLConnectionReturns the read timeout in milliseconds, or0if reads never timeout.- Overrides:
getReadTimeoutin classURLConnection
-
usingProxy
public final boolean usingProxy()
Returns true if either:- A specific proxy was explicitly configured for this connection.
- The response has already been retrieved, and a proxy was
selectedin order to get it.
Warning: This method may return false before attempting to connect and true afterwards.
- Specified by:
usingProxyin classHttpURLConnection- Returns:
trueif this connection passes a proxy server, false otherwise.
-
getResponseMessage
public String getResponseMessage() throws IOException
Description copied from class:HttpURLConnectionReturns the response message returned by the remote HTTP server.- Overrides:
getResponseMessagein classHttpURLConnection- Returns:
- the response message.
nullif no such response exists. - Throws:
IOException- if there is an error during the retrieval.- See Also:
HttpURLConnection.getResponseCode()
-
getResponseCode
public final int getResponseCode() throws IOExceptionDescription copied from class:HttpURLConnectionReturns the response code returned by the remote HTTP server.- Overrides:
getResponseCodein classHttpURLConnection- Returns:
- the response code, -1 if no valid response code.
- Throws:
IOException- if there is an IO error during the retrieval.- See Also:
HttpURLConnection.getResponseMessage()
-
setRequestProperty
public final void setRequestProperty(String field, String newValue)
Description copied from class:URLConnectionSets the value of the specified request header field. The value will only be used by the currentURLConnectioninstance. This method can only be called before the connection is established.- Overrides:
setRequestPropertyin classURLConnection- Parameters:
field- the request header field to be set.newValue- the new value of the specified property.
-
setIfModifiedSince
public void setIfModifiedSince(long newValue)
Description copied from class:URLConnectionSets the point of time since when the data must be modified to be transmitted. Some protocols transmit data only if it has been modified more recently than a particular time. The data will be transmitted regardless of its timestamp if this option is set to0.- Overrides:
setIfModifiedSincein classURLConnection- Parameters:
newValue- the time in milliseconds since January 1, 1970 GMT.- See Also:
URLConnection.ifModifiedSince
-
addRequestProperty
public final void addRequestProperty(String field, String value)
Description copied from class:URLConnectionAdds the given property to the request header. Existing properties with the same name will not be overwritten by this method.- Overrides:
addRequestPropertyin classURLConnection- Parameters:
field- the request property field name to add.value- the value of the property which is to add.
-
setRequestMethod
public void setRequestMethod(String method) throws ProtocolException
Description copied from class:HttpURLConnectionSets the request command which will be sent to the remote HTTP server. This method can only be called before the connection is made.- Overrides:
setRequestMethodin classHttpURLConnection- Parameters:
method- the string representing the method to be used.- Throws:
ProtocolException- if this is called after connected, or the method is not supported by this HTTP implementation.- See Also:
HttpURLConnection.getRequestMethod(),HttpURLConnection.method
-
setFixedLengthStreamingMode
public void setFixedLengthStreamingMode(int contentLength)
Description copied from class:HttpURLConnectionEquivalent tosetFixedLengthStreamingMode((long) contentLength), but available on earlier versions of Android and limited to 2 GiB.- Overrides:
setFixedLengthStreamingModein classHttpURLConnection
-
setFixedLengthStreamingMode
public void setFixedLengthStreamingMode(long contentLength)
Description copied from class:HttpURLConnectionConfigures this connection to stream the request body with the known fixed byte count ofcontentLength.- Overrides:
setFixedLengthStreamingModein classHttpURLConnection- Parameters:
contentLength- the fixed length of the HTTP request body.- See Also:
HttpURLConnection.setChunkedStreamingMode(int)
-
-