org.xlightweb.client
Class HttpClient

Package class diagram package HttpClient
java.lang.Object
  extended by org.xlightweb.client.HttpClient
All Implemented Interfaces:
Closeable, IHttpClientEndpoint, IConnectionPool

public class HttpClient
extends Object
implements IHttpClientEndpoint, IConnectionPool, Closeable

Higher level client-side abstraction of the client side endpoint. Internally, the HttpClient uses a pool of HttpClientConnection to perform the requests. Example:

   HttpClient httpClient = new HttpClient();
   
   // set some properties
   httpClient.setFollowsRedirect(true);  
   httpClient.setAutoHandleCookies(false);
   // ...
   
   // perform a synchronous call 
   IHttpResponse response = httpClient.call(new GetRequest("http://www.gmx.com/index.html"));
   System.out.println(response.getStatus());
   
   BlockingBodyDataSource bodyChannel = response.getBlockingBody();
   System.out.println(bodyChannel.readString());
   
   
   // perform an asynchronous request
   MyResponseHandler respHdl = new MyResponseHandler();
   httpClient.send(new HttpRequestHeader("GET", "http://www.gmx.com/index.html"), respHdl);
   
   //..
   
   httpClient.close(); 
 
The HttpClient is thread-safe


Field Summary
static boolean DEFAULT_AUTOHANDLING_COOKIES
           
static int DEFAULT_CACHE_SIZE
           
static int DEFAULT_CREATION_MAX_WAIT_TIMEOUT
           
static boolean DEFAULT_FOLLOWS_REDIRECT
           
static int DEFAULT_MAX_REDIRECTS
           
static int DEFAULT_MAX_RETRIES
           
static int DEFAULT_POOLED_IDLE_TIMEOUT_MILLIS
           
static int DEFAULT_POOLED_LIFE_TIMEOUT_MILLIS
           
static boolean DEFAULT_PROXY_ACTIVATED
           
static Long DEFAULT_RESPONSE_TIMEOUT_SEC
           
static boolean DEFAULT_TREAT_302_REDIRECT_AS_303
           
 
Fields inherited from interface org.xlightweb.client.IHttpClientEndpoint
DEFAULT_AUTOHANDLE_100CONTINUE_RESPONSE
 
Fields inherited from interface org.xsocket.connection.IConnectionPool
DEFAULT_CREATION_TIMEOUT_MILLIS, DEFAULT_IDLE_TIMEOUT_MILLIS, DEFAULT_LIFE_TIMEOUT_MILLIS, DEFAULT_MAX_ACTIVE, DEFAULT_MAX_ACTIVE_PER_SERVER, DEFAULT_MAX_IDLE, DEFAULT_MAX_WAIT_MILLIS, DEFAULT_MAX_WAITING
 
Constructor Summary
HttpClient()
          constructor
HttpClient(IHttpRequestHandler... interceptors)
          constructor
HttpClient(SSLContext sslCtx)
          constructor
HttpClient(SSLContext sslCtx, IHttpRequestHandler... interceptors)
          constructor
 
Method Summary
 void addInterceptor(IHttpRequestHandler interceptor)
          adds an interceptor.
 void addListener(ILifeCycle listener)
          
 IHttpResponse call(IHttpRequest request)
          performs a request.
 void close()
          
 List<String> getActiveConnectionInfos()
          
 long getBodyDataReceiveTimeoutMillis()
          
 int getCacheMaxSizeKB()
          returns the max cache size
 float getCacheSizeKB()
          returns the cache size
 boolean getCallReturnOnMessage()
          return true when the call will return, if the message is received
 int getConnectTimeoutMillis()
          returns the connect timeout
 boolean getFollowsRedirect()
          returns true, if redirects should be followed
 String getId()
          returns a unique id
 List<String> getIdleConnectionInfos()
          
 int getMaxActive()
          
 int getMaxActivePerServer()
          
 int getMaxIdle()
          
 int getMaxRedirects()
          get the max redirects (of GET, DELETE and PUT calls)
 int getMaxRetries()
          get the max retries (of GET, DELETE and PUT calls)
 int getNumActive()
          
 int getNumCacheHit()
          returns the number of cache hits
 int getNumCacheMiss()
          returns the number of cache misses
 int getNumCreated()
          
 int getNumDestroyed()
          
 int getNumIdle()
          
 int getNumTimeoutPooledMaxIdleTime()
          
 int getNumTimeoutPooledMaxLifeTime()
          
 int getPooledMaxIdleTimeMillis()
          
 int getPooledMaxLifeTimeMillis()
          
 long getResponseTimeoutMillis()
          returns the response timeout
 boolean isAutohandleCookies()
          returns if cookies should be auto handled
 boolean isAutoUncompress()
          return true, if the response will be uncompressed (if compressed)
 boolean isCacheShared()
          returns true, if the cache is shared between users
 boolean isOpen()
          
 boolean isTreat302RedirectAs303()
          gets if a 302 response should be treat as a 303 response
 boolean removeListener(ILifeCycle listener)
          
 IFutureResponse send(IHttpRequest request)
          send the request.
 BodyDataSink send(IHttpRequestHeader requestHeader, IHttpResponseHandler responseHandler)
          send the request.
 BodyDataSink send(IHttpRequestHeader requestHeader, int contentLength, IHttpResponseHandler responseHandler)
          send the request in a plain body mode

