org.apache.commons.httpclient
Class HttpConnection

java.lang.Object
  |
  +--org.apache.commons.httpclient.HttpConnection

public class HttpConnection
extends Object

An abstraction of an HTTP InputStream and OutputStream pair, together with the relevant attributes.

The following options are set on the socket before getting the input/output streams in the open() method:
Socket Method Sockets Option Configuration
Socket.setTcpNoDelay(boolean) SO_NODELAY None
Socket.setSoTimeout(int) SO_TIMEOUT setConnectionTimeout(int)

Version:
$Revision: 1.67.2.2 $ $Date: 2003/07/31 17:59:17 $
Author:
Rod Waldhoff, Sean C. Sullivan, Ortwin Gl??ck, Jeff Dever, Mike Bowler, Oleg Kalnichevski, Michael Becke, Eric E Johnson, Laura Werner

Inner Class Summary
 interface HttpConnection.ConnectionTimeoutException
          Signals that a timeout occured while opening the socket.
 
Field Summary
protected  boolean isOpen
          Whether or not I am connected.
 
Constructor Summary
HttpConnection(HostConfiguration hostConfiguration)
          Creates a new HttpConnection.
HttpConnection(String host, int port)
          Constructor.
HttpConnection(String host, int port, boolean secure)
          Deprecated. use HttpConnection(String, int, Protocol)
HttpConnection(String host, int port, Protocol protocol)
          Constructor.
HttpConnection(String proxyHost, int proxyPort, String host, int port)
          Constructor.
HttpConnection(String proxyHost, int proxyPort, String host, int port, boolean secure)
          Deprecated. use HttpConnection(String, int, String, int, Protocol)
HttpConnection(String proxyHost, int proxyPort, String host, String virtualHost, int port, Protocol protocol)
          Create an instance
HttpConnection(String host, String virtualHost, int port, Protocol protocol)
          Constructor.
 
Method Summary
protected  void assertNotOpen()
          Throw an IllegalStateException if I am connected.
protected  void assertOpen()
          Throw an IllegalStateException if I am not connected.
 void close()
          Close my socket and streams.
protected  void closeSocketAndStreams()
          Close everything out.
 void flushRequestOutputStream()
          Flushes the output request stream.
 String getHost()
          Return my host name.
 HttpConnectionManager getHttpConnectionManager()
          Returns the httpConnectionManager.
 InputStream getLastResponseInputStream()
          Returns the stream used to read the last response's body.
 InetAddress getLocalAddress()
          Return the local address used when creating the connection.
 int getPort()
          Return my port.
 Protocol getProtocol()
          Get the protocol.
 String getProxyHost()
          Return my proxy host.
 int getProxyPort()
          Return my proxy port.
 OutputStream getRequestOutputStream()
          Return a OutputStream suitable for writing (possibly chunked) bytes to my OutputStream.
 OutputStream getRequestOutputStream(boolean useChunking)
          Deprecated. Use new ChunkedOutputStream(httpConnecion.getRequestOutputStream());
 InputStream getResponseInputStream()
          Return the response input stream
 InputStream getResponseInputStream(HttpMethod method)
          Deprecated. Use getResponseInputStream() instead.
 int getSendBufferSize()
          Gets the socket's sendBufferSize.
 int getSoTimeout()
          Return my Socket's timeout, via Socket.setSoTimeout(int), if the connection is already open.
 String getVirtualHost()
          Return my virtual host name.
 boolean isOpen()
          Return true if I am connected, false otherwise.
 boolean isProxied()
          Return true if I am (or I will be) connected via a proxy, false otherwise.
 boolean isResponseAvailable()
          Tests if input data avaialble.
 boolean isResponseAvailable(int timeout)
          Tests if input data becomes available within the given period time in milliseconds.
 boolean isSecure()
          Return true if I will (or I am) connected over a secure (HTTPS/SSL) protocol.
