net.noderunner.http
Class EasyHttpClient

java.lang.Object
  extended by net.noderunner.http.EasyHttpClient

public class EasyHttpClient
extends java.lang.Object

An easy-to-use HTTP client that can perform any standard HTTP operation. Opens a connection that can be used over and over again, unlike the Java HTTP client. Also allows for streamed data input and output, and allows for data operations to be performed without the use of call-backs.

The underlying connection is kept active until close() is called. After every operation, the data sent by the HTTP server must be fully read, otherwise, any following operation on the same connection may not execute successfully. The character readers returned can be read or discarded easily with the HttpUtil.read(java.io.InputStream) and HttpUtil.discard(java.io.BufferedReader) methods. If the HTTP connection is to be used again, do not call close on any returned character readers.

Example GET usage: (Retrieves the root document)

 URL url = new URL("http://example.com");
 EasyHttpClient client = new EasyHttpClient(url);
 String document = HttpUtil.read(client.doGet());
 client.setFile("/somedir/somefile.html");
 String document2 = HttpUtil.read(client.doGet());
 client.close();
 

Example POST usage: (Posts URL encoded data to the same CGI script)

 URL url = new URL("http://example.com/post.cgi");
 EasyHttpClientFactory factory = new EasyHttpClientFactory();
 EasyHttpClient client = factory.makePostClient(url);
 BufferedReader br;
 java.util.Map map = new HashMap();
 map.put("name", "Joe");
 map.put("business", "Bar");
 br = client.doPostUrlEncoded(HttpUtil.urlEncode(map));
 EasyHttpClient.discard(br);

 map.put("name", "Alice");
 map.put("business", "Foo");
 br = client.doPostUrlEncoded(HttpUtil.urlEncode(map));
 EasyHttpClient.discard(br);

 client.close();
 

Example DELETE method usage: (Deletes two remote files)

 URL url = new URL("http://example.com/somefile");
 EasyHttpClientFactory factory = new EasyHttpClientFactory();
 EasyHttpClient client = factory.makeClient(url, RequestLine.METHOD_DELETE);
 client.doOperation();
 client.setFile("/somefile2");
 client.doOperation();
 

Example binary POST method usage: (Posts an image to a CGI script)

 URL url = new URL("http://example.com/post.cgi");
 EasyHttpClientFactory factory = new EasyHttpClientFactory();
 EasyHttpClient client = factory.makePostClient();
 InputStream fileIS = new FileInputStream("somefile.jpeg");
 InputStream resultIS = client.doOperation(fileIS, -1, "image/jpeg");
 
 

Design notes: This class is designed as a wrapper, allowing the underlying HttpClient behavior to be delegated in another class. The goal is to provide a lot of functionality that users will not have to re-implement deal with many of the common HTTP use-cases. If something significant must be altered in what HTTP-level functionality is needed, it should be implementable by extending an existing HttpClient. The operations on any HttpClient can then be simply extended with this wrapper.

See Also:
EasyHttpClientFactory, HttpClient

Constructor Summary
EasyHttpClient(HttpClient client, RequestLine requestLine, MessageHeaders headers)
          Constructs a new HTTP client with a specific wrapped client, request line, and headers.
EasyHttpClient(HttpClient c, java.net.URL url, Method method)
          Constructs a new HTTP client.
EasyHttpClient(java.net.URL url)
          Constructs a new HTTP client.
EasyHttpClient(java.net.URL url, Method method)
          Constructs a new HTTP client.
 
Method Summary
 void close()
          Closes the wrapped HttpClient.
 java.io.BufferedReader doGet()
          Performs a GET operation, returning a BufferedReader, which can be used to read the response body.
 void doOperation()
          Performs whatever operation was specified in the request line, as passed into the constructor.
 java.io.InputStream doOperation(java.io.InputStream is, int len, java.lang.String contentType)
          Performs whatever operation was specified in the request, as passed into the constructor.
 java.io.BufferedReader doPost(byte[] data, int off, int len, java.lang.String contentType)
          Performs a POST operation, returning a BufferedReader for reading the response body.
 java.io.BufferedReader doPostUrlEncoded(byte[] urlEncodedData)
          Performs a POST operation, returning a BufferedReader for reading the response body.
 MessageHeaders getHeaders()
          Returns the message headers in use.
 Response getLastResponse()
          Returns the last HTTP response, including headers, resulting from the last doPost, doGet, or doOperation call.
static void main(java.lang.String[] args)
          Performs a command-line test.
 void setCheckStatus(boolean checkStatus)
          Sets if the status will automatically be checked for a 200-level response or whether or not the status will be ignored.
 void setFile(java.lang.String fileName)
          Allows a subsequent operation to be repeated with a different file on the same connection.
 void setMethod(Method method)
          Allows a subsequent operation to be repeated with a different method on the same connection.
 java.lang.String toString()
          Returns debug information.
 
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, wait, wait, wait
 