Connection-LifeCycle support: If the request header contains a 'Connection: close' entry, the connection will be closed after the HTTP transaction
 void send(IHttpRequest request, IHttpResponseHandler responseHandler)
          send the request.
 void setAutoHandleCookies(boolean isAutohandlingCookies)
          sets if cookies should be auto handled
 void setAutoUncompress(boolean isAutoUncompress)
          set if the response will be uncompressed (if compressed)
 void setBodyDataReceiveTimeoutMillis(long bodyDataReceiveTimeoutMillis)
          
 void setCacheMaxSizeKB(int maxSizeKB)
          sets the cache size (in kilo bytes)
 void setCacheShared(boolean isSharedCache)
          sets if the cache is shared between users
 void setCallReturnOnMessage(boolean isCallReturnOnMessage)
          set that the call will return if the complete message is received.
 void setConnectTimeoutMillis(int connectTimeoutMillis)
          sets the connect timeout
 void setFollowsRedirect(boolean isFollowsRedirect)
          sets if redirects should be followed.
 void setMaxActive(int maxActive)
          
 void setMaxActivePerServer(int maxActivePerServer)
          
 void setMaxIdle(int maxIdle)
          
 void setMaxRedirects(int maxRedirects)
          set the max redirects
 void setMaxRetries(int maxRetries)
          sets the max retries (of GET, DELETE and PUT calls)
 void setPooledMaxIdleTimeMillis(int idleTimeoutMillis)
          
 void setPooledMaxLifeTimeMillis(int lifeTimeoutMillis)
          
 void setProxyHost(String proxyHost)
          sets the proxy host to use.
 void setProxyPassword(String proxyPassword)
          sets the user password for proxy authentification
 void setProxyPort(int proxyPort)
          sets the proxy port.
 void setProxyUser(String proxyUser)
          sets the user name for proxy authentification
 void setResponseBodyDefaultEncoding(String defaultEncoding)
          set the response body default encoding.
 void setResponseTimeoutMillis(long responseTimeoutMillis)
          set the response time out by performing the call or send method.
 void setTreat302RedirectAs303(boolean isTreat303RedirectAs302)
          sets if a 302 response should be treat as a 303 response
 void setWorkerpool(Executor workerpool)
          set the worker pool which will be assigned to the connections for call back handling
 String toString()
          
 
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, wait, wait, wait
 

Field Detail

DEFAULT_CREATION_MAX_WAIT_TIMEOUT

public static final int DEFAULT_CREATION_MAX_WAIT_TIMEOUT
See Also:
Constant Field Values

DEFAULT_POOLED_LIFE_TIMEOUT_MILLIS

public static final int DEFAULT_POOLED_LIFE_TIMEOUT_MILLIS
See Also:
Constant Field Values

DEFAULT_POOLED_IDLE_TIMEOUT_MILLIS

public static final int DEFAULT_POOLED_IDLE_TIMEOUT_MILLIS
See Also:
Constant Field Values

DEFAULT_TREAT_302_REDIRECT_AS_303

public static final boolean DEFAULT_TREAT_302_REDIRECT_AS_303
See Also:
Constant Field Values

DEFAULT_RESPONSE_TIMEOUT_SEC

public static final Long DEFAULT_RESPONSE_TIMEOUT_SEC

DEFAULT_MAX_REDIRECTS

public static final int DEFAULT_MAX_REDIRECTS

DEFAULT_FOLLOWS_REDIRECT

public static final boolean DEFAULT_FOLLOWS_REDIRECT

