Package com.mastfrog.netty.http.client
Class HttpClient
java.lang.Object
com.mastfrog.netty.http.client.HttpClient
A simple asynchronous HTTP client with an emphasis on ease of use and a
simple callback-based API to discourage blocking calls - use
HttpClient.builder() to configure and create an instance. Use
HttpRequestBuilder
instances obtained from the get/put/post/options methods to construct and
send requests.
By default, handles http or https and allows for untrusted ssl certs.
HTTP compression is supported.
Usage
Build a request, then callsend() on the builder to trigger
sending the request. When building the request, you can add handlers for
different event types. So, for example, if you're only interested in the
content, you can receive that as a string, a byte array or decoded JSON
simply based on the type of callback you provide.
<
pre>
HttpClient client = HttpClient.builder().useCompression().build();
ResponseHandler<String> receiver = new
ResponseHandler<>(String.class) { public void receive(String body) { //
do something } } HttpRequestBuilder bldr =
client.get().setURL(URL.parse("http://mail-vm.timboudreau.org/blog/api-list"));
ResponseFuture h = bldr.execute(receiver);
When the request is completed, the callback will be invoked. There are
three receive methods you can override which give you varying
levels of detail - the signature of the receive() method could
also be:
public void receive(HttpResponseStatus status, String body) {
or it could be
public void receive(HttpResponseStatus status, HttpHeaders h, String body) {
Now say we want to set some headers - for example, to get a NOT MODIFIED
response if the server sees the data is older than the If-Modified-Since
header (in this case, three minutes ago - this uses Joda Time's DateTime and
Duration classes):
bldr.add(Headers.IF_MODIFIED_SINCE, DateTime.now().minus(Duration.standardMinutes(3)));
States / Events
There are a number of states possible - see theStateType
enum for all of them. Some can be called multiple times - for example, you
can examine every chunk of a chunked response by adding a listener for
State.ContentReceived:
<
pre>
bldr.on(State.ContentReceived.class, new Receiver<ByteBuf>(){ public
void receive(ByteBuf buf) { ... } })
If you just want a Netty HttpResponse or
FullHttpResponse just ask for a
State.HeadersReceived or a
State.FullContentReceived instead.
To catch the details, use the
StateType enum instead - a number
of events don't have public classes because there is no data to pass with
them. So, to detect, say, when the channel for a request is closed, use
StateType.Closed- Author:
- Tim Boudreau
-
Constructor Summary
ConstructorsConstructorDescriptionHttpClient(boolean compress, int maxChunkSize, int threads, int maxInitialLineLength, int maxHeadersSize, boolean followRedirects, CharSequence userAgent, List<RequestInterceptor> interceptors, Iterable<HttpClientBuilder.ChannelOptionSetting<?>> settings, boolean send100continue, CookieStore cookies, Duration timeout, io.netty.handler.ssl.SslContext sslContext, io.netty.resolver.AddressResolverGroup<?> resolver, io.netty.channel.nio.NioEventLoopGroup threadPool, int maxRedirects, NettyContentMarshallers marshallers, com.fasterxml.jackson.databind.ObjectMapper mapper) Create a new HTTP client; prefer HttpClient.builder() where possible, as that is much simpler.HttpClientBuilder will remain backward compatible; this constructor may be changed if new parameters are needed (all state of an HTTP client is immutable and must be passed to the constructor). -
Method Summary
Modifier and TypeMethodDescriptionvoidaddActivityMonitor(ActivityMonitor monitor) static HttpClientBuilderbuilder()Create a builder to configure connectingdelete()Build an HTTP DELETE requestget()Build an HTTP GET requesthead()Build an HTTP HEAD request Spioptions()Build an HTTP OPTIONS requestpost()Build an HTTP POST requestput()Build an HTTP PUT requestvoidremoveActivityMonitor(ActivityMonitor monitor) voidshutdown()Shut down any running connections
-
Constructor Details
-
HttpClient
public HttpClient() -
HttpClient
public HttpClient(boolean compress, int maxChunkSize, int threads, int maxInitialLineLength, int maxHeadersSize, boolean followRedirects, CharSequence userAgent, List<RequestInterceptor> interceptors, Iterable<HttpClientBuilder.ChannelOptionSetting<?>> settings, boolean send100continue, CookieStore cookies, Duration timeout, io.netty.handler.ssl.SslContext sslContext, io.netty.resolver.AddressResolverGroup<?> resolver, io.netty.channel.nio.NioEventLoopGroup threadPool, int maxRedirects, NettyContentMarshallers marshallers, com.fasterxml.jackson.databind.ObjectMapper mapper) Create a new HTTP client; prefer HttpClient.builder() where possible, as that is much simpler.HttpClientBuilder will remain backward compatible; this constructor may be changed if new parameters are needed (all state of an HTTP client is immutable and must be passed to the constructor).- Parameters:
compress- Enable http compressionmaxChunkSize- Max buffer size for chunked encodingthreads- Number of threads to dedicate to network I/OmaxInitialLineLength- Maximum length the initial line (method + url) will havemaxHeadersSize- Maximum buffer size for HTTP headersfollowRedirects- If true, client will transparently follow redirectsuserAgent- The user agent string - may be nullinterceptors- A list of interceptors which can decorate all http requests created by this client. May be null.settings- Netty channel options forsend100continue- If true, requests with payloads will have theExpect: 100-CONTINUEheader setcookies- A place to store http cookies, which will be re-sent where appropriate; may be null.timeout- Maximum time a connection will be open; may be null to keep open indefinitely.sslContext- Ssl context for secure connections. May be null.resolver- An alternate DNS resolver (may be null).threadPool- The thread pool to use - if null, a private one will be createdmaxRedirects- The maximum number of redirects that can be encountered before the client considers itself in a redirect loop and cancels the request (sending a cancelled event) If -1, the default of 15 will be used.managers- Trust managers for secure connections. May be empty for default trust manager.
-
-
Method Details
-
builder
Create a builder to configure connecting- Returns:
- A builder
-
request
-
get
Build an HTTP GET request- Returns:
- a request builder
-
head
Build an HTTP HEAD request Spi- Returns:
- a request builder
-
put
Build an HTTP PUT request- Returns:
- a request builder
-
post
Build an HTTP POST request- Returns:
- a request builder
-
delete
Build an HTTP DELETE request- Returns:
- a request builder
-
options
Build an HTTP OPTIONS request- Returns:
- a request builder
-
shutdown
public void shutdown()Shut down any running connections -
addActivityMonitor
-
removeActivityMonitor
-