|
![]() |
||||||||
PREV CLASS NEXT CLASS | FRAMES NO FRAMES | ||||||||
SUMMARY: NESTED | FIELD | CONSTR | METHOD | DETAIL: FIELD | CONSTR | METHOD |
java.lang.Object | +--sunlabs.brazil.util.http.HttpRequest
Sends an HTTP request to some target host and gets the answer back.
Similar to the URLConnection
class.
Caches connections to hosts, and reuses them if possible. Talks HTTP/1.1 to the hosts, in order to keep alive connections as much as possible.
The sequence of events for using an HttpRequest
is similar
to how URLConnection
is used:
HttpRequest
object is constructed.
In the common case, all the setup parameters are initialized to sensible
values and won't need to be modified. Most users will only need to
construct a new HttpRequest
object and then call
getInputStream
to read the contents. The rest of the
member variables and methods are only needed for advanced behavior.
The HttpRequest
class is intended to be a replacement for the
URLConnection
class. It operates at a lower level and makes
fewer decisions on behavior. Some differences between the
HttpRequest
class and the URLConnection
class
follow:
System.getProperties
) that modify the behavior of
HttpRequest
.
HttpRequest
does not automatically follow redirects.
HttpRequest
does not turn HTTP responses with a status
code other than "200 OK" into IOExceptions
. Sometimes
it may be necessary and even quite useful to examine the results of
an "unsuccessful" HTTP request.
HttpRequest
issues HTTP/1.1 requests and handles
HTTP/0.9, HTTP/1.0, and HTTP/1.1 responses.
URLConnection
class leaks open sockets if there is
an error reading the response or if the target does not use
Keep-Alive, and depends upon the garabge collector to close and
release the open socket in these cases, which is unreliable because
it may lead to intermittently running out of sockets if the garbage
collector doesn't run often enough.
URLConnection
, there are bugs in its implementation
(as of JDK1.2) that may cause the program to block forever and/or
read an insufficient amount of data before trying to reuse the
underlying socket.
A number of the fields in the HttpRequest
object are public,
by design. Most of the methods mentioned above are convenience methods;
the underlying data fields are meant to be accessed for more complicated
operations, such as changing the socket factory or accessing the raw HTTP
response line. Note however, that the order of the methods described
above is important. For instance, the user cannot examine the response
headers (by calling getResponseHeader
or by examining the
variable responseHeaders
) without first having connected to
the host.
However, if the user wants to modify the default behavior, the
HttpRequest
uses the value of a number of variables and
automatically sets some HTTP headers when sending the request. The user
can change these settings up until the time connect
is
called, as follows:
version
HttpRequest
issues HTTP/1.1
requests. The user can set version
to change this to
HTTP/1.0.
method
method
is null
(the default),
the HttpRequest
decides what the HTTP request method
should be as follows: If the user has called
getOutputStream
, then the method will be "POST",
otherwise the method will be "GET".
proxyHost
connect
opens a connection to the proxy.
connect
opens a connection to the remote host.
HttpRequest
.
HttpRequest
sets the appropriate connection
header to "Keep-Alive" to keep alive the connection to the host or
proxy (respectively). By setting the appropriate connection header,
the user can control whether the HttpRequest
tries to
use Keep-Alives.
HttpRequest
,
and is set automatically if the user does not set it.
getOutputStream
and writes some
data to it, the "Content-Length" header will be set to the amount of
data that has been written at the time that connect
is called.
close
to release
the socket. Although it happens under the covers, the user should be
aware that if an IOException occurs or once data has been read normally
from the remote host, close
is called automatically. This
is to ensure that the minimal number of sockets are left open at any time.
The input stream that getInputStream
provides automatically
hides whether the remote host is providing HTTP/1.1 "chunked" encoding or
regular streaming data. The user can simply read until reaching the
end of the input stream, which signifies that all the available data from
this request has been read. If reading from a "chunked" source, the
data is automatically de-chunked as it is presented to the user. Currently,
no access is provided to the underlying raw input stream.
Field Summary | |
static String |
defaultHTTPVersion
The default HTTP version string to send to the remote host when issuing requests. |
static String |
defaultProxyHost
The default proxy host for HTTP requests. |
static int |
defaultProxyPort
The default proxy port for HTTP requests. |
static boolean |
displayAllHeaders
setting this to "true" causing all http headers to be printed on the standard error stream; useful for debugging client/server interactions. |
static int |
DRAIN_TIMEOUT
Timeout (in msec) to drain an input stream that has been closed before the entire HTTP response has been read. |
String |
host
The host extracted from the URL used to construct this HttpRequest . |
static int |
LINE_LIMIT
Maximum length of a line in the HTTP response headers (sanity check). |
String |
method
The HTTP method, such as "GET", "POST", or "HEAD". |
static HttpSocketPool |
pool
The cache of idle sockets. |
int |
port
The port extracted from the URL used to construct this HttpRequest . |
String |
proxyHost
If non- null , sends this HTTP request via the specified
proxy host and port. |
int |
proxyPort
The proxy port. |
MimeHeaders |
requestHeaders
The headers for the HTTP request. |
MimeHeaders |
responseHeaders
The headers that were present in the HTTP response. |
MimeHeaders |
responseTrailers
An artifact of HTTP/1.1 chunked encoding. |
static SocketFactory |
socketFactory
The factory for constructing new Sockets objects used to connect to remote hosts when issuing HTTP requests. |
String |
status
The status line from the HTTP response. |
URL |
url
The URL used to construct this HttpRequest . |
String |
version
The HTTP version string. |
Constructor Summary | |
HttpRequest(String url)
Creates a new HttpRequest object that will send an
HTTP request to fetch the resource represented by the URL. |
|
HttpRequest(URL url)
Creates a new HttpRequest object that will send an
HTTP request to fetch the resource represented by the URL. |
Method Summary | |
int |
addHeaders(String tokens,
Properties props)
Convenience method for adding request headers by looking them up in a properties object. |
void |
close()
Gracefully closes this HTTP request when user is done with it. |
void |
connect()
Connect to the target host (or proxy), send the request, and read the response headers. |
void |
disconnect()
Interrupts this HTTP request. |
String |
getContent()
Return the content as a string. |
String |
getContent(String encoding)
Get the content as a string. |
int |
getContentLength()
Convenience method to get the "Content-Length" header from the HTTP response. |
String |
getEncoding()
|
HttpInputStream |
getInputStream()
Gets an input stream that can be used to read the body of the HTTP response. |
OutputStream |
getOutputStream()
Gets an output stream that can be used for uploading data to the host. |
int |
getResponseCode()
Gets the HTTP response status code. |
String |
getResponseHeader(String key)
Gets the value associated with the given case-insensitive header name from the HTTP response. |
static void |
removePointToPointHeaders(MimeHeaders headers,
boolean response)
Removes all the point-to-point (hop-by-hop) headers from the given mime headers. |
void |
setMethod(String method)
Sets the HTTP method to the specified value. |
void |
setProxy(String proxyHost,
int proxyPort)
Sets the proxy for this request. |
void |
setRequestHeader(String key,
String value)
Sets a request header in the HTTP request that will be issued. |
Methods inherited from class java.lang.Object |
equals, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait |
Field Detail |
public static int DRAIN_TIMEOUT
If the user closes the HttpRequest
before reading all of
the data, but the remote host has agreed to keep this socket alive, we
need to read and discard the rest of the response before issuing a new
request. If it takes longer than DRAIN_TIMEOUT
to read
and discard the data, we will just forcefully close the connection to
the remote host rather than waiting to read any more.
Default value is 10000.
public static int LINE_LIMIT
If an HTTP response line is longer than this, the response is considered to be malformed.
Default value is 1000.
public static String defaultHTTPVersion
The default value can be overridden on a per-request basis by
setting the version
instance variable.
Default value is "HTTP/1.1".
version
public static String defaultProxyHost
null
,
then all new HTTP requests will be sent via this proxy. If
null
, then all new HTTP requests are sent directly to
the host specified when the HttpRequest
object was
constructed.
The default value can be overridden on a per-request basis by
calling the setProxy
method or setting the
proxyHost
instance variables.
Default value is null
.
defaultProxyPort
,
proxyHost
,
setProxy(java.lang.String, int)
public static int defaultProxyPort
Default value is 80
.
defaultProxyHost
,
proxyPort
public static SocketFactory socketFactory
Default value is null
, which signifies plain sockets.
public static HttpSocketPool pool
public URL url
HttpRequest
.
public String host
HttpRequest
.
url
public int port
HttpRequest
.
url
public String proxyHost
null
, sends this HTTP request via the specified
proxy host and port.
Initialized from defaultProxyHost
, but may be changed
by the user at any time up until the HTTP request is actually sent.
defaultProxyHost
,
proxyPort
,
setProxy(java.lang.String, int)
,
connect()
public int proxyPort
proxyHost
public String method
May be set by the user at any time up until the HTTP request is actually sent.
public String version
Initialized from defaultHTTPVersion
, but may be changed
by the user at any time up until the HTTP request is actually sent.
public MimeHeaders requestHeaders
public static boolean displayAllHeaders
public String status
connect
has been called and the HTTP response has
been read.
public MimeHeaders responseHeaders
connect
has been called and the
HTTP response has been read.
public MimeHeaders responseTrailers
getInputStream
has been read. At that point,
this field will automatically be initialized to the set of any headers
that were found. If not reading from an HTTP/1.1 chunked source, then
this field is irrelevant and will remain null
.
Constructor Detail |
public HttpRequest(URL url)
HttpRequest
object that will send an
HTTP request to fetch the resource represented by the URL.
The host specified by the URL is not contacted at this time.
url
- A fully qualified "http:" URL.
IllegalArgumentException
- if url
is not an "http:" URL.public HttpRequest(String url)
HttpRequest
object that will send an
HTTP request to fetch the resource represented by the URL.
The host specified by the URL is not contacted at this time.
url
- A string representing a fully qualified "http:" URL.
IllegalArgumentException
- if url
is not a well-formed "http:" URL.Method Detail |
public void setMethod(String method)
If this method is called, it must be called before connect
is called. Otherwise it will have no effect.
method
- The string for the HTTP method, or null
to
allow this HttpRequest
to pick the method for
itself.public void setProxy(String proxyHost, int proxyPort)
If this method is called, it must be called before connect
is called. Otherwise it will have no effect.
proxyHost
- The proxy that will handle the request, or null
to not use a proxy.proxyPort
- The port on the proxy, for the proxy request. Ignored if
proxyHost
is null
.public void setRequestHeader(String key, String value)
requestHeaders
variable.
If this method is called, it must be called before connect
is called. Otherwise it will have no effect.
key
- The header name.value
- The value for the request header.requestHeaders
public OutputStream getOutputStream() throws IOException
If this method is called, it must be called before connect
is called. Otherwise it will have no effect.
Currently the implementation is not as good as it could be. The user should avoid uploading huge amounts of data, for some definition of huge.
IOException
public void connect() throws UnknownHostException, IOException
UnknownHostException
- if the target host (or proxy) could not be contacted.
IOException
- if there is a problem writing the HTTP request or reading
the HTTP response headers.public HttpInputStream getInputStream() throws IOException
The input stream that getInputStream
provides
automatically hides the differences between "Content-Length", no
"Content-Length", and "chunked" for HTTP/1.0 and HTTP/1.1 responses.
In all cases, the user can simply read until reaching the end of the
input stream, which signifies that all the available data from this
request has been read. (If reading from a "chunked" source, the data
is automatically de-chunked as it is presented to the user. There is
no way to access the raw underlying stream that contains the HTTP/1.1
chunking packets.)
IOException
- if there is problem connecting to the target.connect()
public void close()
The user can either call this method or close
on the
input stream obtained from the getInputStream
method -- the results are the same.
When all the response data is read from the input stream, the
input stream is automatically closed (recycled). If the user is
not going to read all the response data from input stream, the user
must call close
to
release the resources associated with the open request. Otherwise
the program may consume all available sockets, waiting forever for
the user to finish reading.
Note that the input stream is automatically closed if the input stream throws an exception while reading.
In order to interrupt a pending I/O operation in another thread
(for example, to stop a request that is taking too long), the user
should call disconnect
or interrupt the blocked thread.
The user should not call close
in this case because
close
will not interrupt the pending I/O operation.
Closing the request multiple times is allowed.
In order to make sure that open sockets are not left lying around the user should use code similar to the following:
OutputStream out = ... HttpRequest http = new HttpRequest("http://bob.com/index.html"); try { HttpInputStream in = http.getInputStream(); in.copyTo(out); } finally { // Copying to "out" could have failed. Close "http" in case // not all the data has been read from it yet. http.close(); }
public void disconnect()
InterruptedIOException
during the connect
or while reading from the input stream, depending upon what state
this HTTP request is in when it is disconnected.
close()
public int getResponseCode()
HTTP/1.0 200 OK HTTP/1.0 401 Unauthorizedthis method extracts the integers
200
and 401
respectively. Returns -1
if the response status code
was malformed.
If this method is called, it must be called after connect
has been called. Otherwise the information is not yet available and
this method will return -1
.
For advanced features, the user can directly access the
status
variable.
connect()
,
status
public String getResponseHeader(String key)
If this method is called, it must be called after connect
has been called. Otherwise the information is not available and
this method will return null
.
For advanced features, such as enumerating over all response headers,
the user should directly access the responseHeaders
variable.
key
- The case-insensitive name of the response header.
null
if there is no such header in the response.connect()
,
responseHeaders
public int getContentLength()
If this method is called, it must be called after connect
has been called. Otherwise the information is not available and
this method will return -1
.
-1
if the length was not specified or malformed
(not a number).connect()
,
getResponseHeader(java.lang.String)
public static void removePointToPointHeaders(MimeHeaders headers, boolean response)
headers
- The mime headers to be modified.response
- true
to remove the point-to-point response
headers, false
to remove the point-to-point
request headers.public int addHeaders(String tokens, Properties props)
tokens
- a white space delimited set of tokens that refer
to headers that will be added to the HTTP request.props
- Keys of the form [token].name
and
[token].value
are used to lookup additional
HTTP headers to be added to the request.
setRequestHeader(java.lang.String, java.lang.String)
public String getContent(String encoding) throws IOException, UnsupportedEncodingException
encoding
- The ISO character encoding to use, if
the encoding can't be determined by
context.
IOException
UnsupportedEncodingException
public String getContent() throws IOException, UnsupportedEncodingException
IOException
UnsupportedEncodingException
public String getEncoding()
|
Version 2.1, Generated 12/30/04 Copyright (c) 2001-2004, Sun Microsystems. |
||||||||
PREV CLASS NEXT CLASS | FRAMES NO FRAMES | ||||||||
SUMMARY: NESTED | FIELD | CONSTR | METHOD | DETAIL: FIELD | CONSTR | METHOD |