DEFAULT_MAX_RETRIES

public static final int DEFAULT_MAX_RETRIES

DEFAULT_AUTOHANDLING_COOKIES

public static final boolean DEFAULT_AUTOHANDLING_COOKIES
See Also:
Constant Field Values

DEFAULT_PROXY_ACTIVATED

public static final boolean DEFAULT_PROXY_ACTIVATED
See Also:
Constant Field Values

DEFAULT_CACHE_SIZE

public static final int DEFAULT_CACHE_SIZE
See Also:
Constant Field Values
Constructor Detail

HttpClient

public HttpClient()
constructor


HttpClient

public HttpClient(IHttpRequestHandler... interceptors)
constructor

Parameters:
interceptors - interceptor

HttpClient

public HttpClient(SSLContext sslCtx)
constructor

Parameters:
sslCtx - the ssl context to use

HttpClient

public HttpClient(SSLContext sslCtx,
                  IHttpRequestHandler... interceptors)
constructor

Parameters:
sslCtx - the ssl context to use
interceptors - the interceptors
Method Detail

addInterceptor

public void addInterceptor(IHttpRequestHandler interceptor)
adds an interceptor. Example:
  HttpClient httpClient = new HttpClient();
  
  LoadBalancerRequestInterceptor lbInterceptor = new LoadBalancerRequestInterceptor();
  lbInterceptor.addVirtualServer("http://customerService", "srv1:8030", "srv2:8030");
  httpClient.addInterceptor(lbInterceptor);
  
  // ...
  GetRequest request = new GetRequest("http://customerService/price?id=2336&amount=5656");
  IHttpResponse response = httpClient.call(request);
  //...
 
 

Parameters:
interceptor - the interceptor to add

setFollowsRedirect

public void setFollowsRedirect(boolean isFollowsRedirect)
sets if redirects should be followed.
Activating the redirect support causes that the request body will be buffered internally. This is necessary to perform a redirected request. Hint: using the Expect continue approach avoids the need for buffering.

Parameters:
isFollowsRedirect - true, if redirects should be followed

getFollowsRedirect

public boolean getFollowsRedirect()
returns true, if redirects should be followed

Returns:
true, if redirects should be followed

setAutoHandleCookies

public void setAutoHandleCookies(boolean isAutohandlingCookies)
sets if cookies should be auto handled

Parameters:
isAutohandlingCookies - true, if cookies should be auto handled

setCacheMaxSizeKB

public void setCacheMaxSizeKB(int maxSizeKB)
sets the cache size (in kilo bytes)

Parameters:
maxSizeKB - the max cache size in bytes or 0 to deactivate caching

getCacheMaxSizeKB

public int getCacheMaxSizeKB()
returns the max cache size

Returns:
the max cache size

getCacheSizeKB

public float getCacheSizeKB()
returns the cache size

Returns:
the cache size

setCacheShared

public void setCacheShared(boolean isSharedCache)
sets if the cache is shared between users

Parameters:
isSharedCache - true, if the cache is shared between users

isCacheShared

public boolean isCacheShared()
returns true, if the cache is shared between users

Returns:
true, if the cache is shared between users

setProxyHost

