Class HttpsURLConnection
HttpsURLConnection extends HttpURLConnection
with support for https-specific features.
See http://www.w3.org/pub/WWW/Protocols/ and RFC 2818 for more details on the https specification.
This class uses HostnameVerifier and
SSLSocketFactory.
There are default implementations defined for both classes.
However, the implementations can be replaced on a per-class (static) or
per-instance basis. All new HttpsURLConnections instances
will be assigned
the "default" static values at instance creation, but they can be overridden
by calling the appropriate per-instance set method(s) before
connecting.
- Since:
- 1.4
-
Field Summary
FieldsModifier and TypeFieldDescriptionprotected HostnameVerifierThehostnameVerifierfor this object.Fields declared in class HttpURLConnection
chunkLength, fixedContentLength, 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, responseMessageModifier and TypeFieldDescriptionprotected intThe chunk-length when using chunked encoding streaming mode for output.protected intThe fixed content-length when using fixed-length streaming mode.protected longThe fixed content-length when using fixed-length streaming mode.static final intHTTP Status-Code 202: Accepted.static final intHTTP Status-Code 502: Bad Gateway.static final intHTTP Status-Code 405: Method Not Allowed.static final intHTTP Status-Code 400: Bad Request.static final intHTTP Status-Code 408: Request Time-Out.static final intHTTP Status-Code 409: Conflict.static final intHTTP Status-Code 201: Created.static final intHTTP Status-Code 413: Request Entity Too Large.static final intHTTP Status-Code 403: Forbidden.static final intHTTP Status-Code 504: Gateway Timeout.static final intHTTP Status-Code 410: Gone.static final intHTTP Status-Code 500: Internal Server Error.static final intHTTP Status-Code 411: Length Required.static final intHTTP Status-Code 301: Moved Permanently.static final intHTTP Status-Code 302: Temporary Redirect.static final intHTTP Status-Code 300: Multiple Choices.static final intHTTP Status-Code 204: No Content.static final intHTTP Status-Code 406: Not Acceptable.static final intHTTP Status-Code 203: Non-Authoritative Information.static final intHTTP Status-Code 404: Not Found.static final intHTTP Status-Code 501: Not Implemented.static final intHTTP Status-Code 304: Not Modified.static final intHTTP Status-Code 200: OK.static final intHTTP Status-Code 206: Partial Content.static final intHTTP Status-Code 402: Payment Required.static final intHTTP Status-Code 412: Precondition Failed.static final intHTTP Status-Code 407: Proxy Authentication Required.static final intHTTP Status-Code 414: Request-URI Too Large.static final intHTTP Status-Code 205: Reset Content.static final intHTTP Status-Code 303: See Other.static final intDeprecated.it is misplaced and shouldn't have existed.static final intHTTP Status-Code 401: Unauthorized.static final intHTTP Status-Code 503: Service Unavailable.static final intHTTP Status-Code 415: Unsupported Media Type.static final intHTTP Status-Code 305: Use Proxy.static final intHTTP Status-Code 505: HTTP Version Not Supported.protected booleanIftrue, the protocol will automatically follow redirects.protected StringThe HTTP method (GET,POST,PUT,etc.).protected intAnintrepresenting the three digit HTTP Status-Code.protected StringThe HTTP response message.Fields declared in class URLConnection
allowUserInteraction, connected, doInput, doOutput, ifModifiedSince, url, useCachesModifier and TypeFieldDescriptionprotected booleanIftrue, thisURLis being examined in a context in which it makes sense to allow user interactions such as popping up an authentication dialog.protected booleanIffalse, this connection object has not created a communications link to the specified URL.protected booleanThis variable is set by thesetDoInputmethod.protected booleanThis variable is set by thesetDoOutputmethod.protected longSome protocols support skipping the fetching of the object unless the object has been modified more recently than a certain time.protected URLThe URL represents the remote object on the World Wide Web to which this connection is opened.protected booleanIftrue, the protocol is allowed to use caching whenever it can. -
Constructor Summary
ConstructorsModifierConstructorDescriptionprotectedHttpsURLConnection(URL url) Creates anHttpsURLConnectionusing the URL specified. -
Method Summary
Modifier and TypeMethodDescriptionabstract StringReturns the cipher suite in use on this connection.static HostnameVerifierGets the defaultHostnameVerifierthat is inherited by new instances of this class.static SSLSocketFactoryGets the default staticSSLSocketFactorythat is inherited by new instances of this class.Gets theHostnameVerifierin place on this instance.abstract Certificate[]Returns the certificate(s) that were sent to the server during handshaking.Returns the principal that was sent to the server during handshaking.Returns the server's principal which was established as part of defining the session.abstract Certificate[]Returns the server's certificate chain which was established as part of defining the session.Returns anOptionalcontaining theSSLSessionin use on this connection.Gets the SSL socket factory to be used when creating sockets for secure https URL connections.static voidSets the defaultHostnameVerifierinherited by a new instance of this class.static voidSets the defaultSSLSocketFactoryinherited by new instances of this class.voidSets theHostnameVerifierfor this instance.voidSets theSSLSocketFactoryto be used when this instance creates sockets for secure https URL connections.Methods declared in class HttpURLConnection
disconnect, getErrorStream, getFollowRedirects, getHeaderField, getHeaderFieldKey, getInstanceFollowRedirects, getPermission, getRequestMethod, getResponseCode, getResponseMessage, setAuthenticator, setChunkedStreamingMode, setFixedLengthStreamingMode, setFixedLengthStreamingMode, setFollowRedirects, setInstanceFollowRedirects, setRequestMethod, usingProxyModifier and TypeMethodDescriptionabstract voidIndicates that other requests to the server are unlikely in the near future.Returns the error stream if the connection failed but the server sent useful data nonetheless.static booleanReturns abooleanindicating whether or not HTTP redirects (3xx) should be automatically followed.getHeaderField(int n) Returns the value for thenth header field.getHeaderFieldKey(int n) Returns the key for thenth header field.booleanReturns the value of thisHttpURLConnection'sinstanceFollowRedirectsfield.Deprecated, for removal: This API element is subject to removal in a future version.Permissions can no longer be used for controlling access to resources as the Security Manager is no longer supported.Get the request method.intGets the status code from an HTTP response message.Gets the HTTP response message, if any, returned along with the response code from a server.voidSupplies anAuthenticatorto be used when authentication is requested through the HTTP protocol for thisHttpURLConnection.voidsetChunkedStreamingMode(int chunklen) This method is used to enable streaming of a HTTP request body without internal buffering, when the content length is not known in advance.voidsetFixedLengthStreamingMode(int contentLength) This method is used to enable streaming of a HTTP request body without internal buffering, when the content length is known in advance.voidsetFixedLengthStreamingMode(long contentLength) This method is used to enable streaming of a HTTP request body without internal buffering, when the content length is known in advance.static voidsetFollowRedirects(boolean set) Sets whether HTTP redirects (requests with response code 3xx) should be automatically followed by this class.voidsetInstanceFollowRedirects(boolean followRedirects) Sets whether HTTP redirects (requests with response code 3xx) should be automatically followed by thisHttpURLConnectioninstance.voidsetRequestMethod(String method) Set the method for the URL request, one of: GET POST HEAD OPTIONS PUT DELETE TRACE are legal, subject to protocol restrictions.abstract booleanIndicates if the connection is going through a proxy.Methods declared in class URLConnection
addRequestProperty, connect, getAllowUserInteraction, getConnectTimeout, getContent, getContent, getContentEncoding, getContentLength, getContentLengthLong, getContentType, getDate, getDefaultAllowUserInteraction, getDefaultRequestProperty, getDefaultUseCaches, getDefaultUseCaches, getDoInput, getDoOutput, getExpiration, getFileNameMap, getHeaderField, getHeaderFieldDate, getHeaderFieldInt, getHeaderFieldLong, getHeaderFields, getIfModifiedSince, getInputStream, getLastModified, getOutputStream, getReadTimeout, getRequestProperties, getRequestProperty, getURL, getUseCaches, guessContentTypeFromName, guessContentTypeFromStream, setAllowUserInteraction, setConnectTimeout, setContentHandlerFactory, setDefaultAllowUserInteraction, setDefaultRequestProperty, setDefaultUseCaches, setDefaultUseCaches, setDoInput, setDoOutput, setFileNameMap, setIfModifiedSince, setReadTimeout, setRequestProperty, setUseCaches, toStringModifier and TypeMethodDescriptionvoidaddRequestProperty(String key, String value) Adds a general request property specified by a key-value pair.abstract voidconnect()Opens a communications link to the resource referenced by this URL, if such a connection has not already been established.booleanReturns the value of theallowUserInteractionfield for this object.intReturns setting for connect timeout.Retrieves the contents of this URL connection.getContent(Class<?>[] classes) Retrieves the contents of this URL connection.Returns the value of thecontent-encodingheader field.intReturns the value of thecontent-lengthheader field.longReturns the value of thecontent-lengthheader field as a long.Returns the value of thecontent-typeheader field.longgetDate()Returns the value of thedateheader field.static booleanReturns the default value of theallowUserInteractionfield.static StringDeprecated.The instance specific getRequestProperty method should be used after an appropriate instance of URLConnection is obtained.booleanReturns the default value of aURLConnection'suseCachesflag.static booleangetDefaultUseCaches(String protocol) Returns the default value of theuseCachesflag for the given protocol.booleanReturns the value of thisURLConnection'sdoInputflag.booleanReturns the value of thisURLConnection'sdoOutputflag.longReturns the value of theexpiresheader field.static FileNameMapLoads filename map (a mimetable) from a data file.getHeaderField(String name) Returns the value of the named header field.longgetHeaderFieldDate(String name, long defaultValue) Returns the value of the named field parsed as date.intgetHeaderFieldInt(String name, int defaultValue) Returns the value of the named field parsed as a number.longgetHeaderFieldLong(String name, long defaultValue) Returns the value of the named field parsed as a number.Returns an unmodifiable Map of the header fields.longReturns the value of this object'sifModifiedSincefield.Returns an input stream that reads from this open connection.longReturns the value of thelast-modifiedheader field.Returns an output stream that writes to this connection.intReturns setting for read timeout. 0 return implies that the option is disabled (i.e., timeout of infinity).Returns an unmodifiable Map of general request properties for this connection.getRequestProperty(String key) Returns the value of the named general request property for this connection.getURL()Returns the value of thisURLConnection'sURLfield.booleanReturns the value of thisURLConnection'suseCachesfield.static StringguessContentTypeFromName(String fname) Tries to determine the content type of an object, based on the specified "file" component of a URL.static StringTries to determine the type of an input stream based on the characters at the beginning of the input stream.voidsetAllowUserInteraction(boolean allowuserinteraction) Set the value of theallowUserInteractionfield of thisURLConnection.voidsetConnectTimeout(int timeout) Sets a specified timeout value, in milliseconds, to be used when opening a communications link to the resource referenced by this URLConnection.static voidSets theContentHandlerFactoryof an application.static voidsetDefaultAllowUserInteraction(boolean defaultallowuserinteraction) Sets the default value of theallowUserInteractionfield for all futureURLConnectionobjects to the specified value.static voidsetDefaultRequestProperty(String key, String value) Deprecated.The instance specific setRequestProperty method should be used after an appropriate instance of URLConnection is obtained.voidsetDefaultUseCaches(boolean defaultusecaches) Sets the default value of theuseCachesfield to the specified value.static voidsetDefaultUseCaches(String protocol, boolean defaultVal) Sets the default value of theuseCachesfield for the named protocol to the given value.voidsetDoInput(boolean doinput) Sets the value of thedoInputfield for thisURLConnectionto the specified value.voidsetDoOutput(boolean dooutput) Sets the value of thedoOutputfield for thisURLConnectionto the specified value.static voidSets the FileNameMap.voidsetIfModifiedSince(long ifmodifiedsince) Sets the value of theifModifiedSincefield of thisURLConnectionto the specified value.voidsetReadTimeout(int timeout) Sets the read timeout to a specified timeout, in milliseconds.voidsetRequestProperty(String key, String value) Sets the general request property.voidsetUseCaches(boolean usecaches) Sets the value of theuseCachesfield of thisURLConnectionto the specified value.toString()Returns aStringrepresentation of this URL connection.Methods declared in class Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, wait, wait, waitModifier and TypeMethodDescriptionprotected Objectclone()Creates and returns a copy of this object.booleanIndicates whether some other object is "equal to" this one.protected voidfinalize()Deprecated, for removal: This API element is subject to removal in a future version.Finalization is deprecated and subject to removal in a future release.final Class<?> getClass()Returns the runtime class of thisObject.inthashCode()Returns a hash code value for this object.final voidnotify()Wakes up a single thread that is waiting on this object's monitor.final voidWakes up all threads that are waiting on this object's monitor.final voidwait()Causes the current thread to wait until it is awakened, typically by being notified or interrupted.final voidwait(long timeoutMillis) Causes the current thread to wait until it is awakened, typically by being notified or interrupted, or until a certain amount of real time has elapsed.final voidwait(long timeoutMillis, int nanos) Causes the current thread to wait until it is awakened, typically by being notified or interrupted, or until a certain amount of real time has elapsed.
-
Field Details
-
hostnameVerifier
ThehostnameVerifierfor this object.
-
-
Constructor Details
-
HttpsURLConnection
Creates anHttpsURLConnectionusing the URL specified.- Parameters:
url- the URL
-
-
Method Details
-
getCipherSuite
Returns the cipher suite in use on this connection.- Returns:
- the cipher suite
- Throws:
IllegalStateException- if this method is called before the connection has been established.
-
getLocalCertificates
Returns the certificate(s) that were sent to the server during handshaking.Note: This method is useful only when using certificate-based cipher suites.
When multiple certificates are available for use in a handshake, the implementation chooses what it considers the "best" certificate chain available, and transmits that to the other side. This method allows the caller to know which certificate chain was actually sent.
- Returns:
- an ordered array of certificates, with the client's own certificate first followed by any certificate authorities. If no certificates were sent, then null is returned.
- Throws:
IllegalStateException- if this method is called before the connection has been established.- See Also:
-
getServerCertificates
Returns the server's certificate chain which was established as part of defining the session.Note: This method can be used only when using certificate-based cipher suites; using it with non-certificate-based cipher suites, such as Kerberos, will throw an SSLPeerUnverifiedException.
Note: The returned value may not be a valid certificate chain and should not be relied on for trust decisions.
- Returns:
- an ordered array of server certificates, with the peer's own certificate first followed by any certificate authorities.
- Throws:
SSLPeerUnverifiedException- if the peer is not verified.IllegalStateException- if this method is called before the connection has been established.- See Also:
-
getPeerPrincipal
Returns the server's principal which was established as part of defining the session.Note: Subclasses should override this method. If not overridden, it will default to returning the X500Principal of the server's end-entity certificate for certificate-based ciphersuites, or throw an SSLPeerUnverifiedException for non-certificate based ciphersuites, such as Kerberos.
- Returns:
- the server's principal. Returns an X500Principal of the end-entity certificate for X509-based cipher suites, and KerberosPrincipal for Kerberos cipher suites.
- Throws:
SSLPeerUnverifiedException- if the peer was not verifiedIllegalStateException- if this method is called before the connection has been established.- Since:
- 1.5
- See Also:
-
getLocalPrincipal
Returns the principal that was sent to the server during handshaking.Note: Subclasses should override this method. If not overridden, it will default to returning the X500Principal of the end-entity certificate that was sent to the server for certificate-based ciphersuites or, return null for non-certificate based ciphersuites, such as Kerberos.
- Returns:
- the principal sent to the server. Returns an X500Principal of the end-entity certificate for X509-based cipher suites, and KerberosPrincipal for Kerberos cipher suites. If no principal was sent, then null is returned.
- Throws:
IllegalStateException- if this method is called before the connection has been established.- Since:
- 1.5
- See Also:
-
setDefaultHostnameVerifier
Sets the defaultHostnameVerifierinherited by a new instance of this class.If this method is not called, the default
HostnameVerifierassumes the connection should not be permitted.- Parameters:
v- the default host name verifier- Throws:
IllegalArgumentException- if theHostnameVerifierparameter is null.- See Also:
-
getDefaultHostnameVerifier
Gets the defaultHostnameVerifierthat is inherited by new instances of this class.- Returns:
- the default host name verifier
- See Also:
-
setHostnameVerifier
Sets theHostnameVerifierfor this instance.New instances of this class inherit the default static hostname verifier set by
setDefaultHostnameVerifier. Calls to this method replace this object'sHostnameVerifier.- Parameters:
v- the host name verifier- Throws:
IllegalArgumentException- if theHostnameVerifierparameter is null.- See Also:
-
getHostnameVerifier
Gets theHostnameVerifierin place on this instance.- Returns:
- the host name verifier
- See Also:
-
setDefaultSSLSocketFactory
Sets the defaultSSLSocketFactoryinherited by new instances of this class.The socket factories are used when creating sockets for secure https URL connections.
- Parameters:
sf- the default SSL socket factory- Throws:
IllegalArgumentException- if the SSLSocketFactory parameter is null.- See Also:
-
getDefaultSSLSocketFactory
Gets the default staticSSLSocketFactorythat is inherited by new instances of this class.The socket factories are used when creating sockets for secure https URL connections.
- Returns:
- the default
SSLSocketFactory - See Also:
-
setSSLSocketFactory
Sets theSSLSocketFactoryto be used when this instance creates sockets for secure https URL connections.New instances of this class inherit the default static
SSLSocketFactoryset bysetDefaultSSLSocketFactory. Calls to this method replace this object'sSSLSocketFactory.- Parameters:
sf- the SSL socket factory- Throws:
IllegalArgumentException- if theSSLSocketFactoryparameter is null.- See Also:
-
getSSLSocketFactory
Gets the SSL socket factory to be used when creating sockets for secure https URL connections.- Returns:
- the
SSLSocketFactory - See Also:
-
getSSLSession
Returns anOptionalcontaining theSSLSessionin use on this connection. Returns an emptyOptionalif the underlying implementation does not support this method.- Implementation Requirements:
- For compatibility, the default implementation of this
method returns an empty
Optional. Subclasses should override this method with an appropriate implementation since an application may need to access additional parameters associated with the SSL session. - Returns:
- an
Optionalcontaining theSSLSessionin use on this connection. - Throws:
IllegalStateException- if this method is called before the connection has been established- Since:
- 12
- See Also:
-