Constructor Detail

EasyHttpClient

public EasyHttpClient(HttpClient client,
                      RequestLine requestLine,
                      MessageHeaders headers)
Constructs a new HTTP client with a specific wrapped client, request line, and headers.


EasyHttpClient

public EasyHttpClient(java.net.URL url,
                      Method method)
Constructs a new HTTP client.


EasyHttpClient

public EasyHttpClient(HttpClient c,
                      java.net.URL url,
                      Method method)
Constructs a new HTTP client.


EasyHttpClient

public EasyHttpClient(java.net.URL url)
Constructs a new HTTP client.

Method Detail

setFile

public void setFile(java.lang.String fileName)
Allows a subsequent operation to be repeated with a different file on the same connection. Any previously set headers remain identical.


setMethod

public void setMethod(Method method)
Allows a subsequent operation to be repeated with a different method on the same connection. Any previously set headers remain identical.


getHeaders

public MessageHeaders getHeaders()
Returns the message headers in use. These may be modified as required.


setCheckStatus

public void setCheckStatus(boolean checkStatus)
Sets if the status will automatically be checked for a 200-level response or whether or not the status will be ignored. By default, status is checked.


getLastResponse

public Response getLastResponse()
Returns the last HTTP response, including headers, resulting from the last doPost, doGet, or doOperation call. Returns null if no response information exists.


doGet

public java.io.BufferedReader doGet()
                             throws java.io.IOException
Performs a GET operation, returning a BufferedReader, which can be used to read the response body.

Returns:
null if no body was obtained
Throws:
HttpException - if the input stream could not be created, or the status was not allowed
java.io.IOException
See Also:
getLastResponse(), setCheckStatus(boolean), HttpUtil.read(java.io.InputStream), HttpUtil.discard(java.io.BufferedReader)

doPost

public java.io.BufferedReader doPost(byte[] data,
                                     int off,
                                     int len,
                                     java.lang.String contentType)
                              throws java.io.IOException
Performs a POST operation, returning a BufferedReader for reading the response body. The data type to be transferred may be indicated.

Parameters:
data - source data array
off - zero-based offset in source
len - length of array to send
contentType - content type to indicate, optionally null to indicate no content type
Returns:
null if no body was obtained
Throws:
java.io.IOException
See Also:
getLastResponse(), setCheckStatus(boolean), HttpUtil.read(java.io.InputStream), HttpUtil.discard(java.io.BufferedReader)

doPostUrlEncoded

public java.io.BufferedReader doPostUrlEncoded(byte[] urlEncodedData)
                                        throws java.io.IOException
Performs a POST operation, returning a BufferedReader for reading the response body. The content type header is set to indicate the x-www-form-urlencoded type.

Parameters:
urlEncodedData - data to send (ASCII format)
Throws:
java.io.IOException
See Also:
HttpUtil.urlEncode(java.lang.String[], java.lang.String)

doOperation

public void doOperation()
                 throws java.io.IOException
Performs whatever operation was specified in the request line, as passed into the constructor. Handles no input or output. This method assumes no data will be returned by the server. If response data is returned, it is thrown away. Call the other doOperation method to have the data returned.

Throws:
HttpException - if (unexpectedly) HTTP was obtained
java.io.IOException

doOperation

public java.io.InputStream doOperation(java.io.InputStream is,
                                       int len,
                                       java.lang.String contentType)
                                throws java.io.IOException
Performs whatever operation was specified in the request, as passed into the constructor. This method can be used to perform tasks not handled by the basic doPost and doGet methods. Utilizes the class GeneralDataPoster to do the data posting.

Parameters:
is - data stream to be copied and output over HTTP; if null, no data is written; if the input stream supports marking, the post operation may be retried, if not any retry will throw an HttpException
len - if len >= 0, sets the content-length header to this length; if len < 0, sets the chunked-encoding header
contentType - if not null, specifies the data content type in the request
Returns:
wrapped input stream for reading HTTP server data from
Throws:
HttpException - if the supplied input stream does not contain enough data to be sent
java.lang.IllegalArgumentException - if the supplied input stream is null and a non-zero length was indicated
java.io.IOException
See Also:
HttpUtil.readFully(java.io.InputStream)

close

public void close()
           throws java.io.IOException
Closes the wrapped HttpClient.

Throws:
java.io.IOException

toString

public java.lang.String toString()
Returns debug information.

Overrides:
toString in class java.lang.Object

main

public static void main(java.lang.String[] args)
                 throws java.lang.Exception
Performs a command-line test.

Throws:
java.lang.Exception


Copyright © 2009. All Rights Reserved.