Class HttpURLConnection
This class can be used to replace the HttpClient in the JDK with this
HTTPClient by defining the property
java.protocol.handler.pkgs=HTTPClient.
One difference between Sun's HttpClient and this one is that this one will provide you with a real output stream if possible. This leads to two changes: you should set the request property "Content-Length", if possible, before invoking getOutputStream(); and in many cases getOutputStream() implies connect(). This should be transparent, though, apart from the fact that you can't change any headers or other settings anymore once you've gotten the output stream. So, for large data do:
HttpURLConnection con = (HttpURLConnection) url.openConnection();
con.setDoOutput(true);
con.setRequestProperty("Content-Length", ...);
OutputStream out = con.getOutputStream();
out.write(...);
out.close();
if (con.getResponseCode() != 200)
...
The HTTPClient will send the request data using the chunked transfer encoding when no Content-Length is specified and the server is HTTP/1.1 compatible. Because cgi-scripts can't usually handle this, you may experience problems trying to POST data. For this reason, whenever the Content-Type is application/x-www-form-urlencoded getOutputStream() will buffer the data before sending it so as prevent chunking. If you are sending requests with a different Content-Type and are experiencing problems then you may want to try setting the system property HTTPClient.dontChunkRequests to true (this needs to be done either on the command line or somewhere in the code before the first URLConnection.openConnection() is invoked).
A second potential incompatibility is that the HTTPClient aggresively resuses connections, and can do so more often that Sun's client. This can cause problems if you send multiple requests, and the first one has a long response. In this case (assuming the server allows the connection to be used for multiple requests) the responses to second, third, etc request won't be received until the first response has been completely read. With Sun's client on the other hand you may not experience this, as it may not be able to keep the connection open and there may create multiple connections for the requests. This allows the responses to the second, third, etc requests to be read before the first response has completed. Note: whether this will happen depends on details of the resource being requested and the server. In many cases the HTTPClient and Sun's client will exhibit the same behaviour. Also, applications which depend on being able to read the second response before the first one has completed must be considered broken, because A) this behaviour cannot be relied upon even in Sun's current client, and B) Sun's implementation will exhibit the same problem if they ever switch to HTTP/1.1.
- Since:
- V0.3
- Version:
- 0.3-3 06/05/2001
- Author:
- Ronald Tschal�r
-
Field Summary
FieldsModifier and TypeFieldDescriptionprotected HTTPConnectionthe current connectionprotected static Hashtablethe cache of HTTPConnectionsprotected HTTPResponsethe responseFields inherited from class java.net.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, responseCode, responseMessageFields inherited from class java.net.URLConnection
allowUserInteraction, connected, doInput, doOutput, ifModifiedSince, url, useCaches -
Constructor Summary
Constructors -
Method Summary
Modifier and TypeMethodDescriptionvoidconnect()Connects to the server (if connection not still kept alive) and issues the request.voidCloses all the connections to this server.protected HTTPConnectiongetConnection(URL url) Returns an HTTPConnection.static StringGets the value for a given default request header.Returns the error stream if the connection failed but the server sent useful data nonetheless.getHeaderField(int n) Gets header value of the n-th header.getHeaderField(String name) Get the value part of a header.longgetHeaderFieldDate(String name, long def) Get the value part of a header, interprets it as a date and converts it to a long representing the number of milliseconds since 1970.intgetHeaderFieldInt(String name, int def) Get the value part of a header and converts it to an int.getHeaderFieldKey(int n) Gets header name of the n-th header.Gets an input stream from which the data in the response may be read.booleanGets an output stream which can be used send an entity with the request.Return the request method used.getRequestProperty(String name) Gets the value of a given request header.intGet the response code.Get the response message describing the response code.getURL()Gets the url for this connection.static voidsetDefaultRequestProperty(String name, String value) Sets an arbitrary default request header.voidsetIfModifiedSince(long time) Sets the If-Modified-Since header.voidsetInstanceFollowRedirects(boolean set) Enables or disables the automatic handling of redirection responses for this instance only.voidsetRequestMethod(String method) Sets the request method (e.g.voidsetRequestProperty(String name, String value) Sets an arbitrary request header.toString()produces a string.booleanShows if request are being made through an http proxy or directly.Methods inherited from class java.net.HttpURLConnection
getFollowRedirects, getPermission, setAuthenticator, setChunkedStreamingMode, setFixedLengthStreamingMode, setFixedLengthStreamingMode, setFollowRedirectsMethods inherited from class java.net.URLConnection
addRequestProperty, getAllowUserInteraction, getConnectTimeout, getContent, getContent, getContentEncoding, getContentLength, getContentLengthLong, getContentType, getDate, getDefaultAllowUserInteraction, getDefaultUseCaches, getDefaultUseCaches, getDoInput, getDoOutput, getExpiration, getFileNameMap, getHeaderFieldLong, getHeaderFields, getIfModifiedSince, getLastModified, getReadTimeout, getRequestProperties, getUseCaches, guessContentTypeFromName, guessContentTypeFromStream, setAllowUserInteraction, setConnectTimeout, setContentHandlerFactory, setDefaultAllowUserInteraction, setDefaultUseCaches, setDefaultUseCaches, setDoInput, setDoOutput, setFileNameMap, setReadTimeout, setUseCaches
-
Field Details
-
connections
the cache of HTTPConnections -
con
the current connection -
resp
the response
-
-
Constructor Details
-
HttpURLConnection
Construct a connection to the specified url. A cache of HTTPConnections is used to maximize the reuse of these across multiple HttpURLConnections.
The default method is "GET".- Parameters:
url- the url of the request- Throws:
ProtocolNotSuppException- if the protocol is not supportedIOException
-
-
Method Details
-
getConnection
Returns an HTTPConnection. A cache of connections is kept and first consulted; only when the cache lookup fails is a new one created and added to the cache.- Parameters:
url- the url- Returns:
- an HTTPConnection
- Throws:
ProtocolNotSuppException- if the protocol is not supported
-
setRequestMethod
Sets the request method (e.g. "PUT" or "HEAD"). Can only be set before connect() is called.- Overrides:
setRequestMethodin classHttpURLConnection- Parameters:
method- the http method.- Throws:
ProtocolException- if already connected.
-
getRequestMethod
Return the request method used.- Overrides:
getRequestMethodin classHttpURLConnection- Returns:
- the http method.
-
getResponseCode
Get the response code. Calls connect() if not connected.- Overrides:
getResponseCodein classHttpURLConnection- Returns:
- the http response code returned.
- Throws:
IOException
-
getResponseMessage
Get the response message describing the response code. Calls connect() if not connected.- Overrides:
getResponseMessagein classHttpURLConnection- Returns:
- the http response message returned with the response code.
- Throws:
IOException
-
getHeaderField
Get the value part of a header. Calls connect() if not connected.- Overrides:
getHeaderFieldin classURLConnection- Parameters:
name- the of the header.- Returns:
- the value of the header, or null if no such header was returned.
-
getHeaderFieldInt
Get the value part of a header and converts it to an int. If the header does not exist or if its value could not be converted to an int then the default is returned. Calls connect() if not connected.- Overrides:
getHeaderFieldIntin classURLConnection- Parameters:
name- the of the header.def- the default value to return in case of an error.- Returns:
- the value of the header, or null if no such header was returned.
-
getHeaderFieldDate
Get the value part of a header, interprets it as a date and converts it to a long representing the number of milliseconds since 1970. If the header does not exist or if its value could not be converted to a date then the default is returned. Calls connect() if not connected.- Overrides:
getHeaderFieldDatein classHttpURLConnection- Parameters:
name- the of the header.def- the default value to return in case of an error.- Returns:
- the value of the header, or def in case of an error.
-
getHeaderFieldKey
Gets header name of the n-th header. Calls connect() if not connected. The name of the 0-th header is null, even though it the 0-th header has a value.- Overrides:
getHeaderFieldKeyin classHttpURLConnection- Parameters:
n- which header to return.- Returns:
- the header name, or null if not that many headers.
-
getHeaderField
Gets header value of the n-th header. Calls connect() if not connected. The value of 0-th header is the Status-Line (e.g. "HTTP/1.1 200 Ok").- Overrides:
getHeaderFieldin classHttpURLConnection- Parameters:
n- which header to return.- Returns:
- the header value, or null if not that many headers.
-
getInputStream
Gets an input stream from which the data in the response may be read. Calls connect() if not connected.- Overrides:
getInputStreamin classURLConnection- Returns:
- an InputStream
- Throws:
ProtocolException- if input not enabled.IOException- See Also:
-
getErrorStream
Returns the error stream if the connection failed but the server sent useful data nonetheless.This method will not cause a connection to be initiated.
- Overrides:
getErrorStreamin classHttpURLConnection- Returns:
- an InputStream, or null if either the connection hasn't been established yet or no error occured
- Since:
- V0.3-1
- See Also:
-
getOutputStream
Gets an output stream which can be used send an entity with the request. Can be called multiple times, in which case always the same stream is returned.The default request method changes to "POST" when this method is called. Cannot be called after connect().
If no Content-type has been set it defaults to application/x-www-form-urlencoded. Furthermore, if the Content-type is application/x-www-form-urlencoded then all output will be collected in a buffer before sending it to the server; otherwise an HttpOutputStream is used.
- Overrides:
getOutputStreamin classURLConnection- Returns:
- an OutputStream
- Throws:
ProtocolException- if already connect()'ed, if output is not enabled or if the request method does not support output.IOException- See Also:
-
getURL
Gets the url for this connection. If we're connect()'d and the request was redirected then the url returned is that of the final request.- Overrides:
getURLin classURLConnection- Returns:
- the final url, or null if any exception occured.
-
setIfModifiedSince
public void setIfModifiedSince(long time) Sets the If-Modified-Since header.- Overrides:
setIfModifiedSincein classURLConnection- Parameters:
time- the number of milliseconds since 1970.
-
setRequestProperty
Sets an arbitrary request header.- Overrides:
setRequestPropertyin classURLConnection- Parameters:
name- the name of the header.value- the value for the header.
-
getRequestProperty
Gets the value of a given request header.- Overrides:
getRequestPropertyin classURLConnection- Parameters:
name- the name of the header.- Returns:
- the value part of the header, or null if no such header.
-
setDefaultRequestProperty
Sets an arbitrary default request header. All headers set here are automatically sent with each request.- Parameters:
name- the name of the header.value- the value for the header.
-
getDefaultRequestProperty
Gets the value for a given default request header.- Parameters:
name- the name of the header.- Returns:
- the value part of the header, or null if no such header.
-
setInstanceFollowRedirects
public void setInstanceFollowRedirects(boolean set) Enables or disables the automatic handling of redirection responses for this instance only. Cannot be called afterconnect().- Overrides:
setInstanceFollowRedirectsin classHttpURLConnection- Parameters:
set- enables automatic redirection handling if true.
-
getInstanceFollowRedirects
public boolean getInstanceFollowRedirects()- Overrides:
getInstanceFollowRedirectsin classHttpURLConnection- Returns:
- true if automatic redirection handling for this instance is enabled.
-
connect
Connects to the server (if connection not still kept alive) and issues the request.- Specified by:
connectin classURLConnection- Throws:
IOException
-
disconnect
public void disconnect()Closes all the connections to this server.- Specified by:
disconnectin classHttpURLConnection
-
usingProxy
public boolean usingProxy()Shows if request are being made through an http proxy or directly.- Specified by:
usingProxyin classHttpURLConnection- Returns:
- true if an http proxy is being used.
-
toString
produces a string.- Overrides:
toStringin classURLConnection- Returns:
- a string containing the HttpURLConnection
-