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) { ... } });
AbstractLifeCycle.AbstractLifeCycleListener
Container.InheritedListener, Container.Listener
LifeCycle.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(HttpClientTransport transport,
SslContextFactory sslContextFactory) |
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 Request |
copyRequest(HttpRequest 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 |
FORM(String uri,
Fields fields)
Performs a POST request to the specified URI with the given form parameters.
|
ContentResponse |
FORM(URI uri,
Fields fields)
Performs a POST request to the specified URI with the given form parameters.
|
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.Factory s that can be modified before
performing requests. |
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.Listener s that can be modified before
performing requests. |
int |
getResponseBufferSize() |
Scheduler |
getScheduler() |
SslContextFactory |
getSslContextFactory() |
HttpClientTransport |
getTransport() |
HttpField |
getUserAgentField() |
protected boolean |
isDefaultPort(String scheme,
int port) |
boolean |
isDispatchIO() |
boolean |
isFollowRedirects() |
boolean |
isRemoveIdleDestinations() |
boolean |
isStrictEventOrdering() |
boolean |
isTCPNoDelay() |
protected void |
newConnection(HttpDestination destination,
Promise<Connection> promise) |
protected HttpRequest |
newHttpRequest(HttpConversation conversation,
URI uri) |
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 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 boolean |
removeDestination(HttpDestination destination) |
protected void |
send(HttpRequest 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 |
setRemoveIdleDestinations(boolean removeIdleDestinations)
Whether destinations that have no connections (nor active nor idle) should be removed.
|
void |
setRequestBufferSize(int requestBufferSize) |
void |
setResponseBufferSize(int responseBufferSize) |
void |
setScheduler(Scheduler scheduler) |
void |
setStrictEventOrdering(boolean strictEventOrdering)
Whether request/response events must be strictly ordered with respect to connection usage.
|
void |
setTCPNoDelay(boolean tcpNoDelay) |
void |
setUserAgentField(HttpField agent) |
addBean, addBean, addBean, addEventListener, addManaged, contains, destroy, dump, dump, dump, dump, dumpBeans, dumpObject, dumpStdErr, dumpThis, getBean, getBeans, getBeans, isManaged, manage, removeBean, removeBeans, removeEventListener, setBeans, setStopTimeout, start, stop, unmanage, updateBean, updateBeans
addLifeCycleListener, getState, getState, getStopTimeout, isFailed, isRunning, isStarted, isStarting, isStopped, isStopping, removeLifeCycleListener, start, stop
public 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 HttpClient(HttpClientTransport transport, SslContextFactory sslContextFactory)
public HttpClientTransport getTransport()
public SslContextFactory getSslContextFactory()
SslContextFactory
that manages TLS encryptionHttpClient(SslContextFactory)
protected void doStart() throws Exception
ContainerLifeCycle
doStart
in class ContainerLifeCycle
Exception
protected void doStop() throws Exception
ContainerLifeCycle
doStop
in class ContainerLifeCycle
Exception
public List<Request.Listener> getRequestListeners()
Request.Listener
s 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.Factory
s 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 requestInterruptedException
ExecutionException
TimeoutException
GET(URI)
public ContentResponse GET(URI uri) throws InterruptedException, ExecutionException, TimeoutException
uri
- the URI to GETContentResponse
for the requestInterruptedException
ExecutionException
TimeoutException
newRequest(URI)
public ContentResponse FORM(String uri, Fields fields) throws InterruptedException, ExecutionException, TimeoutException
uri
- the URI to POSTfields
- the fields composing the form name/value pairsContentResponse
for the requestInterruptedException
ExecutionException
TimeoutException
public ContentResponse FORM(URI uri, Fields fields) throws InterruptedException, ExecutionException, TimeoutException
uri
- the URI to POSTfields
- the fields composing the form name/value pairsContentResponse
for the requestInterruptedException
ExecutionException
TimeoutException
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 requestprotected Request copyRequest(HttpRequest oldRequest, URI newURI)
protected HttpRequest newHttpRequest(HttpConversation conversation, URI uri)
public Destination getDestination(String scheme, String host, int port)
Destination
for the given scheme, host and port.
Applications may use Destination
s to create Connection
s
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)
protected boolean removeDestination(HttpDestination destination)
public List<Destination> getDestinations()
HttpClient
.protected void send(HttpRequest request, List<Response.ResponseListener> listeners)
protected void newConnection(HttpDestination destination, Promise<Connection> promise)
protected List<ProtocolHandler> getProtocolHandlers()
protected ProtocolHandler findProtocolHandler(Request request, Response response)
public ByteBufferPool getByteBufferPool()
ByteBufferPool
of this HttpClient
public void setByteBufferPool(ByteBufferPool byteBufferPool)
byteBufferPool
- the ByteBufferPool
of this HttpClient
public long getConnectTimeout()
public void setConnectTimeout(long connectTimeout)
connectTimeout
- the max time, in milliseconds, 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, in milliseconds, 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()
HttpClient
public void setUserAgentField(HttpField agent)
agent
- the "User-Agent" HTTP header string of this HttpClient
public 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 HttpClient
public void setExecutor(Executor executor)
executor
- the Executor
of this HttpClient
public Scheduler getScheduler()
Scheduler
of this HttpClient
public void setScheduler(Scheduler scheduler)
scheduler
- the Scheduler
of this HttpClient
public int getMaxConnectionsPerDestination()
HttpClient
opens to Destination
spublic 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 Destination
spublic 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 boolean isStrictEventOrdering()
setStrictEventOrdering(boolean)
public void setStrictEventOrdering(boolean strictEventOrdering)
Response.CompleteListener
s
(but after the "success" event).
When a request/response exchange is completing, the destination may have another request
queued to be sent to the server.
If the connection for that destination is reused for the second request before the "complete"
event of the first exchange, it may happen that the "begin" event of the second request
happens before the "complete" event of the first exchange.
Enforcing strict ordering of events so that a "begin" event of a request can never happen
before the "complete" event of the previous exchange comes with the cost of increased
connection usage.
In case of HTTP redirects and strict event ordering, for example, the redirect request will
be forced to open a new connection because it is typically sent from the complete listener
when the connection cannot yet be reused.
When strict event ordering is not enforced, the redirect request will reuse the already
open connection making the system more efficient.
The default value for this property is false
.strictEventOrdering
- whether request/response events must be strictly orderedpublic boolean isRemoveIdleDestinations()
setRemoveIdleDestinations(boolean)
public void setRemoveIdleDestinations(boolean removeIdleDestinations)
removeIdleDestinations
- whether destinations that have no connections should be removedConnectionPool
public ProxyConfiguration getProxyConfiguration()
protected HttpField getAcceptEncodingField()
protected int normalizePort(String scheme, int port)
protected boolean isDefaultPort(String scheme, int port)
public void dump(Appendable out, String indent) throws IOException
dump
in interface Dumpable
dump
in class ContainerLifeCycle
IOException
Copyright © 1995-2015 Webtide. All Rights Reserved.