Class HttpClient

java.lang.Object
com.mastfrog.netty.http.client.HttpClient

public final class HttpClient extends Object
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 call send() 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 the StateType 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 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 compression
      maxChunkSize - Max buffer size for chunked encoding
      threads - Number of threads to dedicate to network I/O
      maxInitialLineLength - Maximum length the initial line (method + url) will have
      maxHeadersSize - Maximum buffer size for HTTP headers
      followRedirects - If true, client will transparently follow redirects
      userAgent - The user agent string - may be null
      interceptors - A list of interceptors which can decorate all http requests created by this client. May be null.
      settings - Netty channel options for
      send100continue - If true, requests with payloads will have the Expect: 100-CONTINUE header set
      cookies - 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 created
      maxRedirects - 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

      public static HttpClientBuilder builder()
      Create a builder to configure connecting
      Returns:
      A builder
    • request

      public HttpRequestBuilder request(Method method)
    • get

      public HttpRequestBuilder get()
      Build an HTTP GET request
      Returns:
      a request builder
    • head

      public HttpRequestBuilder head()
      Build an HTTP HEAD request Spi
      Returns:
      a request builder
    • put

      public HttpRequestBuilder put()
      Build an HTTP PUT request
      Returns:
      a request builder
    • post

      public HttpRequestBuilder post()
      Build an HTTP POST request
      Returns:
      a request builder
    • delete

      public HttpRequestBuilder delete()
      Build an HTTP DELETE request
      Returns:
      a request builder
    • options

      public HttpRequestBuilder options()
      Build an HTTP OPTIONS request
      Returns:
      a request builder
    • shutdown

      public void shutdown()
      Shut down any running connections
    • addActivityMonitor

      public void addActivityMonitor(ActivityMonitor monitor)
    • removeActivityMonitor

      public void removeActivityMonitor(ActivityMonitor monitor)