public class HttpURLConnection extends 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.
| Modifier and Type | Field and Description |
|---|---|
protected HTTPConnection |
con
the current connection
|
protected static Hashtable |
connections
the cache of HTTPConnections
|
protected HTTPResponse |
resp
the response
|
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, responseMessageallowUserInteraction, connected, doInput, doOutput, ifModifiedSince, url, useCaches| Constructor and Description |
|---|
HttpURLConnection(URL url)
Construct a connection to the specified url.
|
| Modifier and Type | Method and Description |
|---|---|
void |
connect()
Connects to the server (if connection not still kept alive) and
issues the request.
|
void |
disconnect()
Closes all the connections to this server.
|
protected HTTPConnection |
getConnection(URL url)
Returns an HTTPConnection.
|
static String |
getDefaultRequestProperty(String name)
Gets the value for a given default request header.
|
InputStream |
getErrorStream()
Returns the error stream if the connection failed
but the server sent useful data nonetheless.
|
String |
getHeaderField(int n)
Gets header value of the n-th header.
|
String |
getHeaderField(String name)
Get the value part of a header.
|
long |
getHeaderFieldDate(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.
|
int |
getHeaderFieldInt(String name,
int def)
Get the value part of a header and converts it to an int.
|
String |
getHeaderFieldKey(int n)
Gets header name of the n-th header.
|
InputStream |
getInputStream()
Gets an input stream from which the data in the response may be read.
|
boolean |
getInstanceFollowRedirects() |
OutputStream |
getOutputStream()
Gets an output stream which can be used send an entity with the
request.
|
String |
getRequestMethod()
Return the request method used.
|
String |
getRequestProperty(String name)
Gets the value of a given request header.
|
int |
getResponseCode()
Get the response code.
|
String |
getResponseMessage()
Get the response message describing the response code.
|
URL |
getURL()
Gets the url for this connection.
|
static void |
setDefaultRequestProperty(String name,
String value)
Sets an arbitrary default request header.
|
void |
setIfModifiedSince(long time)
Sets the If-Modified-Since header.
|
void |
setInstanceFollowRedirects(boolean set)
Enables or disables the automatic handling of redirection responses
for this instance only.
|
void |
setRequestMethod(String method)
Sets the request method (e.g.
|
void |
setRequestProperty(String name,
String value)
Sets an arbitrary request header.
|
String |
toString()
produces a string.
|
boolean |
usingProxy()
Shows if request are being made through an http proxy or directly.
|
getFollowRedirects, getPermission, setChunkedStreamingMode, setFixedLengthStreamingMode, setFixedLengthStreamingMode, setFollowRedirectsaddRequestProperty, getAllowUserInteraction, getConnectTimeout, getContent, getContent, getContentEncoding, getContentLength, getContentLengthLong, getContentType, getDate, getDefaultAllowUserInteraction, getDefaultUseCaches, getDoInput, getDoOutput, getExpiration, getFileNameMap, getHeaderFieldLong, getHeaderFields, getIfModifiedSince, getLastModified, getReadTimeout, getRequestProperties, getUseCaches, guessContentTypeFromName, guessContentTypeFromStream, setAllowUserInteraction, setConnectTimeout, setContentHandlerFactory, setDefaultAllowUserInteraction, setDefaultUseCaches, setDoInput, setDoOutput, setFileNameMap, setReadTimeout, setUseCachesprotected static Hashtable connections
protected HTTPConnection con
protected HTTPResponse resp
public HttpURLConnection(URL url) throws ProtocolNotSuppException, IOException
url - the url of the requestProtocolNotSuppException - if the protocol is not supportedIOExceptionprotected HTTPConnection getConnection(URL url) throws ProtocolNotSuppException
url - the urlProtocolNotSuppException - if the protocol is not supportedpublic void setRequestMethod(String method) throws ProtocolException
setRequestMethod in class HttpURLConnectionmethod - the http method.ProtocolException - if already connected.public String getRequestMethod()
getRequestMethod in class HttpURLConnectionpublic int getResponseCode()
throws IOException
getResponseCode in class HttpURLConnectionIOExceptionpublic String getResponseMessage() throws IOException
getResponseMessage in class HttpURLConnectionIOExceptionpublic String getHeaderField(String name)
getHeaderField in class URLConnectionname - the of the header.public int getHeaderFieldInt(String name, int def)
getHeaderFieldInt in class URLConnectionname - the of the header.def - the default value to return in case of an error.public long getHeaderFieldDate(String name, long def)
getHeaderFieldDate in class HttpURLConnectionname - the of the header.def - the default value to return in case of an error.public String getHeaderFieldKey(int n)
getHeaderFieldKey in class HttpURLConnectionn - which header to return.public String getHeaderField(int n)
getHeaderField in class HttpURLConnectionn - which header to return.public InputStream getInputStream() throws IOException
getInputStream in class URLConnectionProtocolException - if input not enabled.IOExceptionURLConnection.setDoInput(boolean)public InputStream getErrorStream()
This method will not cause a connection to be initiated.
getErrorStream in class HttpURLConnectionHttpURLConnection.getErrorStream()public OutputStream getOutputStream() throws IOException
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.
getOutputStream in class URLConnectionProtocolException - if already connect()'ed, if output is not
enabled or if the request method does not
support output.IOExceptionURLConnection.setDoOutput(boolean),
HttpOutputStreampublic URL getURL()
getURL in class URLConnectionpublic void setIfModifiedSince(long time)
setIfModifiedSince in class URLConnectiontime - the number of milliseconds since 1970.public void setRequestProperty(String name, String value)
setRequestProperty in class URLConnectionname - the name of the header.value - the value for the header.public String getRequestProperty(String name)
getRequestProperty in class URLConnectionname - the name of the header.public static void setDefaultRequestProperty(String name, String value)
name - the name of the header.value - the value for the header.public static String getDefaultRequestProperty(String name)
name - the name of the header.public void setInstanceFollowRedirects(boolean set)
connect().setInstanceFollowRedirects in class HttpURLConnectionset - enables automatic redirection handling if true.public boolean getInstanceFollowRedirects()
getInstanceFollowRedirects in class HttpURLConnectionpublic void connect()
throws IOException
connect in class URLConnectionIOExceptionpublic void disconnect()
disconnect in class HttpURLConnectionpublic boolean usingProxy()
usingProxy in class HttpURLConnectionpublic String toString()
toString in class URLConnectionCopyright © 2000-2014. All Rights Reserved.