protected  boolean isStale()
          Determines whether this connection is "stale", which is to say that either it is no longer open, or an attempt to read the connection would fail.
 boolean isStaleCheckingEnabled()
          Tests if stale checking is enabled.
 boolean isTransparent()
          Indicates if the connection is completely transparent from end to end.
 void open()
          Open this connection to the current host and port (via a proxy if so configured).
 void print(String data)
          Write the specified String (as bytes) to my output stream.
 void printLine()
          Write "\r\n".getBytes() to my output stream.
 void printLine(String data)
          Write the specified String (as bytes), followed by "\r\n".getBytes() to my output stream.
 String readLine()
          Read up to "\n" from my (unchunked) input stream.
 void releaseConnection()
          Release the connection.
 void setConnectionTimeout(int timeout)
          Sets the connection timeout.
 void setHost(String host)
          Set my host name.
 void setHttpConnectionManager(HttpConnectionManager httpConnectionManager)
          Sets the httpConnectionManager.
 void setLastResponseInputStream(InputStream inStream)
          Set the state to keep track of the last response for the last request.
 void setLocalAddress(InetAddress localAddress)
          Set the local address used when creating the connection.
 void setPort(int port)
          Set my port.
 void setProtocol(Protocol protocol)
          Sets the protocol used by this connection.
 void setProxyHost(String host)
          Set the host I should proxy through.
 void setProxyPort(int port)
          Set the port I should proxy through.
 void setSecure(boolean secure)
          Deprecated. use setProtocol(Protocol)
 void setSendBufferSize(int sendBufferSize)
          Sets the socket's sendBufferSize.
 void setSoTimeout(int timeout)
          Set my Socket's timeout, via Socket.setSoTimeout(int).
 void setStaleCheckingEnabled(boolean staleCheckEnabled)
          Sets whether or not isStale() will be called when testing if this connection is open.
 void setVirtualHost(String host)
          Set my virtual host name.
 void shutdownOutput()
          Shutdown my Socket's output, via Socket.shutdownOutput() when running on JVM 1.3 or higher.
 void tunnelCreated()
          Calling this method indicates that the proxy has successfully created the tunnel to the host.
 void write(byte[] data)
          Write the specified bytes to my output stream.
 void write(byte[] data, int offset, int length)
          Write length bytes in data starting at offset to my output stream.
 void writeLine()
          Write "\r\n".getBytes() to my output stream.
 void writeLine(byte[] data)
          Write the specified bytes, followed by "\r\n".getBytes() to my output stream.
 
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait
 

Field Detail

isOpen

protected boolean isOpen
Whether or not I am connected.
Constructor Detail

HttpConnection

public HttpConnection(String host,
                      int port)
Constructor.
Parameters:
host - the host I should connect to
port - the port I should connect to

HttpConnection

public HttpConnection(String host,
                      int port,
                      boolean secure)
Deprecated. use HttpConnection(String, int, Protocol)

Constructor.
Parameters:
host - the host I should connect to
port - the port I should connect to
secure - when true, connect via HTTPS (SSL)
See Also:
HttpConnection(String,int,Protocol)

HttpConnection

public HttpConnection(String host,
                      int port,
                      Protocol protocol)
Constructor.
Parameters:
host - the host I should connect to
port - the port I should connect to
protocol - the protocol to use

HttpConnection

public HttpConnection(String host,
                      String virtualHost,
                      int port,
                      Protocol protocol)
Constructor.
Parameters:
host - the host I should connect to
virtualHost - the virtual host I will be sending requests to
port - the port I should connect to
protocol - the protocol to use

HttpConnection

public HttpConnection(String proxyHost,
                      int proxyPort,
                      String host,
                      int port)
Constructor.
Parameters:
proxyHost - the host I should proxy via
proxyPort - the port I should proxy via
host - the host I should connect to
port - the port I should connect to

HttpConnection

public HttpConnection(String proxyHost,
                      int proxyPort,
                      String host,
                      int port,
                      boolean secure)
Deprecated. use HttpConnection(String, int, String, int, Protocol)

Fully-specified constructor.
Parameters:
proxyHost - the host I should proxy via
proxyPort - the port I should proxy via
host - the host I should connect to. Parameter value must be non-null.
port - the port I should connect to
secure - when true, connect via HTTPS (SSL)
See Also:
HttpConnection(String, int, String, String, int, Protocol)

HttpConnection

public HttpConnection(HostConfiguration hostConfiguration)
Creates a new HttpConnection.
Parameters:
hostConfiguration - the host/proxy/protocol to use

HttpConnection

public HttpConnection(String proxyHost,
                      int proxyPort,
                      String host,
                      String virtualHost,
                      int port,
                      Protocol protocol)
Create an instance
Parameters:
proxyHost - the host I should proxy via
proxyPort - the port I should proxy via
host - the host I should connect to. Parameter value must be non-null.
virtualHost - the virtual host I will be sending requests to
port - the port I should connect to
protocol - The protocol to use. Parameter value must be non-null.
Method Detail

getHost

public String getHost()
Return my host name.
Returns:
my host.

setHost

public void setHost(String host)
             throws IllegalStateException
Set my host name.
Parameters:
host - the host I should connect to. Parameter value must be non-null.
Throws:
IllegalStateException - if I am already connected

getVirtualHost

public String getVirtualHost()
Return my virtual host name.
Returns:
my virtual host.