public void setProxyHost(String proxyHost)
sets the proxy host to use. Example:
 HttpClient httpClient = new HttpClient();
 
 // sets the proxy adress 
 httpClient.setProxyHost(host);
 httpClient.setProxyPort(port);
 
 // set auth params (only necessary if proxy authentication is required) 
 httpClient.setProxyUser(user);
 httpClient.setProxyPassword(pwd);
 
 // calling through the proxy   
 IHttpResponse resp = httpClient.call(new GetRequest("http://www.gmx.com/");
 // ...
 

Parameters:
proxyHost - the proxy host or

setProxyPort

public void setProxyPort(int proxyPort)
sets the proxy port. Default is 80. For an example see setProxyHost(String)

Parameters:
proxyPort - the proxy port

setProxyUser

public void setProxyUser(String proxyUser)
sets the user name for proxy authentification

Parameters:
proxyUser - the user name

setProxyPassword

public void setProxyPassword(String proxyPassword)
sets the user password for proxy authentification

Parameters:
proxyPassword - the user password

isAutohandleCookies

public boolean isAutohandleCookies()
returns if cookies should be auto handled

Returns:
true, if cookies should be auto handled

setAutoUncompress

public final void setAutoUncompress(boolean isAutoUncompress)
set if the response will be uncompressed (if compressed)

Parameters:
isAutoUncompress - true, if the response will be uncompressed (if compressed)

isAutoUncompress

public final boolean isAutoUncompress()
return true, if the response will be uncompressed (if compressed)

Returns:
true, if the response will be uncompressed (if compressed)

setMaxRedirects

public void setMaxRedirects(int maxRedirects)
set the max redirects

Parameters:
maxRedirects - the max redirects

getMaxRedirects

public int getMaxRedirects()
get the max redirects (of GET, DELETE and PUT calls)

Returns:
the max redirects

getMaxRetries

public int getMaxRetries()
get the max retries (of GET, DELETE and PUT calls)

Returns:
the max retries

setMaxRetries

public void setMaxRetries(int maxRetries)
sets the max retries (of GET, DELETE and PUT calls)

Parameters:
maxRetries - the max retries

setTreat302RedirectAs303

public void setTreat302RedirectAs303(boolean isTreat303RedirectAs302)
sets if a 302 response should be treat as a 303 response

Parameters:
isTreat303RedirectAs302 - true, if a 303 response should be treat a a 303 response

isTreat302RedirectAs303

public boolean isTreat302RedirectAs303()
gets if a 302 response should be treat as a 303 response

Returns:
true, if a 302 response should be treat as a 303 response

setWorkerpool

public void setWorkerpool(Executor workerpool)
set the worker pool which will be assigned to the connections for call back handling

Parameters:
workerpool - the worker pool

setResponseBodyDefaultEncoding

public void setResponseBodyDefaultEncoding(String defaultEncoding)
set the response body default encoding. According to RFC 2616 the initial value is ISO-8859-1

Parameters:
encoding - the defaultEncoding

setCallReturnOnMessage

public void setCallReturnOnMessage(boolean isCallReturnOnMessage)
set that the call will return if the complete message is received. If false is set, the call will return when the response header is received (default is false)

Parameters:
isCallReturnOnMessage - true, if the call is returned on Message

getCallReturnOnMessage

public boolean getCallReturnOnMessage()
return true when the call will return, if the message is received

Returns:
true when the call will return, if the message is received

setResponseTimeoutMillis

public void setResponseTimeoutMillis(long responseTimeoutMillis)
set the response time out by performing the call or send method.

Specified by:
setResponseTimeoutMillis in interface IHttpClientEndpoint
Parameters:
responseTimeoutMillis - the response timeout

getResponseTimeoutMillis

public long getResponseTimeoutMillis()
returns the response timeout

Specified by:
getResponseTimeoutMillis in interface IHttpClientEndpoint
Returns:
the response timeout

setBodyDataReceiveTimeoutMillis

public final void setBodyDataReceiveTimeoutMillis(long bodyDataReceiveTimeoutMillis)


getBodyDataReceiveTimeoutMillis

public final long getBodyDataReceiveTimeoutMillis()


close

public void close()
           throws IOException

Specified by:
close in interface Closeable
Throws:
IOException

isOpen

public boolean isOpen()

Specified by:
isOpen in interface IConnectionPool

getId

public String getId()
returns a unique id

Specified by:
getId in interface IHttpClientEndpoint
Returns:
the id

addListener

public void addListener(ILifeCycle listener)

Specified by:
addListener in interface IConnectionPool

removeListener

public boolean removeListener(ILifeCycle listener)

Specified by:
removeListener in interface IConnectionPool

setPooledMaxIdleTimeMillis

public void setPooledMaxIdleTimeMillis(int idleTimeoutMillis)

Specified by:
setPooledMaxIdleTimeMillis in interface IConnectionPool

getPooledMaxIdleTimeMillis

public int getPooledMaxIdleTimeMillis()

Specified by:
getPooledMaxIdleTimeMillis in interface IConnectionPool

setPooledMaxLifeTimeMillis

public void setPooledMaxLifeTimeMillis(int lifeTimeoutMillis)

Specified by:
setPooledMaxLifeTimeMillis in interface IConnectionPool

getPooledMaxLifeTimeMillis

public int getPooledMaxLifeTimeMillis()

Specified by:
getPooledMaxLifeTimeMillis in interface IConnectionPool

setMaxIdle

public void setMaxIdle(int maxIdle)

Specified by:
setMaxIdle in interface IConnectionPool

getMaxIdle

public int getMaxIdle()

Specified by:
getMaxIdle in interface IConnectionPool

setMaxActive

public void setMaxActive(int maxActive)

Specified by:
setMaxActive in interface IConnectionPool

getMaxActivePerServer

public int getMaxActivePerServer()

Specified by:
getMaxActivePerServer in interface IConnectionPool

setMaxActivePerServer

public void setMaxActivePerServer(int maxActivePerServer)

Specified by:
setMaxActivePerServer in interface IConnectionPool

getMaxActive

public int getMaxActive()

Specified by:
getMaxActive in interface IConnectionPool

setConnectTimeoutMillis

public void setConnectTimeoutMillis(int connectTimeoutMillis)
sets the connect timeout

Parameters:
connectTimeoutMillis - the connect timeout

getConnectTimeoutMillis

public int getConnectTimeoutMillis()
returns the connect timeout

Returns:
the connect timeout

getNumActive

public int getNumActive()

Specified by:
getNumActive in interface IConnectionPool

getNumIdle

public int getNumIdle()

Specified by:
getNumIdle in interface IConnectionPool

getNumCreated

public int getNumCreated()

Specified by:
getNumCreated in interface IConnectionPool

getNumDestroyed

public int getNumDestroyed()

Specified by:
getNumDestroyed in interface IConnectionPool

getNumTimeoutPooledMaxIdleTime

public int getNumTimeoutPooledMaxIdleTime()

Specified by:
getNumTimeoutPooledMaxIdleTime in interface IConnectionPool

getNumTimeoutPooledMaxLifeTime

public int getNumTimeoutPooledMaxLifeTime()

Specified by:
getNumTimeoutPooledMaxLifeTime in interface IConnectionPool

getNumCacheHit

public int getNumCacheHit()
returns the number of cache hits

Returns:
the number of cache hits

getNumCacheMiss

public int getNumCacheMiss()
returns the number of cache misses

Returns:
the number of cache misses

getActiveConnectionInfos

public List<String> getActiveConnectionInfos()

Specified by:
getActiveConnectionInfos in interface IConnectionPool

getIdleConnectionInfos

public List<String> getIdleConnectionInfos()

Specified by:
getIdleConnectionInfos in interface IConnectionPool

call

public IHttpResponse call(IHttpRequest request)
                   throws IOException,
                          SocketTimeoutException
performs a request. This method blocks until the response (header) is received.

Specified by:
call in interface IHttpClientEndpoint
Parameters:
request - the request
Returns:
the response
Throws:
IOException - if an exception occurs
ConnectException - if an error occurred while attempting to connect to a remote address and port.
SocketTimeoutException - if the received timeout is exceed

send

public IFutureResponse send(IHttpRequest request)
                     throws IOException,
                            ConnectException
send the request.

Specified by:
send in interface IHttpClientEndpoint
Parameters:
request - the request
Throws:
ConnectException - if an error occurred while attempting to connect to a remote address and port.
IOException - if an exception occurs

send

public void send(IHttpRequest request,
                 IHttpResponseHandler responseHandler)
          throws IOException,
                 ConnectException
send the request.

Specified by:
send in interface IHttpClientEndpoint
Parameters:
request - the request
responseHandler - the response handler or null (supported: IHttpRequestHandler, IHttpSocketTimeoutHandler)
Throws:
ConnectException - if an error occurred while attempting to connect to a remote address and port.
IOException - if an exception occurs

send

public BodyDataSink send(IHttpRequestHeader requestHeader,
                         int contentLength,
                         IHttpResponseHandler responseHandler)
                  throws IOException,
                         ConnectException
send the request in a plain body mode

Specified by:
send in interface IHttpClientEndpoint
Parameters:
requestHeader - the request header
contentLength - the content length
responseHandler - the response handler or null (supported: IHttpRequestHandler, IHttpSocketTimeoutHandler)
Returns:
the body handle to write
Throws:
ConnectException - if an error occurred while attempting to connect to a remote address and port.
IOException - if an exception occurs

send

public BodyDataSink send(IHttpRequestHeader requestHeader,
                         IHttpResponseHandler responseHandler)
                  throws IOException,
                         ConnectException
send the request. If the content-length header is not set, the message will send in chunked mode

Specified by:
send in interface IHttpClientEndpoint
Parameters:
requestHeader - the request header
responseHandler - the response handler or null (supported: IHttpRequestHandler, IHttpSocketTimeoutHandler)
Returns:
the body handle to write
Throws:
ConnectException - if an error occurred while attempting to connect to a remote address and port.
IOException - if an exception occurs

toString

public String toString()

Overrides:
toString in class Object