public class HttpClient extends ContainerLifeCycle
HttpClient provides an efficient, asynchronous, non-blocking implementation
to perform HTTP requests to a server through a simple API that offers also blocking semantic.
HttpClient provides easy-to-use methods such as GET(String) that allow to perform HTTP
requests in a one-liner, but also gives the ability to fine tune the configuration of requests via
newRequest(URI).
HttpClient acts as a central configuration point for network parameters (such as idle timeouts)
and HTTP parameters (such as whether to follow redirects).
HttpClient transparently pools connections to servers, but allows direct control of connections
for cases where this is needed.
HttpClient also acts as a central configuration point for cookies, via getCookieStore().
Typical usage:
HttpClient httpClient = new HttpClient();
httpClient.start();
// One liner:
httpClient.GET("http://localhost:8080/").get().status();
// Building a request with a timeout
Response response = httpClient.newRequest("http://localhost:8080").send().get(5, TimeUnit.SECONDS);
int status = response.status();
// Asynchronously
httpClient.newRequest("http://localhost:8080").send(new Response.CompleteListener()
{
@Override
public void onComplete(Result result)
{
...
}
});
| Modifier and Type | Class and Description |
|---|---|
protected class |
HttpClient.ClientSelectorManager |
AbstractLifeCycle.AbstractLifeCycleListenerContainer.InheritedListener, Container.ListenerLifeCycle.Listener| Constructor and Description |
|---|
HttpClient()
Creates a
HttpClient instance that can perform requests to non-TLS destinations only
(that is, requests with the "http" scheme only, and not "https"). |
HttpClient(SslContextFactory sslContextFactory)
Creates a
HttpClient instance that can perform requests to non-TLS and TLS destinations
(that is, both requests with the "http" scheme and with the "https" scheme). |
| Modifier and Type | Method and Description |
|---|---|
protected String |
address(String scheme,
String host,
int port) |
protected void |
configure(SocketChannel channel) |
protected Request |
copyRequest(Request oldRequest,
URI newURI) |
protected HttpDestination |
destinationFor(String scheme,
String host,
int port) |
protected void |
doStart()
Starts the managed lifecycle beans in the order they were added.
|
protected void |
doStop()
Stops the managed lifecycle beans in the reverse order they were added.
|
void |
dump(Appendable out,
String indent) |
protected ProtocolHandler |
findProtocolHandler(Request request,
Response response) |
ContentResponse |
GET(String uri)
Performs a GET request to the specified URI.
|
ContentResponse |
GET(URI uri)
Performs a GET request to the specified URI.
|
protected HttpField |
getAcceptEncodingField() |
long |
getAddressResolutionTimeout() |
AuthenticationStore |
getAuthenticationStore() |
SocketAddress |
getBindAddress() |
ByteBufferPool |
getByteBufferPool() |
long |
getConnectTimeout() |
Set<ContentDecoder.Factory> |
getContentDecoderFactories()
Returns a non thread-safe set of
ContentDecoder.Factorys that can be modified before
performing requests. |
protected HttpConversation |
getConversation(long id,
boolean create) |
CookieStore |
getCookieStore() |
Destination |
getDestination(String scheme,
String host,
int port)
Returns a
Destination for the given scheme, host and port. |
List<Destination> |
getDestinations() |
Executor |
getExecutor() |
long |
getIdleTimeout() |
int |
getMaxConnectionsPerDestination() |
int |
getMaxRedirects() |
int |
getMaxRequestsQueuedPerDestination() |
protected List<ProtocolHandler> |
getProtocolHandlers() |
ProxyConfiguration |
getProxyConfiguration() |
int |
getRequestBufferSize() |
List<Request.Listener> |
getRequestListeners()
Returns a non thread-safe list of
Request.Listeners that can be modified before
performing requests. |
int |
getResponseBufferSize() |
Scheduler |
getScheduler() |
protected SelectorManager |
getSelectorManager() |
SslContextFactory |
getSslContextFactory() |
HttpField |
getUserAgentField() |
protected boolean |
isDefaultPort(String scheme,
int port) |
boolean |
isDispatchIO() |
boolean |
isFollowRedirects() |
boolean |
isTCPNoDelay() |
protected void |
newConnection(HttpDestination destination,
Promise<Connection> promise) |
protected HttpConnection |
newHttpConnection(HttpClient httpClient,
EndPoint endPoint,
HttpDestination destination) |
Request |
newRequest(String uri)
Creates a new request with the specified URI.
|
Request |
newRequest(String host,
int port)
Creates a new request with the "http" scheme and the specified host and port
|
Request |
newRequest(URI uri)
Creates a new request with the specified URI.
|
protected SelectorManager |
newSelectorManager() |
protected SslConnection |
newSslConnection(HttpClient httpClient,
EndPoint endPoint,
SSLEngine engine) |
protected String |
normalizeHost(String host) |
protected int |
normalizePort(String scheme,
int port) |
Request |
POST(String uri)
Creates a POST request to the specified URI.
|
Request |
POST(URI uri)
Creates a POST request to the specified URI.
|
protected void |
removeConversation(HttpConversation conversation) |
protected void |
send(Request request,
List<Response.ResponseListener> listeners) |
void |
setAddressResolutionTimeout(long addressResolutionTimeout) |
void |
setBindAddress(SocketAddress bindAddress) |
void |
setByteBufferPool(ByteBufferPool byteBufferPool) |
void |
setConnectTimeout(long connectTimeout) |
void |
setCookieStore(CookieStore cookieStore) |
void |
setDispatchIO(boolean dispatchIO)
Whether to dispatch I/O operations from the selector thread to a different thread.
|
void |
setExecutor(Executor executor) |
void |
setFollowRedirects(boolean follow) |
void |
setIdleTimeout(long idleTimeout) |
void |
setMaxConnectionsPerDestination(int maxConnectionsPerDestination)
Sets the max number of connections to open to each destinations.
|
void |
setMaxRedirects(int maxRedirects) |
void |
setMaxRequestsQueuedPerDestination(int maxRequestsQueuedPerDestination)
Sets the max number of requests that may be queued to a destination.
|
void |
setProxyConfiguration(ProxyConfiguration proxyConfig) |
void |
setRequestBufferSize(int requestBufferSize) |
void |
setResponseBufferSize(int responseBufferSize) |
void |
setScheduler(Scheduler scheduler) |
void |
setTCPNoDelay(boolean tcpNoDelay) |
void |
setUserAgentField(HttpField agent) |
addBean, addBean, addBean, contains, destroy, dump, dump, dump, dump, dumpBeans, dumpObject, dumpStdErr, dumpThis, getBean, getBeans, getBeans, isManaged, manage, removeBean, removeBeans, setBeans, setStopTimeout, start, unmanage, updateBean, updateBeansaddLifeCycleListener, getState, getState, getStopTimeout, isFailed, isRunning, isStarted, isStarting, isStopped, isStopping, removeLifeCycleListener, start, stoppublic HttpClient()
HttpClient instance that can perform requests to non-TLS destinations only
(that is, requests with the "http" scheme only, and not "https").public HttpClient(SslContextFactory sslContextFactory)
HttpClient instance that can perform requests to non-TLS and TLS destinations
(that is, both requests with the "http" scheme and with the "https" scheme).sslContextFactory - the SslContextFactory that manages TLS encryptiongetSslContextFactory()public SslContextFactory getSslContextFactory()
SslContextFactory that manages TLS encryptionHttpClient(SslContextFactory)protected void doStart()
throws Exception
ContainerLifeCycledoStart in class ContainerLifeCycleExceptionprotected SelectorManager newSelectorManager()
protected void doStop()
throws Exception
ContainerLifeCycledoStop in class ContainerLifeCycleExceptionpublic List<Request.Listener> getRequestListeners()
Request.Listeners that can be modified before
performing requests.Request.Listener that can be used to add and remove listenerspublic CookieStore getCookieStore()
public void setCookieStore(CookieStore cookieStore)
cookieStore - the cookie store associated with this instancepublic AuthenticationStore getAuthenticationStore()
public Set<ContentDecoder.Factory> getContentDecoderFactories()
ContentDecoder.Factorys that can be modified before
performing requests.ContentDecoder.Factory that can be used to add and remove content decoder factoriespublic ContentResponse GET(String uri) throws InterruptedException, ExecutionException, TimeoutException
uri - the URI to GETContentResponse for the requestInterruptedExceptionExecutionExceptionTimeoutExceptionGET(URI)public ContentResponse GET(URI uri) throws InterruptedException, ExecutionException, TimeoutException
uri - the URI to GETContentResponse for the requestInterruptedExceptionExecutionExceptionTimeoutExceptionnewRequest(URI)public Request POST(String uri)
uri - the URI to POST toPOST(URI)public Request POST(URI uri)
uri - the URI to POST topublic Request newRequest(String host, int port)
host - the request hostport - the request portpublic Request newRequest(String uri)
uri - the URI to requestpublic Request newRequest(URI uri)
uri - the URI to requestpublic Destination getDestination(String scheme, String host, int port)
Destination for the given scheme, host and port.
Applications may use Destinations to create Connections
that will be outside HttpClient's pooling mechanism, to explicitly
control the connection lifecycle (in particular their termination with
Connection.close()).scheme - the destination schemehost - the destination hostport - the destination portgetDestinations()protected HttpDestination destinationFor(String scheme, String host, int port)
public List<Destination> getDestinations()
HttpClient.protected void send(Request request, List<Response.ResponseListener> listeners)
protected void newConnection(HttpDestination destination, Promise<Connection> promise)
protected void configure(SocketChannel channel) throws SocketException
SocketExceptionprotected HttpConversation getConversation(long id, boolean create)
protected void removeConversation(HttpConversation conversation)
protected List<ProtocolHandler> getProtocolHandlers()
protected ProtocolHandler findProtocolHandler(Request request, Response response)
public ByteBufferPool getByteBufferPool()
ByteBufferPool of this HttpClientpublic void setByteBufferPool(ByteBufferPool byteBufferPool)
byteBufferPool - the ByteBufferPool of this HttpClientpublic long getConnectTimeout()
public void setConnectTimeout(long connectTimeout)
connectTimeout - the max time a connection can take to connect to destinationsSocket.connect(SocketAddress, int)public long getAddressResolutionTimeout()
public void setAddressResolutionTimeout(long addressResolutionTimeout)
addressResolutionTimeout - the timeout, in milliseconds, for the DNS resolution of host addressespublic long getIdleTimeout()
public void setIdleTimeout(long idleTimeout)
idleTimeout - the max time a connection can be idle (that is, without traffic of bytes in either direction)public SocketAddress getBindAddress()
setBindAddress(SocketAddress)public void setBindAddress(SocketAddress bindAddress)
bindAddress - the address to bind socket channels togetBindAddress(),
SocketChannel.bind(SocketAddress)public HttpField getUserAgentField()
HttpClientpublic void setUserAgentField(HttpField agent)
agent - the "User-Agent" HTTP header string of this HttpClientpublic boolean isFollowRedirects()
HttpClient follows HTTP redirectsRequest.isFollowRedirects()public void setFollowRedirects(boolean follow)
follow - whether this HttpClient follows HTTP redirectssetMaxRedirects(int)public Executor getExecutor()
Executor of this HttpClientpublic void setExecutor(Executor executor)
executor - the Executor of this HttpClientpublic Scheduler getScheduler()
Scheduler of this HttpClientpublic void setScheduler(Scheduler scheduler)
scheduler - the Scheduler of this HttpClientprotected SelectorManager getSelectorManager()
public int getMaxConnectionsPerDestination()
HttpClient opens to Destinationspublic void setMaxConnectionsPerDestination(int maxConnectionsPerDestination)
HttpClient is used for load testing, it is common to have only one destination
(the server to load test), and it is recommended to set this value to a high value (at least as
much as the threads present in the executor).maxConnectionsPerDestination - the max number of connections that this HttpClient opens to Destinationspublic int getMaxRequestsQueuedPerDestination()
Destination.public void setMaxRequestsQueuedPerDestination(int maxRequestsQueuedPerDestination)
HttpClient performs a high rate of requests to a destination,
and all the connections managed by that destination are busy with other requests,
then new requests will be queued up in the destination.
This parameter controls how many requests can be queued before starting to reject them.
If this HttpClient is used for load testing, it is common to have this parameter
set to a high value, although this may impact latency (requests sit in the queue for a long
time before being sent).maxRequestsQueuedPerDestination - the max number of requests that may be queued to a Destination.public int getRequestBufferSize()
public void setRequestBufferSize(int requestBufferSize)
requestBufferSize - the size of the buffer used to write requestspublic int getResponseBufferSize()
public void setResponseBufferSize(int responseBufferSize)
responseBufferSize - the size of the buffer used to read responsespublic int getMaxRedirects()
setMaxRedirects(int)public void setMaxRedirects(int maxRedirects)
maxRedirects - the max number of HTTP redirects that are followedsetFollowRedirects(boolean)public boolean isTCPNoDelay()
public void setTCPNoDelay(boolean tcpNoDelay)
tcpNoDelay - whether TCP_NODELAY is enabledSocket.setTcpNoDelay(boolean)public boolean isDispatchIO()
setDispatchIO(boolean)public void setDispatchIO(boolean dispatchIO)
dispatchIO
should be set to true.
If application callbacks are known to be quick and never block on I/O, then parameter dispatchIO
may be set to false.dispatchIO - true to dispatch I/O operations in a different thread,
false to execute them in the selector threadpublic ProxyConfiguration getProxyConfiguration()
public void setProxyConfiguration(ProxyConfiguration proxyConfig)
proxyConfig - the forward proxy configurationprotected HttpField getAcceptEncodingField()
protected int normalizePort(String scheme, int port)
protected boolean isDefaultPort(String scheme, int port)
protected HttpConnection newHttpConnection(HttpClient httpClient, EndPoint endPoint, HttpDestination destination)
protected SslConnection newSslConnection(HttpClient httpClient, EndPoint endPoint, SSLEngine engine)
public void dump(Appendable out, String indent) throws IOException
dump in interface Dumpabledump in class ContainerLifeCycleIOExceptionCopyright © 1995-2015 Mort Bay Consulting. All Rights Reserved.