setVirtualHost

public void setVirtualHost(String host)
                    throws IllegalStateException
Set my virtual host name.
Parameters:
host - the virtual host name that should be used instead of physical host name when sending HTTP requests. Virtual host name can be set to null if virtual host name is not to be used
Throws:
IllegalStateException - if I am already connected

getPort

public int getPort()
Return my port. If the port is -1 (or less than 0) the default port for the current protocol is returned.
Returns:
my port.

setPort

public void setPort(int port)
             throws IllegalStateException
Set my port.
Parameters:
port - the port I should connect to
Throws:
IllegalStateException - if I am already connected

getProxyHost

public String getProxyHost()
Return my proxy host.
Returns:
my proxy host.

setProxyHost

public void setProxyHost(String host)
                  throws IllegalStateException
Set the host I should proxy through.
Parameters:
host - the host I should proxy through.
Throws:
IllegalStateException - if I am already connected

getProxyPort

public int getProxyPort()
Return my proxy port.
Returns:
my proxy port.

setProxyPort

public void setProxyPort(int port)
                  throws IllegalStateException
Set the port I should proxy through.
Parameters:
port - the host I should proxy through.
Throws:
IllegalStateException - if I am already connected

isSecure

public boolean isSecure()
Return true if I will (or I am) connected over a secure (HTTPS/SSL) protocol.
Returns:
true if I will (or I am) connected over a secure (HTTPS/SSL) protocol.

getProtocol

public Protocol getProtocol()
Get the protocol.
Returns:
HTTPS if secure, HTTP otherwise

setSecure

public void setSecure(boolean secure)
               throws IllegalStateException
Deprecated. use setProtocol(Protocol)

Set whether or not I should connect over HTTPS (SSL).
Parameters:
secure - whether or not I should connect over HTTPS (SSL).
Throws:
IllegalStateException - if I am already connected
See Also:
setProtocol(Protocol)

setProtocol

public void setProtocol(Protocol protocol)
Sets the protocol used by this connection.
Parameters:
protocol - The new protocol.

getLocalAddress

public InetAddress getLocalAddress()
Return the local address used when creating the connection. If null, the default address is used.
Returns:
InetAddress the local address to be used when creating Sockets

setLocalAddress

public void setLocalAddress(InetAddress localAddress)
Set the local address used when creating the connection. If unset or null, the default address is used.
Parameters:
localAddress - the local address to use

isOpen

public boolean isOpen()
Return true if I am connected, false otherwise.
Returns:
true if I am connected

isStaleCheckingEnabled

public boolean isStaleCheckingEnabled()
Tests if stale checking is enabled.
Returns:
true if enabled
See Also:
isStale()

setStaleCheckingEnabled

public void setStaleCheckingEnabled(boolean staleCheckEnabled)
Sets whether or not isStale() will be called when testing if this connection is open.
Parameters:
staleCheckEnabled - true to enable isStale()
See Also:
isStale(), isOpen()

isStale

protected boolean isStale()
Determines whether this connection is "stale", which is to say that either it is no longer open, or an attempt to read the connection would fail.

Unfortunately, due to the limitations of the JREs prior to 1.4, it is not possible to test a connection to see if both the read and write channels are open - except by reading and writing. This leads to a difficulty when some connections leave the "write" channel open, but close the read channel and ignore the request. This function attempts to ameliorate that problem by doing a test read, assuming that the caller will be doing a write followed by a read, rather than the other way around.

To avoid side-effects, the underlying connection is wrapped by a PushbackInputStream, so although data might be read, what is visible to clients of the connection will not change with this call.

Returns:
true if the connection is already closed, or a read would fail.

isProxied

public boolean isProxied()
Return true if I am (or I will be) connected via a proxy, false otherwise.
Returns:
true if I am (or I will be) connected via a proxy, false otherwise.

setLastResponseInputStream

public void setLastResponseInputStream(InputStream inStream)
Set the state to keep track of the last response for the last request.

The connection managers use this to ensure that previous requests are properly closed before a new request is attempted. That way, a GET request need not be read in its entirety before a new request is issued. Instead, this stream can be closed as appropriate.

Parameters:
inStream - The stream associated with an HttpMethod.

getLastResponseInputStream

public InputStream getLastResponseInputStream()
Returns the stream used to read the last response's body.

Clients will generally not need to call this function unless using HttpConnection directly, instead of calling HttpClient.executeMethod(org.apache.commons.httpclient.HttpMethod). For those clients, call this function, and if it returns a non-null stream, close the stream before attempting to execute a method. Note that calling "close" on the stream returned by this function may close the connection if the previous response contained a "Connection: close" header.

Returns:
An InputStream corresponding to the body of the last response.

setSoTimeout

public void setSoTimeout(int timeout)
                  throws SocketException,
                         IllegalStateException
Set my Socket's timeout, via Socket.setSoTimeout(int). If the connection is already open, the SO_TIMEOUT is changed. If no connection is open, then subsequent connections will use the timeout value.

Note: This is not a connection timeout but a timeout on network traffic!

Parameters:
timeout - the timeout value
Throws:
SocketException - - if there is an error in the underlying protocol, such as a TCP error.
IllegalStateException - if I am not connected

getSoTimeout

public int getSoTimeout()
                 throws SocketException
Return my Socket's timeout, via Socket.setSoTimeout(int), if the connection is already open. If no connection is open, return the value subsequent connection will use.

Note: This is not a connection timeout but a timeout on network traffic!

Returns:
the timeout value

setConnectionTimeout

public void setConnectionTimeout(int timeout)
Sets the connection timeout. This is the maximum time that may be spent until a connection is established. The connection will fail after this amount of time.
Parameters:
timeout - The timeout in milliseconds. 0 means timeout is not used.

open

public void open()
          throws IOException
Open this connection to the current host and port (via a proxy if so configured). The underlying socket is created from the ProtocolSocketFactory.
Throws:
IOException - when there are errors opening the connection

tunnelCreated

public void tunnelCreated()
                   throws IllegalStateException,
                          IOException
Calling this method indicates that the proxy has successfully created the tunnel to the host. The socket will be switched to the secure socket. Subsequent communication is done via the secure socket. The method can only be called once on a proxied secure connection.
Throws:
IllegalStateException - if connection is not secure and proxied or if the socket is already secure.
IOException - if an error occured creating the secure socket

isTransparent

public boolean isTransparent()
Indicates if the connection is completely transparent from end to end.
Returns:
true if conncetion is not proxied or tunneled through a transparent proxy; false otherwise.

flushRequestOutputStream

public void flushRequestOutputStream()
                              throws IOException
Flushes the output request stream. This method should be called to ensure that data written to the request OutputStream is sent to the server.
Throws:
IOException - if an I/O problem occurs

getRequestOutputStream

public OutputStream getRequestOutputStream()
                                    throws IOException,
                                           IllegalStateException
Return a OutputStream suitable for writing (possibly chunked) bytes to my OutputStream.
Returns:
a stream to write the request to
Throws:
IllegalStateException - if I am not connected
IOException - if an I/O problem occurs

getRequestOutputStream

public OutputStream getRequestOutputStream(boolean useChunking)
                                    throws IOException,
                                           IllegalStateException
Deprecated. Use new ChunkedOutputStream(httpConnecion.getRequestOutputStream());

Return a OutputStream suitable for writing (possibly chunked) bytes to my OutputStream.
Parameters:
useChunking - when true the chunked transfer-encoding will be used
Returns:
a stream to write the request to
Throws:
IllegalStateException - if I am not connected
IOException - if an I/O problem occurs

getResponseInputStream

public InputStream getResponseInputStream(HttpMethod method)
                                   throws IOException,
                                          IllegalStateException
Deprecated. Use getResponseInputStream() instead.

Return a InputStream suitable for reading (possibly chunked) bytes from my InputStream.

If the given HttpMethod contains a Transfer-Encoding: chunked header, the returned stream will be configured to read chunked bytes.

Parameters:
method - This argument is ignored.
Returns:
a stream to read the response from
Throws:
IllegalStateException - if I am not connected
IOException - if an I/O problem occurs

getResponseInputStream

public InputStream getResponseInputStream()
                                   throws IOException,
                                          IllegalStateException
Return the response input stream
Returns:
InputStream The response input stream.
Throws:
IOException - If an IO problem occurs
IllegalStateException - If the connection isn't open.

isResponseAvailable

public boolean isResponseAvailable()
                            throws IOException
Tests if input data avaialble. This method returns immediately and does not perform any read operations on the input socket
Returns:
boolean true if input data is availble, false otherwise.
Throws:
IOException - If an IO problem occurs
IllegalStateException - If the connection isn't open.

isResponseAvailable

public boolean isResponseAvailable(int timeout)
                            throws IOException
Tests if input data becomes available within the given period time in milliseconds.
Parameters:
timeout - The number milliseconds to wait for input data to become available
Returns:
boolean true if input data is availble, false otherwise.
Throws:
IOException - If an IO problem occurs
IllegalStateException - If the connection isn't open.

write

public void write(byte[] data)
           throws IOException,
                  IllegalStateException,
                  HttpRecoverableException
Write the specified bytes to my output stream.
Parameters:
data - the data to be written
Throws:
HttpRecoverableException - if a SocketException occurs
IllegalStateException - if not connected
IOException - if an I/O problem occurs
See Also:
write(byte[],int,int)

write

public void write(byte[] data,
                  int offset,
                  int length)
           throws IOException,
                  IllegalStateException,
                  HttpRecoverableException
Write length bytes in data starting at offset to my output stream. The general contract for write(b, off, len) is that some of the bytes in the array b are written to the output stream in order; element b[off] is the first byte written and b[off+len-1] is the last byte written by this operation.
Parameters:
data - array containing the data to be written.
offset - the start offset in the data.
length - the number of bytes to write.
Throws:
HttpRecoverableException - if a SocketException occurs
IllegalStateException - if not connected
IOException - if an I/O problem occurs

writeLine

public void writeLine(byte[] data)
               throws IOException,
                      IllegalStateException,
                      HttpRecoverableException
Write the specified bytes, followed by "\r\n".getBytes() to my output stream.
Parameters:
data - the bytes to be written
Throws:
HttpRecoverableException - when socket exceptions occur writing data
IllegalStateException - if I am not connected
IOException - if an I/O problem occurs

writeLine

public void writeLine()
               throws IOException,
                      IllegalStateException,
                      HttpRecoverableException
Write "\r\n".getBytes() to my output stream.
Throws:
HttpRecoverableException - when socket exceptions occur writing data
IllegalStateException - if I am not connected
IOException - if an I/O problem occurs

print

public void print(String data)
           throws IOException,
                  IllegalStateException,
                  HttpRecoverableException
Write the specified String (as bytes) to my output stream.
Parameters:
data - the string to be written
Throws:
HttpRecoverableException - when socket exceptions occur writing data
IllegalStateException - if I am not connected
IOException - if an I/O problem occurs

printLine

public void printLine(String data)
               throws IOException,
                      IllegalStateException,
                      HttpRecoverableException
Write the specified String (as bytes), followed by "\r\n".getBytes() to my output stream.
Parameters:
data - the data to be written
Throws:
HttpRecoverableException - when socket exceptions occur writing data
IllegalStateException - if I am not connected
IOException - if an I/O problem occurs

printLine

public void printLine()
               throws IOException,
                      IllegalStateException,
                      HttpRecoverableException
Write "\r\n".getBytes() to my output stream.
Throws:
HttpRecoverableException - when socket exceptions occur writing data
IllegalStateException - if I am not connected
IOException - if an I/O problem occurs

readLine

public String readLine()
                throws IOException,
                       IllegalStateException
Read up to "\n" from my (unchunked) input stream. If the stream ends before the line terminator is found, the last part of the string will still be returned.
Returns:
a line from the response
Throws:
IllegalStateException - if I am not connected
IOException - if an I/O problem occurs

shutdownOutput

public void shutdownOutput()
Shutdown my Socket's output, via Socket.shutdownOutput() when running on JVM 1.3 or higher.

close

public void close()
Close my socket and streams.

getHttpConnectionManager

public HttpConnectionManager getHttpConnectionManager()
Returns the httpConnectionManager.
Returns:
HttpConnectionManager

setHttpConnectionManager

public void setHttpConnectionManager(HttpConnectionManager httpConnectionManager)
Sets the httpConnectionManager.
Parameters:
httpConnectionManager - The httpConnectionManager to set

releaseConnection

public void releaseConnection()
Release the connection.

closeSocketAndStreams

protected void closeSocketAndStreams()
Close everything out.

assertNotOpen

protected void assertNotOpen()
                      throws IllegalStateException
Throw an IllegalStateException if I am connected.
Throws:
IllegalStateException - if connected

assertOpen

protected void assertOpen()
                   throws IllegalStateException
Throw an IllegalStateException if I am not connected.
Throws:
IllegalStateException - if not connected

getSendBufferSize

public int getSendBufferSize()
                      throws SocketException
Gets the socket's sendBufferSize.
Returns:
the size of the buffer for the socket OutputStream, -1 if the value has not been set and the socket has not been opened
Throws:
SocketException - if an error occurs while getting the socket value
See Also:
Socket.getSendBufferSize()

setSendBufferSize

public void setSendBufferSize(int sendBufferSize)
                       throws SocketException
Sets the socket's sendBufferSize.
Parameters:
sendBufferSize - the size to set for the socket OutputStream
Throws:
SocketException - if an error occurs while setting the socket value
See Also:
Socket.setSendBufferSize(int)


Copyright © 2001-2003 Apache Software Foundation. All Rights Reserved.