== Writing HTTP servers and clients

Vert.x allows you to easily write non blocking HTTP clients and servers.

Vert.x supports the HTTP/1.0, HTTP/1.1 and HTTP/2 protocols.

The base API for HTTP is the same for HTTP/1.x and HTTP/2, specific API features are available for dealing with the
HTTP/2 protocol.

=== Creating an HTTP Server

The simplest way to create an HTTP server, using all default options is as follows:

[source,java]
----
HttpServer server = vertx.createHttpServer();
----

=== Configuring an HTTP server

If you don't want the default, a server can be configured by passing in a `link:../../apidocs/io/vertx/core/http/HttpServerOptions.html[HttpServerOptions]`
instance when creating it:

[source,java]
----
HttpServerOptions options = new HttpServerOptions().setMaxWebSocketFrameSize(1000000);

HttpServer server = vertx.createHttpServer(options);
----

=== Configuring an HTTP/2 server

Vert.x supports HTTP/2 over TLS `h2` and over TCP `h2c`.

- `h2` identifies the HTTP/2 protocol when used over TLS negotiated by https://en.wikipedia.org/wiki/Application-Layer_Protocol_Negotiation[Application-Layer Protocol Negotiation] (ALPN)
- `h2c` identifies the HTTP/2 protocol when using in clear text over TCP, such connections are established either with
an HTTP/1.1 upgraded request or directly

To handle `h2` requests, TLS must be enabled along with `link:../../apidocs/io/vertx/core/http/HttpServerOptions.html#setUseAlpn-boolean-[setUseAlpn]`:

[source,java]
----
HttpServerOptions options = new HttpServerOptions()
    .setUseAlpn(true)
    .setSsl(true)
    .setKeyCertOptions(new JksOptions().setPath("/path/to/my/keystore"));

HttpServer server = vertx.createHttpServer(options);
----

ALPN is a TLS extension that negotiates the protocol before the client and the server start to exchange data.

Clients that don't support ALPN will still be able to do a _classic_ SSL handshake.

ALPN will usually agree on the `h2` protocol, although `http/1.1` can be used if the server or the client decides
so.

To handle `h2c` requests, TLS must be disabled, the server will upgrade to HTTP/2 any request HTTP/1.1 that wants to
upgrade to HTTP/2. It will also accept a direct `h2c` connection beginning with the `PRI * HTTP/2.0\r\nSM\r\n` preface.

WARNING: most browsers won't support `h2c`, so for serving web sites you should use `h2` and not `h2c`.

When a server accepts an HTTP/2 connection, it sends to the client its `link:../../apidocs/io/vertx/core/http/HttpServerOptions.html#getInitialSettings--[initial settings]`.
The settings define how the client can use the connection, the default initial settings for a server are:

- `link:../../apidocs/io/vertx/core/http/Http2Settings.html#getMaxConcurrentStreams--[getMaxConcurrentStreams]`: `100` as recommended by the HTTP/2 RFC
- the default HTTP/2 settings values for the others

=== Configuring server supported HTTP versions

Default supported HTTP versions depends on the server configuration.

- when TLS is disabled
  - HTTP/1.1, HTTP/1.0
  - HTTP/2 when `link:../../apidocs/io/vertx/core/http/HttpServerOptions.html#isHttp2ClearTextEnabled--[isHttp2ClearTextEnabled]` is `true`
- when TLS is enabled and ALPN disabled
  - HTTP/1.1 and HTTP/1.0
- when TLS is enabled and ALPN enabled
  - the protocols defined by `link:../../apidocs/io/vertx/core/http/HttpServerOptions.html#getAlpnVersions--[getAlpnVersions]`: by default HTTP/1.1 and HTTP/2

If you want to disable HTTP/2 on the server
- when TLS is disabled, set `link:../../apidocs/io/vertx/core/http/HttpServerOptions.html#setHttp2ClearTextEnabled-boolean-[setHttp2ClearTextEnabled]` to `false`
- when TLS is enabled
  - set (`link:../../apidocs/io/vertx/core/net/TCPSSLOptions.html#isUseAlpn--[isUseAlpn]`) to `false`
  - _or_ remove HTTP/2 from the `link:../../apidocs/io/vertx/core/http/HttpServerOptions.html#getAlpnVersions--[getAlpnVersions]` list

=== Logging network server activity

For debugging purposes, network activity can be logged.

[source,java]
----
HttpServerOptions options = new HttpServerOptions().setLogActivity(true);

HttpServer server = vertx.createHttpServer(options);
----

See the chapter on <<logging_network_activity, logging network activity>> for a detailed explanation.

=== Start the Server Listening

To tell the server to listen for incoming requests you use one of the `link:../../apidocs/io/vertx/core/http/HttpServer.html#listen--[listen]`
alternatives.

To tell the server to listen at the host and port as specified in the options:

[source,java]
----
HttpServer server = vertx.createHttpServer();
server.listen();
----

Or to specify the host and port in the call to listen, ignoring what is configured in the options:

[source,java]
----
HttpServer server = vertx.createHttpServer();
server.listen(8080, "myhost.com");
----

The default host is `0.0.0.0` which means 'listen on all available addresses' and the default port is `80`.

The actual bind is asynchronous so the server might not actually be listening until some time *after* the call to
listen has returned.

If you want to be notified when the server is actually listening you can provide a handler to the `listen` call.
For example:

[source,java]
----
HttpServer server = vertx.createHttpServer();
server
  .listen(8080, "myhost.com")
  .onComplete(res -> {
    if (res.succeeded()) {
      System.out.println("Server is now listening!");
    } else {
      System.out.println("Failed to bind!");
    }
  });
----

=== Listening to Unix domain sockets

When running on JDK 16+, or using a <<_native_transports,native transport>>, a server can listen to Unix domain sockets:

[source,java]
----
HttpServer httpServer = vertx.createHttpServer();

// Only available when running on JDK16+, or using a native transport
SocketAddress address = SocketAddress.domainSocketAddress("/var/tmp/myservice.sock");

httpServer
  .requestHandler(req -> {
    // Handle application
  })
  .listen(address)
  .onComplete(ar -> {
    if (ar.succeeded()) {
      // Bound to socket
    } else {
      // Handle failure
    }
  });
----

=== Getting notified of incoming requests

To be notified when a request arrives you need to set a `link:../../apidocs/io/vertx/core/http/HttpServer.html#requestHandler-io.vertx.core.Handler-[requestHandler]`:

[source,java]
----
HttpServer server = vertx.createHttpServer();
server.requestHandler(request -> {
  // Handle the request in here
});
----

=== Handling requests

When a request arrives, the request handler is called passing in an instance of `link:../../apidocs/io/vertx/core/http/HttpServerRequest.html[HttpServerRequest]`.
This object represents the server side HTTP request.

The handler is called when the headers of the request have been fully read.

If the request contains a body, that body will arrive at the server some time after the request handler has been called.

The server request object allows you to retrieve the `link:../../apidocs/io/vertx/core/http/HttpServerRequest.html#uri--[uri]`,
`link:../../apidocs/io/vertx/core/http/HttpServerRequest.html#path--[path]`, `link:../../apidocs/io/vertx/core/http/HttpServerRequest.html#params--[params]` and
`link:../../apidocs/io/vertx/core/http/HttpServerRequest.html#headers--[headers]`, amongst other things.

Each server request object is associated with one server response object. You use
`link:../../apidocs/io/vertx/core/http/HttpServerRequest.html#response--[response]` to get a reference to the `link:../../apidocs/io/vertx/core/http/HttpServerResponse.html[HttpServerResponse]`
object.

Here's a simple example of a server handling a request and replying with "hello world" to it.

[source,java]
----
vertx.createHttpServer().requestHandler(request -> {
  request.response().end("Hello world");
}).listen(8080);
----

==== Request version

The version of HTTP specified in the request can be retrieved with `link:../../apidocs/io/vertx/core/http/HttpServerRequest.html#version--[version]`

==== Request method

Use `link:../../apidocs/io/vertx/core/http/HttpServerRequest.html#method--[method]` to retrieve the HTTP method of the request.
(i.e. whether it's GET, POST, PUT, DELETE, HEAD, OPTIONS, etc).

==== Request URI

Use `link:../../apidocs/io/vertx/core/http/HttpServerRequest.html#uri--[uri]` to retrieve the URI of the request.

Note that this is the actual URI as passed in the HTTP request, and it's almost always a relative URI.

The URI is as defined in http://www.w3.org/Protocols/rfc2616/rfc2616-sec5.html[Section 5.1.2 of the HTTP specification - Request-URI]

==== Request path

Use `link:../../apidocs/io/vertx/core/http/HttpServerRequest.html#path--[path]` to return the path part of the URI

For example, if the request URI was `a/b/c/page.html?param1=abc&param2=xyz

Then the path would be `/a/b/c/page.html`

==== Request query

Use `link:../../apidocs/io/vertx/core/http/HttpServerRequest.html#query--[query]` to return the query part of the URI

For example, if the request URI was `a/b/c/page.html?param1=abc&param2=xyz`

Then the query would be  `param1=abc&param2=xyz`

==== Request headers

Use `link:../../apidocs/io/vertx/core/http/HttpServerRequest.html#headers--[headers]` to return the headers of the HTTP request.

This returns an instance of `link:../../apidocs/io/vertx/core/MultiMap.html[MultiMap]` - which is like a normal Map or Hash but allows multiple
values for the same key - this is because HTTP allows multiple header values with the same key.

It also has case-insensitive keys, that means you can do the following:

[source,java]
----
MultiMap headers = request.headers();

// Get the User-Agent:
System.out.println("User agent is " + headers.get("user-agent"));

// You can also do this and get the same result:
System.out.println("User agent is " + headers.get("User-Agent"));
----

==== Request authority

Use `link:../../apidocs/io/vertx/core/http/HttpServerRequest.html#authority--[authority]` to return the authority of the HTTP request.

For HTTP/1.x requests the `host` header is returned, for HTTP/1 requests the `:authority` pseudo header is returned.

==== Request parameters

Use `link:../../apidocs/io/vertx/core/http/HttpServerRequest.html#params--[params]` to return the parameters of the HTTP request.

Just like `link:../../apidocs/io/vertx/core/http/HttpServerRequest.html#headers--[headers]` this returns an instance of `link:../../apidocs/io/vertx/core/MultiMap.html[MultiMap]`
as there can be more than one parameter with the same name.

Request parameters are sent on the request URI, after the path. For example if the URI was `/page.html?param1=abc&param2=xyz`

Then the parameters would contain the following:

----
param1: 'abc'
param2: 'xyz
----

Note that these request parameters are retrieved from the URL of the request. If you have form attributes that
have been sent as part of the submission of an HTML form submitted in the body of a `multi-part/form-data` request
then they will not appear in the params here.

==== Remote address

The address of the sender of the request can be retrieved with `link:../../apidocs/io/vertx/core/http/HttpServerRequest.html#remoteAddress--[remoteAddress]`.

==== Absolute URI

The URI passed in an HTTP request is usually relative. If you wish to retrieve the absolute URI corresponding
to the request, you can get it with `link:../../apidocs/io/vertx/core/http/HttpServerRequest.html#absoluteURI--[absoluteURI]`

==== End handler

The `link:../../apidocs/io/vertx/core/http/HttpServerRequest.html#endHandler-io.vertx.core.Handler-[endHandler]` of the request is invoked when the entire request,
including any body has been fully read.

==== Reading Data from the Request Body

Often an HTTP request contains a body that we want to read. As previously mentioned the request handler is called
when just the headers of the request have arrived so the request object does not have a body at that point.

This is because the body may be very large (e.g. a file upload) and we don't generally want to buffer the entire
body in memory before handing it to you, as that could cause the server to exhaust available memory.

To receive the body, you can use the `link:../../apidocs/io/vertx/core/http/HttpServerRequest.html#handler-io.vertx.core.Handler-[handler]`  on the request,
this will get called every time a chunk of the request body arrives. Here's an example:

[source,java]
----
request.handler(buffer -> {
  System.out.println("I have received a chunk of the body of length " + buffer.length());
});
----

The object passed into the handler is a `link:../../apidocs/io/vertx/core/buffer/Buffer.html[Buffer]`, and the handler can be called
multiple times as data arrives from the network, depending on the size of the body.

In some cases (e.g. if the body is small) you will want to aggregate the entire body in memory, so you could do
the aggregation yourself as follows:

[source,java]
----
Buffer totalBuffer = Buffer.buffer();

request.handler(buffer -> {
  System.out.println("I have received a chunk of the body of length " + buffer.length());
  totalBuffer.appendBuffer(buffer);
});

request.endHandler(v -> {
  System.out.println("Full body received, length = " + totalBuffer.length());
});
----

This is such a common case, that Vert.x provides a `link:../../apidocs/io/vertx/core/http/HttpServerRequest.html#bodyHandler-io.vertx.core.Handler-[bodyHandler]` to do this
for you. The body handler is called once when all the body has been received:

[source,java]
----
request.bodyHandler(totalBuffer -> {
  System.out.println("Full body received, length = " + totalBuffer.length());
});
----

==== Streaming requests

The request object is a `link:../../apidocs/io/vertx/core/streams/ReadStream.html[ReadStream]` so you can pipe the request body to any
`link:../../apidocs/io/vertx/core/streams/WriteStream.html[WriteStream]` instance.

See the chapter on <<streams, streams>> for a detailed explanation.

==== Handling HTML forms

HTML forms can be submitted with either a content type of `application/x-www-form-urlencoded` or `multipart/form-data`.

For url encoded forms, the form attributes are encoded in the url, just like normal query parameters.

For multi-part forms they are encoded in the request body, and as such are not available until the entire body
has been read from the wire.

Multi-part forms can also contain file uploads.

If you want to retrieve the attributes of a multi-part form you should tell Vert.x that you expect to receive
such a form *before* any of the body is read by calling `link:../../apidocs/io/vertx/core/http/HttpServerRequest.html#setExpectMultipart-boolean-[setExpectMultipart]`
with `true`, and then you should retrieve the actual attributes using `link:../../apidocs/io/vertx/core/http/HttpServerRequest.html#formAttributes--[formAttributes]`
once the entire body has been read:

[source,java]
----
server.requestHandler(request -> {
  request.setExpectMultipart(true);
  request.endHandler(v -> {
    // The body has now been fully read, so retrieve the form attributes
    MultiMap formAttributes = request.formAttributes();
  });
});
----

Form attributes have a maximum size of `8192` bytes. When the client submits a form with an attribute
size greater than this value, the file upload triggers an exception on `HttpServerRequest` exception handler. You
can set a different maximum size with `link:../../apidocs/io/vertx/core/http/HttpServerOptions.html#setMaxFormAttributeSize-int-[setMaxFormAttributeSize]`.

==== Handling form file uploads

Vert.x can also handle file uploads which are encoded in a multi-part request body.

To receive file uploads you tell Vert.x to expect a multi-part form and set an
`link:../../apidocs/io/vertx/core/http/HttpServerRequest.html#uploadHandler-io.vertx.core.Handler-[uploadHandler]` on the request.

This handler will be called once for every
upload that arrives on the server.

The object passed into the handler is a `link:../../apidocs/io/vertx/core/http/HttpServerFileUpload.html[HttpServerFileUpload]` instance.

[source,java]
----
server.requestHandler(request -> {
  request.setExpectMultipart(true);
  request.uploadHandler(upload -> {
    System.out.println("Got a file upload " + upload.name());
  });
});
----

File uploads can be large we don't provide the entire upload in a single buffer as that might result in memory
exhaustion, instead, the upload data is received in chunks:

[source,java]
----
request.uploadHandler(upload -> {
  upload.handler(chunk -> {
    System.out.println("Received a chunk of the upload of length " + chunk.length());
  });
});
----

The upload object is a `link:../../apidocs/io/vertx/core/streams/ReadStream.html[ReadStream]` so you can pipe the request body to any
`link:../../apidocs/io/vertx/core/streams/WriteStream.html[WriteStream]` instance. See the chapter on <<streams, streams>> for a
detailed explanation.

If you just want to upload the file to disk somewhere you can use `link:../../apidocs/io/vertx/core/http/HttpServerFileUpload.html#streamToFileSystem-java.lang.String-[streamToFileSystem]`:

[source,java]
----
request.uploadHandler(upload -> {
  upload.streamToFileSystem("myuploads_directory/" + upload.filename());
});
----

WARNING: Make sure you check the filename in a production system to avoid malicious clients uploading files
to arbitrary places on your filesystem. See <<Security notes, security notes>> for more information.

==== Handling cookies

You use `link:../../apidocs/io/vertx/core/http/HttpServerRequest.html#getCookie-java.lang.String-[getCookie]` to retrieve
a cookie by name, or use `link:../../apidocs/io/vertx/core/http/HttpServerRequest.html#cookieMap--[cookieMap]` to retrieve all the cookies.

To remove a cookie, use `link:../../apidocs/io/vertx/core/http/HttpServerResponse.html#removeCookie-java.lang.String-[removeCookie]`.

To add a cookie use `link:../../apidocs/io/vertx/core/http/HttpServerResponse.html#addCookie-io.vertx.core.http.Cookie-[addCookie]`.

The set of cookies will be written back in the response automatically when the response headers are written so the
browser can store them.

Cookies are described by instances of `link:../../apidocs/io/vertx/core/http/Cookie.html[Cookie]`. This allows you to retrieve the name,
value, domain, path and other normal cookie properties.

Same Site Cookies let servers require that a cookie shouldn't be sent with cross-site (where Site is defined by the
registrable domain) requests, which provides some protection against cross-site request forgery attacks. This kind
of cookies are enabled using the setter: `link:../../apidocs/io/vertx/core/http/Cookie.html#setSameSite-io.vertx.core.http.CookieSameSite-[setSameSite]`.

Same site cookies can have one of 3 values:

* None - The browser will send cookies with both cross-site requests and same-site requests.
* Strict - The browser will only send cookies for same-site requests (requests originating from the site that set the
  cookie). If the request originated from a different URL than the URL of the current location, none of the cookies
  tagged with the Strict attribute will be included.
* Lax - Same-site cookies are withheld on cross-site subrequests, such as calls to load images or frames, but will be
  sent when a user navigates to the URL from an external site; for example, by following a link.

Here's an example of querying and adding cookies:

[source,java]
----
Cookie someCookie = request.getCookie("mycookie");
String cookieValue = someCookie.getValue();

// Do something with cookie...

// Add a cookie - this will get written back in the response automatically
request.response().addCookie(Cookie.cookie("othercookie", "somevalue"));
----

==== Handling compressed body

Vert.x can handle compressed body payloads which are encoded by the client with the _deflate_, _gzip_, _snappy_ or _brotli_
algorithms.

To enable decompression set `link:../../apidocs/io/vertx/core/http/HttpServerOptions.html#setDecompressionSupported-boolean-[setDecompressionSupported]` on the
options when creating the server.

Snappy is supported without external dependencies.

You need to have Brotli4j on the classpath to decompress Brotli, and Zstd-jni for Zstandard:

* Maven (in your `pom.xml`):

[source,xml]
----
<dependency>
  <groupId>com.aayushatharva.brotli4j</groupId>
  <artifactId>brotli4j</artifactId>
  <version>${brotli4j.version}</version>
</dependency>
<dependency>
  <groupId>com.github.luben</groupId>
  <artifactId>zstd-jni</artifactId>
  <version>${zstd-jini.version}</version>
</dependency>
----
* Gradle (in your `build.gradle` file):

[source,groovy]
----
dependencies {
  implementation 'com.aayushatharva.brotli4j:brotli4j:${brotli4j.version}'
  runtimeOnly 'com.aayushatharva.brotli4j:native-$system-and-arch:${brotli4j.version}'
  implementation 'com.github.luben:zstd-jni:${zstd-jini.version}'
}
----

When using Gradle, you need to add the runtime native library manually depending on your OS and architecture. See https://github.com/hyperxpro/Brotli4j#gradle[the Gradle section of Brotli4j] for more details.

By default, decompression is disabled.

==== Receiving custom HTTP/2 frames

HTTP/2 is a framed protocol with various frames for the HTTP request/response model. The protocol allows other kind
of frames to be sent and received.

To receive custom frames, you can use the `link:../../apidocs/io/vertx/core/http/HttpServerRequest.html#customFrameHandler-io.vertx.core.Handler-[customFrameHandler]` on the request,
this will get called every time a custom frame arrives. Here's an example:

[source,java]
----
request.customFrameHandler(frame -> {

  System.out.println("Received a frame type=" + frame.type() +
      " payload" + frame.payload().toString());
});
----

HTTP/2 frames are not subject to flow control - the frame handler will be called immediately when a
custom frame is received whether the request is paused or is not

=== Sending back responses

The server response object is an instance of `link:../../apidocs/io/vertx/core/http/HttpServerResponse.html[HttpServerResponse]` and is obtained from the
request with `link:../../apidocs/io/vertx/core/http/HttpServerRequest.html#response--[response]`.

You use the response object to write a response back to the HTTP client.

==== Setting status code and message

The default HTTP status code for a response is `200`, representing `OK`.

Use `link:../../apidocs/io/vertx/core/http/HttpServerResponse.html#setStatusCode-int-[setStatusCode]` to set a different code.

You can also specify a custom status message with `link:../../apidocs/io/vertx/core/http/HttpServerResponse.html#setStatusMessage-java.lang.String-[setStatusMessage]`.

If you don't specify a status message, the default one corresponding to the status code will be used.

NOTE: for HTTP/2 the status won't be present in the response since the protocol won't transmit the message
to the client

==== Writing HTTP responses

To write data to an HTTP response, you use one of the `link:../../apidocs/io/vertx/core/streams/WriteStream.html#write-java.lang.Object-[write]` operations.

These can be invoked multiple times before the response is ended. They can be invoked in a few ways:

With a single buffer:

[source,java]
----
HttpServerResponse response = request.response();
response.write(buffer);
----

With a string. In this case the string will encoded using UTF-8 and the result written to the wire.

[source,java]
----
HttpServerResponse response = request.response();
response.write("hello world!");
----

With a string and an encoding. In this case the string will encoded using the specified encoding and the
result written to the wire.

[source,java]
----
HttpServerResponse response = request.response();
response.write("hello world!", "UTF-16");
----

Writing to a response is asynchronous and always returns immediately after write has been queued.

If you are just writing a single string or buffer to the HTTP response you can write it and end the response in a
single call to the `link:../../apidocs/io/vertx/core/http/HttpServerResponse.html#end-java.lang.String-[end]`

The first call to write results in the response header being written to the response. Consequently, if you are
not using HTTP chunking then you must set the `Content-Length` header before writing to the response, since it will
be too late otherwise. If you are using HTTP chunking you do not have to worry.

==== Ending HTTP responses

Once you have finished with the HTTP response you should `link:../../apidocs/io/vertx/core/http/HttpServerResponse.html#end-java.lang.String-[end]` it.

This can be done in several ways:

With no arguments, the response is simply ended.

[source,java]
----
HttpServerResponse response = request.response();
response.write("hello world!");
response.end();
----

It can also be called with a string or buffer in the same way `write` is called. In this case it's just the same as
calling write with a string or buffer followed by calling end with no arguments. For example:

[source,java]
----
HttpServerResponse response = request.response();
response.end("hello world!");
----

==== Closing the underlying TCP connection

You can close the underlying TCP connection with `link:../../apidocs/io/vertx/core/http/HttpConnection.html#close--[close]`.

Non keep-alive connections will be automatically closed by Vert.x when the response is ended.

Keep-alive connections are not automatically closed by Vert.x by default. If you want keep-alive connections to be
closed after an idle time, then you configure `link:../../apidocs/io/vertx/core/http/HttpServerOptions.html#setIdleTimeout-int-[setIdleTimeout]`.

HTTP/2 connections send a `GOAWAY` frame before closing the response.

==== Setting response headers

HTTP response headers can be added to the response by adding them directly to the
`link:../../apidocs/io/vertx/core/http/HttpServerResponse.html#headers--[headers]`:

[source,java]
----
HttpServerResponse response = request.response();
MultiMap headers = response.headers();
headers.set("content-type", "text/html");
headers.set("other-header", "wibble");
----

Or you can use `link:../../apidocs/io/vertx/core/http/HttpServerResponse.html#putHeader-java.lang.String-java.lang.String-[putHeader]`

[source,java]
----
HttpServerResponse response = request.response();
response.putHeader("content-type", "text/html").putHeader("other-header", "wibble");
----

Headers must all be added before any parts of the response body are written.

==== Chunked HTTP responses and trailers

Vert.x supports http://en.wikipedia.org/wiki/Chunked_transfer_encoding[HTTP Chunked Transfer Encoding].

This allows the HTTP response body to be written in chunks, and is normally used when a large response body is
being streamed to a client and the total size is not known in advance.

You put the HTTP response into chunked mode as follows:

[source,java]
----
HttpServerResponse response = request.response();
response.setChunked(true);
----

Default is non-chunked. When in chunked mode, each call to one of the `link:../../apidocs/io/vertx/core/streams/WriteStream.html#write-java.lang.Object-[write]`
methods will result in a new HTTP chunk being written out.

When in chunked mode you can also write HTTP response trailers to the response. These are actually written in
the final chunk of the response.

NOTE: chunked response has no effect for an HTTP/2 stream

To add trailers to the response, add them directly to the `link:../../apidocs/io/vertx/core/http/HttpServerResponse.html#trailers--[trailers]`.

[source,java]
----
HttpServerResponse response = request.response();
response.setChunked(true);
MultiMap trailers = response.trailers();
trailers.set("X-wibble", "woobble").set("X-quux", "flooble");
----

Or use `link:../../apidocs/io/vertx/core/http/HttpServerResponse.html#putTrailer-java.lang.String-java.lang.String-[putTrailer]`.

[source,java]
----
HttpServerResponse response = request.response();
response.setChunked(true);
response.putTrailer("X-wibble", "woobble").putTrailer("X-quux", "flooble");
----

==== Serving files directly from disk or the classpath

If you were writing a web server, one way to serve a file from disk would be to open it as an `link:../../apidocs/io/vertx/core/file/AsyncFile.html[AsyncFile]`
and pipe it to the HTTP response.

Or you could load it in one go using `link:../../apidocs/io/vertx/core/file/FileSystem.html#readFile-java.lang.String-[readFile]` and write it straight to the response.

Alternatively, Vert.x provides a method which allows you to serve a file from disk or the filesystem to an HTTP response
in one operation.
Where supported by the underlying operating system this may result in the OS directly transferring bytes from the
file to the socket without being copied through user-space at all.

This is done by using `link:../../apidocs/io/vertx/core/http/HttpServerResponse.html#sendFile-java.lang.String-[sendFile]`, and is usually more efficient for large
files, but may be slower for small files.

Here's a very simple web server that serves files from the file system using sendFile:

[source,java]
----
vertx.createHttpServer().requestHandler(request -> {
  String file = "";
  if (request.path().equals("/")) {
    file = "index.html";
  } else if (!request.path().contains("..")) {
    file = request.path();
  }
  request.response().sendFile("web/" + file);
}).listen(8080);
----

Sending a file is asynchronous and may not complete until some time after the call has returned. If you want to
be notified when the file has been written you can use `link:../../apidocs/io/vertx/core/http/HttpServerResponse.html#sendFile-java.lang.String-[sendFile]`.

Please see the chapter about <<classpath, serving files from the classpath>> for restrictions about the classpath resolution or disabling it.

NOTE: If you use `sendFile` while using HTTPS it will copy through user-space, since if the kernel is copying data
directly from disk to socket it doesn't give us an opportunity to apply any encryption.

WARNING: If you're going to write web servers directly using Vert.x be careful that users cannot exploit the
path to access files outside the directory from which you want to serve them or the classpath It may be safer instead to use
Vert.x Web.

When there is a need to serve just a segment of a file, say starting from a given byte, you can achieve this by doing:

[source,java]
----
vertx.createHttpServer().requestHandler(request -> {
  long offset = 0;
  try {
    offset = Long.parseLong(request.getParam("start"));
  } catch (NumberFormatException e) {
    // error handling...
  }

  long end = Long.MAX_VALUE;
  try {
    end = Long.parseLong(request.getParam("end"));
  } catch (NumberFormatException e) {
    // error handling...
  }

  request.response().sendFile("web/mybigfile.txt", offset, end);
}).listen(8080);
----

You are not required to supply the length if you want to send a file starting from an offset until the end, in this
case you can just do:

[source,java]
----
vertx.createHttpServer().requestHandler(request -> {
  long offset = 0;
  try {
    offset = Long.parseLong(request.getParam("start"));
  } catch (NumberFormatException e) {
    // error handling...
  }

  request.response().sendFile("web/mybigfile.txt", offset);
}).listen(8080);
----

==== Piping responses

The server response is a `link:../../apidocs/io/vertx/core/streams/WriteStream.html[WriteStream]` so you can pipe to it from any
`link:../../apidocs/io/vertx/core/streams/ReadStream.html[ReadStream]`, e.g. `link:../../apidocs/io/vertx/core/file/AsyncFile.html[AsyncFile]`, `link:../../apidocs/io/vertx/core/net/NetSocket.html[NetSocket]`,
`link:../../apidocs/io/vertx/core/http/WebSocket.html[WebSocket]` or `link:../../apidocs/io/vertx/core/http/HttpServerRequest.html[HttpServerRequest]`.

Here's an example which echoes the request body back in the response for any PUT methods.
It uses a pipe for the body, so it will work even if the HTTP request body is much larger than can fit in memory
at any one time:

[source,java]
----
vertx.createHttpServer().requestHandler(request -> {
  HttpServerResponse response = request.response();
  if (request.method() == HttpMethod.PUT) {
    response.setChunked(true);
    request.pipeTo(response);
  } else {
    response.setStatusCode(400).end();
  }
}).listen(8080);
----

You can also use the `link:../../apidocs/io/vertx/core/http/HttpServerResponse.html#send-io.vertx.core.streams.ReadStream-[send]` method to send a `link:../../apidocs/io/vertx/core/streams/ReadStream.html[ReadStream]`.

Sending a stream is a pipe operation, however as this is a method of `link:../../apidocs/io/vertx/core/http/HttpServerResponse.html[HttpServerResponse]`, it
will also take  care of chunking the response when the `content-length` is not set.

[source,java]
----
vertx.createHttpServer().requestHandler(request -> {
  HttpServerResponse response = request.response();
  if (request.method() == HttpMethod.PUT) {
    response.send(request);
  } else {
    response.setStatusCode(400).end();
  }
}).listen(8080);
----

==== Writing HTTP/2 frames

HTTP/2 is a framed protocol with various frames for the HTTP request/response model. The protocol allows other kind
of frames to be sent and received.

To send such frames, you can use the `link:../../apidocs/io/vertx/core/http/HttpServerResponse.html#writeCustomFrame-int-int-io.vertx.core.buffer.Buffer-[writeCustomFrame]` on the response.
Here's an example:

[source,java]
----
int frameType = 40;
int frameStatus = 10;
Buffer payload = Buffer.buffer("some data");

// Sending a frame to the client
response.writeCustomFrame(frameType, frameStatus, payload);
----

These frames are sent immediately and are not subject to flow control - when such frame is sent there it may be done
before other `DATA` frames.

==== Stream reset

HTTP/1.x does not allow a clean reset of a request or a response stream, for example when a client uploads
a resource already present on the server, the server needs to accept the entire response.

HTTP/2 supports stream reset at any time during the request/response:

[source,java]
----
request.response().reset();
----

By default, the `NO_ERROR` (0) error code is sent, another code can sent instead:

[source,java]
----
request.response().reset(8);
----

The HTTP/2 specification defines the list of http://httpwg.org/specs/rfc7540.html#ErrorCodes[error codes] one can use.

The request handler are notified of stream reset events with the `link:../../apidocs/io/vertx/core/http/HttpServerRequest.html#exceptionHandler-io.vertx.core.Handler-[request handler]` and
`link:../../apidocs/io/vertx/core/http/HttpServerResponse.html#exceptionHandler-io.vertx.core.Handler-[response handler]`:

[source,java]
----
request.response().exceptionHandler(err -> {
  if (err instanceof StreamResetException) {
    StreamResetException reset = (StreamResetException) err;
    System.out.println("Stream reset " + reset.getCode());
  }
});
----

==== Server push

Server push is a new feature of HTTP/2 that enables sending multiple responses in parallel for a single client request.

When a server process a request, it can push a request/response to the client:

[source,java]
----
HttpServerResponse response = request.response();

// Push main.js to the client
response
  .push(HttpMethod.GET, "/main.js")
  .onComplete(ar -> {

    if (ar.succeeded()) {

      // The server is ready to push the response
      HttpServerResponse pushedResponse = ar.result();

      // Send main.js response
      pushedResponse.
        putHeader("content-type", "application/json").
        end("alert(\"Push response hello\")");
    } else {
      System.out.println("Could not push client resource " + ar.cause());
    }
  });

// Send the requested resource
response.sendFile("<html><head><script src=\"/main.js\"></script></head><body></body></html>");
----

When the server is ready to push the response, the push response handler is called and the handler can send the response.

The push response handler may receive a failure, for instance the client may cancel the push because it already has `main.js` in its
cache and does not want it anymore.

The `link:../../apidocs/io/vertx/core/http/HttpServerResponse.html#push-io.vertx.core.http.HttpMethod-java.lang.String-java.lang.String-[push]` method must be called before the initiating response ends, however
the pushed response can be written after.

==== Handling exceptions

You can set an `link:../../apidocs/io/vertx/core/http/HttpServer.html#exceptionHandler-io.vertx.core.Handler-[exceptionHandler]` to receive any
exceptions that happens before the connection is passed to the `link:../../apidocs/io/vertx/core/http/HttpServer.html#requestHandler-io.vertx.core.Handler-[requestHandler]`
or to the `link:../../apidocs/io/vertx/core/http/HttpServer.html#webSocketHandler-io.vertx.core.Handler-[webSocketHandler]`, e.g. during the TLS handshake.

==== Handling invalid requests

Vert.x will handle invalid HTTP requests and provides a default handler that will handle the common case
appropriately, e.g. it does respond with `REQUEST_HEADER_FIELDS_TOO_LARGE` when a request header is too long.

You can set your own `link:../../apidocs/io/vertx/core/http/HttpServer.html#invalidRequestHandler-io.vertx.core.Handler-[invalidRequestHandler]` to process
invalid requests. Your implementation can handle specific cases and delegate other cases to to `link:../../apidocs/io/vertx/core/http/HttpServerRequest.html#DEFAULT_INVALID_REQUEST_HANDLER[HttpServerRequest.DEFAULT_INVALID_REQUEST_HANDLER]`.

=== HTTP Compression

Vert.x comes with support for HTTP Compression out of the box.

This means you are able to automatically compress the body of the responses before they are sent back to the client.

If the client does not support HTTP compression the responses are sent back without compressing the body.

This allows to handle Client that support HTTP Compression and those that not support it at the same time.

To enable compression use can configure it with `link:../../apidocs/io/vertx/core/http/HttpServerOptions.html#setCompressionSupported-boolean-[setCompressionSupported]`.

By default, compression is not enabled.

When HTTP compression is enabled the server will check if the client includes an `Accept-Encoding` header which
includes the supported compressions. Commonly used are deflate and gzip. Both are supported by Vert.x.

If such a header is found the server will automatically compress the body of the response with one of the supported
compressions and send it back to the client.

Whenever the response needs to be sent without compression you can set the header `content-encoding` to `identity`:

[source,java]
----
request.response()
  .putHeader(HttpHeaders.CONTENT_ENCODING, HttpHeaders.IDENTITY)
  .sendFile("/path/to/image.jpg");
----

Be aware that compression may be able to reduce network traffic but is more CPU-intensive.

To address this latter issue Vert.x allows you to tune the 'compression level' parameter that is native of the gzip/deflate compression algorithms and also set the minimum response content size threshold for compression.

Compression level allows to configure gzip/deflate algorithms in terms of the compression ratio of the resulting data and the computational cost of the compress/decompress operation.

The compression level is an integer value ranged from '1' to '9', where '1' means lower compression ratio but fastest algorithm and '9' means maximum compression ratio available but a slower algorithm.

Using compression levels higher that 1-2 usually allows to save just some bytes in size - the gain is not linear, and depends on the specific data to be compressed
- but it comports a non-trascurable cost in term of CPU cycles required to the server while generating the compressed response data
( Note that at moment Vert.x doesn't support any form caching of compressed response data, even for static files, so the compression is done on-the-fly
at every request body generation ) and in the same way it affects client(s) while decoding (inflating) received responses, operation that becomes more CPU-intensive
the more the level increases.

By default - if compression is enabled via `link:../../apidocs/io/vertx/core/http/HttpServerOptions.html#setCompressionSupported-boolean-[setCompressionSupported]` - Vert.x will use '6' as compression level,
but the parameter can be configured to address any case with `link:../../apidocs/io/vertx/core/http/HttpServerOptions.html#setCompressionLevel-int-[setCompressionLevel]`.

It may not make sense to compress responses under certain size thresholds where the trade-off between CPU and saved network bytes is not beneficial.
The minimum response content size threshold for compression can be configured via `link:../../apidocs/io/vertx/core/http/HttpServerOptions.html#setCompressionContentSizeThreshold-int-[setCompressionContentSizeThreshold]`.
For example, if set to '100', responses under 100 bytes will not be compressed. By default, it is '0' which means all content can be compressed.

=== HTTP compression algorithms

Vert.x supports out of the box deflate and gzip.

Brotli, snappy and zstandard can also be used.

[source,java]
----
new HttpServerOptions()
  .addCompressor(io.netty.handler.codec.compression.StandardCompressionOptions.gzip())
  .addCompressor(io.netty.handler.codec.compression.StandardCompressionOptions.deflate())
  .addCompressor(io.netty.handler.codec.compression.StandardCompressionOptions.brotli())
  .addCompressor(io.netty.handler.codec.compression.StandardCompressionOptions.zstd());
----

NOTE: use `link:../../apidocs/io/netty/handler/codec/compression/StandardCompressionOptions.html[StandardCompressionOptions]` static methods to create `link:../../apidocs/io/netty/handler/codec/compression/CompressionOptions.html[CompressionOptions]`

Brotli and zstandard libraries need to be added to the classpath, snappy is provided by default.

* Maven (in your `pom.xml`):

[source,xml]
----
<dependency>
  <groupId>com.aayushatharva.brotli4j</groupId>
  <artifactId>brotli4j</artifactId>
  <version>${brotli4j.version}</version>
</dependency>
<dependency>
  <groupId>com.github.luben</groupId>
  <artifactId>zstd-jni</artifactId>
  <version>${zstd-jini.version}</version>
</dependency>
----
* Gradle (in your `build.gradle` file):

[source,groovy]
----
dependencies {
  implementation 'com.aayushatharva.brotli4j:brotli4j:${brotli4j.version}'
  runtimeOnly 'com.aayushatharva.brotli4j:native-$system-and-arch:${brotli4j.version}'
  implementation 'com.github.luben:zstd-jni:${zstd-jini.version}'
}
----

When using Gradle, you need to add the runtime native library manually depending on your OS and architecture. See https://github.com/hyperxpro/Brotli4j#gradle[the Gradle section of Brotli4j] for more details.

You can configure compressors according to your needs

[source,java]
----
GzipOptions gzip = StandardCompressionOptions.gzip(6, 15, 8);
----

=== Creating an HTTP client

You create an `link:../../apidocs/io/vertx/core/http/HttpClient.html[HttpClient]` instance with default options as follows:

[source,java]
----
HttpClientAgent client = vertx.createHttpClient();
----

If you want to configure options for the client, you create it as follows:

[source,java]
----
HttpClientOptions options = new HttpClientOptions().setKeepAlive(false);
HttpClientAgent client = vertx.createHttpClient(options);
----

Vert.x supports HTTP/2 over TLS `h2` and over TCP `h2c`.

By default, the http client performs HTTP/1.1 requests, to perform HTTP/2 requests the `link:../../apidocs/io/vertx/core/http/HttpClientOptions.html#setProtocolVersion-io.vertx.core.http.HttpVersion-[setProtocolVersion]`
must be set to `link:../../apidocs/io/vertx/core/http/HttpVersion.html#HTTP_2[HTTP_2]`.

For `h2` requests, TLS must be enabled with _Application-Layer Protocol Negotiation_:

[source,java]
----
HttpClientOptions options = new HttpClientOptions().
    setProtocolVersion(HttpVersion.HTTP_2).
    setSsl(true).
    setUseAlpn(true).
    setTrustAll(true);

HttpClient client = vertx.createHttpClient(options);
----

For `h2c` requests, TLS must be disabled, the client will do an HTTP/1.1 requests and try an upgrade to HTTP/2:

[source,java]
----
HttpClientOptions options = new HttpClientOptions().setProtocolVersion(HttpVersion.HTTP_2);

HttpClient client = vertx.createHttpClient(options);
----

`h2c` connections can also be established directly, i.e. connection started with a prior knowledge, when
`link:../../apidocs/io/vertx/core/http/HttpClientOptions.html#setHttp2ClearTextUpgrade-boolean-[setHttp2ClearTextUpgrade]` options is set to false: after the
connection is established, the client will send the HTTP/2 connection preface and expect to receive
the same preface from the server.

The http server may not support HTTP/2, the actual version can be checked
with `link:../../apidocs/io/vertx/core/http/HttpResponseHead.html#version--[version]` when the response arrives.

When a client connects to an HTTP/2 server, it sends to the server its `link:../../apidocs/io/vertx/core/http/HttpClientOptions.html#getInitialSettings--[initial settings]`.
The settings define how the server can use the connection, the default initial settings for a client are the default
values defined by the HTTP/2 RFC.

=== Making connections to Unix domain sockets

When running on JDK 16+, or using a <<_native_transports,native transport>>, a client can connect to Unix domain sockets:

[source,java]
----
HttpClient httpClient = vertx.createHttpClient();

// Only available when running on JDK16+, or using a native transport
SocketAddress addr = SocketAddress.domainSocketAddress("/var/tmp/myservice.sock");

// Send request to the server
httpClient.request(new RequestOptions()
  .setServer(addr)
  .setHost("localhost")
  .setPort(8080)
  .setURI("/"))
  .compose(request -> request.send().compose(HttpClientResponse::body))
  .onComplete(ar -> {
    if (ar.succeeded()) {
      // Process response
    } else {
      // Handle failure
    }
  });
----

=== Pool configuration

For performance purpose, the client uses connection pooling when interacting with HTTP/1.1 servers.
The pool creates up to 5 connections per server.
You can override the pool configuration like this:

[source,java]
----
PoolOptions options = new PoolOptions().setHttp1MaxSize(10);
HttpClientAgent client = vertx.createHttpClient(options);
----

You can configure various pool `link:../../apidocs/io/vertx/core/http/PoolOptions.html[options]` as follows

- `link:../../apidocs/io/vertx/core/http/PoolOptions.html[options#setHttp1MaxSize]` the maximum number of opened per HTTP/1.x server (5 by default)
- `link:../../apidocs/io/vertx/core/http/PoolOptions.html[options#setHttp2MaxSize]` the maximum number of opened per HTTP/2 server (1 by default), you *should* not change this value since a single HTTP/2 connection is capable of delivering the same performance level than multiple HTTP/1.x connections
- `link:../../apidocs/io/vertx/core/http/PoolOptions.html[options#setCleanerPeriod]` the period in milliseconds at which the pool checks expired connections (1 second by default)
- `link:../../apidocs/io/vertx/core/http/PoolOptions.html[options#setEventLoopSize]` sets the number of event loops the pool use (0 by default)
- a value of 0 configures the pool to use the event loop of the caller
- a positive value configures the pool load balance the creation of connection over a list of event loops determined by the value
- `link:../../apidocs/io/vertx/core/http/PoolOptions.html[options#setMaxWaitQueueSize]` the maximum number of HTTP requests waiting until a connection is available, when the queue is full, the request is rejected

=== Logging network client activity

For debugging purposes, network activity can be logged.

[source,java]
----
HttpClientOptions options = new HttpClientOptions().setLogActivity(true);
HttpClientAgent client = vertx.createHttpClient(options);
----

See the chapter on <<logging_network_activity, logging network activity>> for a detailed explanation.

=== Advanced HTTP client creation

You can pass options `link:../../apidocs/io/vertx/core/Vertx.html#createHttpClient-io.vertx.core.http.HttpClientOptions-io.vertx.core.http.PoolOptions-[createHttpClient]` methods to configure the HTTP client.

Alternatively you can build a client with the builder `link:../../apidocs/io/vertx/core/http/HttpClientBuilder.html[API]` :

[source,java]
----
HttpClientAgent build = vertx
  .httpClientBuilder()
  .with(options)
  .build();
----

In addition to `link:../../apidocs/io/vertx/core/http/HttpClientOptions.html[HttpClientOptions]` and `link:../../apidocs/io/vertx/core/http/PoolOptions.html[PoolOptions]`, you
can set

- a connection event handler notified when the client <<_client_connections,connects>> to a server
- a redirection handler to implement an alternative HTTP <<_30x_redirection_handling,redirect>> behavior

=== Making requests

The http client is very flexible and there are various ways you can make requests with it.

The first step when making a request is obtaining an HTTP connection to the remote server:

[source,java]
----
client
  .request(HttpMethod.GET, 8080, "myserver.mycompany.com", "/some-uri")
  .onComplete(ar1 -> {
    if (ar1.succeeded()) {
      // Connected to the server
    }
  });
----

The client will connect to the remote server or reuse an available connection from the client connection pool.

==== Default host and port

Often you want to make many requests to the same host/port with an http client. To avoid you repeating the host/port
every time you make a request you can configure the client with a default host/port:

[source,java]
----
HttpClientOptions options = new HttpClientOptions().setDefaultHost("wibble.com");

// Can also set default port if you want...
HttpClientAgent client = vertx.createHttpClient(options);
client
  .request(HttpMethod.GET, "/some-uri")
  .onComplete(ar1 -> {
    if (ar1.succeeded()) {
      HttpClientRequest request = ar1.result();
      request
        .send()
        .onComplete(ar2 -> {
          if (ar2.succeeded()) {
            HttpClientResponse response = ar2.result();
            System.out.println("Received response with status code " + response.statusCode());
          }
        });
    }
  });
----

==== Writing request headers

You can write headers to a request using the `link:../../apidocs/io/vertx/core/http/HttpHeaders.html[HttpHeaders]` as follows:

[source,java]
----
HttpClientAgent client = vertx.createHttpClient();

// Write some headers using the headers multi-map
MultiMap headers = HttpHeaders.set("content-type", "application/json").set("other-header", "foo");

client
  .request(HttpMethod.GET, "some-uri")
  .onComplete(ar1 -> {
    if (ar1.succeeded()) {
      if (ar1.succeeded()) {
        HttpClientRequest request = ar1.result();
        request.headers().addAll(headers);
        request
          .send()
          .onComplete(ar2 -> {
            HttpClientResponse response = ar2.result();
            System.out.println("Received response with status code " + response.statusCode());
          });
      }
    }
  });
----

The headers are an instance of `link:../../apidocs/io/vertx/core/MultiMap.html[MultiMap]` which provides operations for adding, setting and removing
entries. Http headers allow more than one value for a specific key.

You can also write headers using `link:../../apidocs/io/vertx/core/http/HttpClientRequest.html#putHeader-java.lang.String-java.lang.String-[putHeader]`

[source,java]
----
request.putHeader("content-type", "application/json")
       .putHeader("other-header", "foo");
----

If you wish to write headers to the request you must do so before any part of the request body is written.

==== Writing request and processing response

The `link:../../apidocs/io/vertx/core/http/HttpClientRequest.html[HttpClientRequest]` `request` methods connects to the remote server
or reuse an existing connection. The request instance obtained is pre-populated with some data
 such like the host or the request URI, but you need to send this request to the server.

You can call `link:../../apidocs/io/vertx/core/http/HttpClientRequest.html#send--[send]` to send a request such as an HTTP
`GET` and process the asynchronous `link:../../apidocs/io/vertx/core/http/HttpClientResponse.html[HttpClientResponse]`.

[source,java]
----
client
  .request(HttpMethod.GET, 8080, "myserver.mycompany.com", "/some-uri")
  .onComplete(ar1 -> {
    if (ar1.succeeded()) {
      HttpClientRequest request = ar1.result();

      // Send the request and process the response
      request
        .send()
        .onComplete(ar -> {
          if (ar.succeeded()) {
            HttpClientResponse response = ar.result();
            System.out.println("Received response with status code " + response.statusCode());
          } else {
            System.out.println("Something went wrong " + ar.cause().getMessage());
          }
        });
    }
  });
----

You can also send the request with a body.

`link:../../apidocs/io/vertx/core/http/HttpClientRequest.html#send-java.lang.String-[send]` with a string, the `Content-Length`
header will be set for you if it was not previously set.

[source,java]
----
client
  .request(HttpMethod.GET, 8080, "myserver.mycompany.com", "/some-uri")
  .onComplete(ar1 -> {
    if (ar1.succeeded()) {
      HttpClientRequest request = ar1.result();

      // Send the request and process the response
      request
        .send("Hello World")
        .onComplete(ar -> {
          if (ar.succeeded()) {
            HttpClientResponse response = ar.result();
            System.out.println("Received response with status code " + response.statusCode());
          } else {
            System.out.println("Something went wrong " + ar.cause().getMessage());
          }
        });
    }
  });
----

`link:../../apidocs/io/vertx/core/http/HttpClientRequest.html#send-io.vertx.core.buffer.Buffer-[send]` with a buffer, the
`Content-Length` header will be set for you if it was not previously set.

[source,java]
----
request
  .send(Buffer.buffer("Hello World"))
  .onComplete(ar -> {
    if (ar.succeeded()) {
      HttpClientResponse response = ar.result();
      System.out.println("Received response with status code " + response.statusCode());
    } else {
      System.out.println("Something went wrong " + ar.cause().getMessage());
    }
  });
----

`link:../../apidocs/io/vertx/core/http/HttpClientRequest.html#send-io.vertx.core.streams.ReadStream-[send]` with a stream, if
the `Content-Length` header was not previously set, the request is sent with a chunked `Content-Encoding`.

[source,java]
----
request
  .putHeader(HttpHeaders.CONTENT_LENGTH, "1000")
  .send(stream)
  .onComplete(ar -> {
    if (ar.succeeded()) {
      HttpClientResponse response = ar.result();
      System.out.println("Received response with status code " + response.statusCode());
    } else {
      System.out.println("Something went wrong " + ar.cause().getMessage());
    }
  });
----

==== Streaming Request body

The `send` method send requests at once.

Sometimes you'll want to have low level control on how you write requests bodies.

The `link:../../apidocs/io/vertx/core/http/HttpClientRequest.html[HttpClientRequest]` can be used to write the request body.

Here are some examples of writing a POST request with a body:

[source,java]
----
HttpClientAgent client = vertx.createHttpClient();

client.request(HttpMethod.POST, "some-uri")
  .onSuccess(request -> {
    request.response().onSuccess(response -> {
      System.out.println("Received response with status code " + response.statusCode());
    });

    // Now do stuff with the request
    request.putHeader("content-length", "1000");
    request.putHeader("content-type", "text/plain");
    request.write(body);

    // Make sure the request is ended when you're done with it
    request.end();
});
----

Methods exist to write strings in UTF-8 encoding and in any specific encoding and to write buffers:

[source,java]
----
request.write("some data");

// Write string encoded in specific encoding
request.write("some other data", "UTF-16");

// Write a buffer
Buffer buffer = Buffer.buffer();
buffer.appendInt(123).appendLong(245l);
request.write(buffer);
----

If you are just writing a single string or buffer to the HTTP request you can write it and end the request in a
single call to the `end` function.

[source,java]
----
request.end("some simple data");

// Write buffer and end the request (send it) in a single call
Buffer buffer = Buffer.buffer().appendDouble(12.34d).appendLong(432l);
request.end(buffer);
----

When you're writing to a request, the first call to `write` will result in the request headers being written
out to the wire.

The actual write is asynchronous and might not occur until some time after the call has returned.

Non-chunked HTTP requests with a request body require a `Content-Length` header to be provided.

Consequently, if you are not using chunked HTTP then you must set the `Content-Length` header before writing
to the request, as it will be too late otherwise.

If you are calling one of the `end` methods that take a string or buffer then Vert.x will automatically calculate
and set the `Content-Length` header before writing the request body.

If you are using HTTP chunking a `Content-Length` header is not required, so you do not have to calculate the size
up-front.

==== Ending streamed HTTP requests

Once you have finished with the HTTP request you must end it with one of the `link:../../apidocs/io/vertx/core/http/HttpClientRequest.html#end-java.lang.String-[end]`
operations.

Ending a request causes any headers to be written, if they have not already been written and the request to be marked
as complete.

Requests can be ended in several ways. With no arguments the request is simply ended:

[source,java]
----
request.end();
----

Or a string or buffer can be provided in the call to `end`. This is like calling `write` with the string or buffer
before calling `end` with no arguments

[source,java]
----
request.end("some-data");

// End it with a buffer
Buffer buffer = Buffer.buffer().appendFloat(12.3f).appendInt(321);
request.end(buffer);
----

==== Using the request as a stream

An `link:../../apidocs/io/vertx/core/http/HttpClientRequest.html[HttpClientRequest]` instance is also a `link:../../apidocs/io/vertx/core/streams/WriteStream.html[WriteStream]` instance.

You can pipe to it from any `link:../../apidocs/io/vertx/core/streams/ReadStream.html[ReadStream]` instance.

For, example, you could pipe a file on disk to an http request body as follows:

[source,java]
----
request.setChunked(true);
file.pipeTo(request);
----

==== Chunked HTTP requests

Vert.x supports http://en.wikipedia.org/wiki/Chunked_transfer_encoding[HTTP Chunked Transfer Encoding] for requests.

This allows the HTTP request body to be written in chunks, and is normally used when a large request body is being streamed
to the server, whose size is not known in advance.

You put the HTTP request into chunked mode using `link:../../apidocs/io/vertx/core/http/HttpClientRequest.html#setChunked-boolean-[setChunked]`.

In chunked mode each call to write will cause a new chunk to be written to the wire. In chunked mode there is
no need to set the `Content-Length` of the request up-front.

[source,java]
----
request.setChunked(true);

// Write some chunks
for (int i = 0; i < 10; i++) {
  request.write("this-is-chunk-" + i);
}

request.end();
----

==== Request timeouts

You can set an idle timeout to prevent your application from unresponsive servers using `link:../../apidocs/io/vertx/core/http/RequestOptions.html#setIdleTimeout-long-[setIdleTimeout]` or `link:../../apidocs/io/vertx/core/http/HttpClientRequest.html#idleTimeout-long-[idleTimeout]`. When the request does not return any data within the timeout period an exception will fail the result and the request will be reset.

[source,java]
----
Future<Buffer> fut = client
  .request(new RequestOptions()
    .setHost(host)
    .setPort(port)
    .setURI(uri)
    .setIdleTimeout(timeoutMS))
  .compose(request -> request.send().compose(HttpClientResponse::body));
----

NOTE: the timeout starts when the `link:../../apidocs/io/vertx/core/http/HttpClientRequest.html[HttpClientRequest]` is available, implying a connection was
obtained from the pool.

You can set a connect timeout to prevent your application from unresponsive busy client connection pool. The
`Future<HttpClientRequest>` is failed when a connection is not obtained before the timeout delay.

The connect timeout option is not related to the TCP `link:../../apidocs/io/vertx/core/http/HttpClientOptions.html#setConnectTimeout-int-[setConnectTimeout]` option, when a request is made against a pooled HTTP client, the timeout applies to the duration to obtain a connection from the pool to serve the request,
the timeout might fire because the server does not respond in time or the pool is too busy to serve a request.

You can configure both timeout using `link:../../apidocs/io/vertx/core/http/RequestOptions.html#setTimeout-long-[setTimeout]`

[source,java]
----
Future<Buffer> fut = client
  .request(new RequestOptions()
    .setHost(host)
    .setPort(port)
    .setURI(uri)
    .setTimeout(timeoutMS))
  .compose(request -> request.send().compose(HttpClientResponse::body));
----

==== Writing HTTP/2 frames

HTTP/2 is a framed protocol with various frames for the HTTP request/response model. The protocol allows other kind
of frames to be sent and received.

To send such frames, you can use the `link:../../apidocs/io/vertx/core/streams/WriteStream.html#write-java.lang.Object-[write]` on the request. Here's an example:

[source,java]
----
int frameType = 40;
int frameStatus = 10;
Buffer payload = Buffer.buffer("some data");

// Sending a frame to the server
request.writeCustomFrame(frameType, frameStatus, payload);
----

==== Stream reset

HTTP/1.x does not allow a clean reset of a request or a response stream, for example when a client uploads a resource already
present on the server, the server needs to accept the entire response.

HTTP/2 supports stream reset at any time during the request/response:

[source,java]
----
request.reset();
----

By default the NO_ERROR (0) error code is sent, another code can sent instead:

[source,java]
----
request.reset(8);
----

The HTTP/2 specification defines the list of http://httpwg.org/specs/rfc7540.html#ErrorCodes[error codes] one can use.

The request handler are notified of stream reset events with the `link:../../apidocs/io/vertx/core/http/HttpClientRequest.html#exceptionHandler-io.vertx.core.Handler-[request handler]` and
`link:../../apidocs/io/vertx/core/http/HttpClientResponse.html#exceptionHandler-io.vertx.core.Handler-[response handler]`:

[source,java]
----
request.exceptionHandler(err -> {
  if (err instanceof StreamResetException) {
    StreamResetException reset = (StreamResetException) err;
    System.out.println("Stream reset " + reset.getCode());
  }
});
----

=== HTTP/2 RST flood protection

An HTTP/2 server is protected against RST flood DDOS attacks (https://github.com/netty/netty/security/advisories/GHSA-xpw8-rcwv-8f8p[CVE-2023-44487]): there is an upper bound to the number of `RST`
frames a server can receive in a time window. The default configuration sets the upper bound to `200` for a duration of
`30` seconds.

You can use `link:../../apidocs/io/vertx/core/http/HttpServerOptions.html#setHttp2RstFloodMaxRstFramePerWindow-int-[setHttp2RstFloodMaxRstFramePerWindow]` and `link:../../apidocs/io/vertx/core/http/HttpServerOptions.html#setHttp2RstFloodWindowDuration-int-[setHttp2RstFloodWindowDuration]` to override these settings.

=== Handling HTTP responses

You receive an instance of `link:../../apidocs/io/vertx/core/http/HttpClientResponse.html[HttpClientResponse]` into the handler that you specify in of
the request methods or by setting a handler directly on the `link:../../apidocs/io/vertx/core/http/HttpClientRequest.html[HttpClientRequest]` object.

You can query the status code and the status message of the response with `link:../../apidocs/io/vertx/core/http/HttpResponseHead.html#statusCode--[statusCode]`
and `link:../../apidocs/io/vertx/core/http/HttpResponseHead.html#statusMessage--[statusMessage]`.

[source,java]
----
request
  .send()
  .onComplete(ar2 -> {
    if (ar2.succeeded()) {

      HttpClientResponse response = ar2.result();

      // the status code - e.g. 200 or 404
      System.out.println("Status code is " + response.statusCode());

      // the status message e.g. "OK" or "Not Found".
      System.out.println("Status message is " + response.statusMessage());
    }
  });
----

==== Using the response as a stream

The `link:../../apidocs/io/vertx/core/http/HttpClientResponse.html[HttpClientResponse]` instance is also a `link:../../apidocs/io/vertx/core/streams/ReadStream.html[ReadStream]` which means
you can pipe it to any `link:../../apidocs/io/vertx/core/streams/WriteStream.html[WriteStream]` instance.

==== Response headers and trailers

Http responses can contain headers. Use `link:../../apidocs/io/vertx/core/http/HttpResponseHead.html#headers--[headers]` to get the headers.

The object returned is a `link:../../apidocs/io/vertx/core/MultiMap.html[MultiMap]` as HTTP headers can contain multiple values for single keys.

[source,java]
----
String contentType = response.headers().get("content-type");
String contentLength = response.headers().get("content-lengh");
----

Chunked HTTP responses can also contain trailers - these are sent in the last chunk of the response body.

You use `link:../../apidocs/io/vertx/core/http/HttpClientResponse.html#trailers--[trailers]` to get the trailers. Trailers are also a `link:../../apidocs/io/vertx/core/MultiMap.html[MultiMap]`.

==== Reading the request body

The response handler is called when the headers of the response have been read from the wire.

If the response has a body this might arrive in several pieces some time after the headers have been read. We
don't wait for all the body to arrive before calling the response handler as the response could be very large and we
might be waiting a long time, or run out of memory for large responses.

As parts of the response body arrive, the `link:../../apidocs/io/vertx/core/http/HttpClientResponse.html#handler-io.vertx.core.Handler-[handler]` is called with
a `link:../../apidocs/io/vertx/core/buffer/Buffer.html[Buffer]` representing the piece of the body:

[source,java]
----
client
  .request(HttpMethod.GET, "some-uri")
  .onComplete(ar1 -> {

    if (ar1.succeeded()) {
      HttpClientRequest request = ar1.result();
      request
        .send()
        .onComplete(ar2 -> {
          HttpClientResponse response = ar2.result();
          response.handler(buffer -> {
            System.out.println("Received a part of the response body: " + buffer);
          });
        });
    }
  });
----

If you know the response body is not very large and want to aggregate it all in memory before handling it, you can
either aggregate it yourself:

[source,java]
----
request
  .send()
  .onComplete(ar2 -> {

    if (ar2.succeeded()) {

      HttpClientResponse response = ar2.result();

      // Create an empty buffer
      Buffer totalBuffer = Buffer.buffer();

      response.handler(buffer -> {
        System.out.println("Received a part of the response body: " + buffer.length());

        totalBuffer.appendBuffer(buffer);
      });

      response.endHandler(v -> {
        // Now all the body has been read
        System.out.println("Total response body length is " + totalBuffer.length());
      });
    }
  });
----

Or you can use the convenience `link:../../apidocs/io/vertx/core/http/HttpClientResponse.html#body--[body]` which
is called with the entire body when the response has been fully read:

[source,java]
----
request
  .send()
  .onComplete(ar1 -> {

    if (ar1.succeeded()) {
      HttpClientResponse response = ar1.result();
      response
        .body()
        .onComplete(ar2 -> {

          if (ar2.succeeded()) {
            Buffer body = ar2.result();
            // Now all the body has been read
            System.out.println("Total response body length is " + body.length());
          }
        });
    }
  });
----

==== Response end handler

The response `link:../../apidocs/io/vertx/core/http/HttpClientResponse.html#endHandler-io.vertx.core.Handler-[endHandler]` is called when the entire response body has been read
or immediately after the headers have been read and the response handler has been called if there is no body.

==== Request and response composition

The client interface is very simple and follows this pattern:

1. `request` a connection
2. `send` or `write`/`end` the request to the server
3. handle the beginning of the `link:../../apidocs/io/vertx/core/http/HttpClientResponse.html[HttpClientResponse]`
4. process the response events

You can use Vert.x future composition methods to make your code simpler, however the API is event driven,
and you need to understand it otherwise you might experience possible data races (i.e. loosing events
leading to corrupted data).

NOTE: https://vertx.io/docs/vertx-web-client/java/[Vert.x Web Client] is a higher level API alternative (in fact it is built
on top of this client) you might consider if this client is too low level for your use cases

The client API intentionally does not return a `Future<HttpClientResponse>` because setting a completion
handler on the future can be racy when this is set outside the event-loop.

[source,java]
----
Future<HttpClientResponse> get = client.get("some-uri");

// Assuming we have a client that returns a future response
// assuging this is *not* on the event-loop
// introduce a potential data race for the sake of this example
Thread.sleep(100);

get.onSuccess(response -> {

  // Response events might have happen already
  response
    .body()
    .onComplete(ar -> {

    });
});
----

Confining the `HttpClientRequest` usage within a verticle is the easiest solution as the Verticle
will ensure that events are processed sequentially avoiding races.

[source,java]
----
vertx.deployVerticle(() -> new AbstractVerticle() {
  @Override
  public void start() {

    HttpClient client = vertx.createHttpClient();

    Future<HttpClientRequest> future = client.request(HttpMethod.GET, "some-uri");
  }
}, new DeploymentOptions());
----

When you are interacting with the client possibly outside a verticle then you can safely perform
composition as long as you do not delay the response events, e.g. processing  directly the response on the event-loop.

[source,java]
----
Future<JsonObject> future = client
  .request(HttpMethod.GET, "some-uri")
  .compose(request -> request
    .send()
    .compose(response -> {
      // Process the response on the event-loop which guarantees no races
      if (response.statusCode() == 200 &&
          response.getHeader(HttpHeaders.CONTENT_TYPE).equals("application/json")) {
        return response
          .body()
          .map(buffer -> buffer.toJsonObject());
      } else {
        return Future.failedFuture("Incorrect HTTP response");
      }
    }));

// Listen to the composed final json result
future.onSuccess(json -> {
  System.out.println("Received json result " + json);
}).onFailure(err -> {
  System.out.println("Something went wrong " + err.getMessage());
});
----

You can also guard the response body with <<response-expectations,HTTP responses expectations>>.

[source,java]
----
Future<JsonObject> future = client
  .request(HttpMethod.GET, "some-uri")
  .compose(request -> request
    .send()
    .expecting(HttpResponseExpectation.SC_OK.and(HttpResponseExpectation.JSON))
    .compose(response -> response
      .body()
      .map(buffer -> buffer.toJsonObject())));
// Listen to the composed final json result
future.onSuccess(json -> {
  System.out.println("Received json result " + json);
}).onFailure(err -> {
  System.out.println("Something went wrong " + err.getMessage());
});
----

If you need to delay the response processing then you need to `pause` the response or use a `pipe`, this
might be necessary when another asynchronous operation is involved.

[source,java]
----
Future<Void> future = client
  .request(HttpMethod.GET, "some-uri")
  .compose(request -> request
    .send()
    .compose(response -> {
      // Process the response on the event-loop which guarantees no races
      if (response.statusCode() == 200) {

        // Create a pipe, this pauses the response
        Pipe<Buffer> pipe = response.pipe();

        // Write the file on the disk
        return fileSystem
          .open("/some/large/file", new OpenOptions().setWrite(true))
          .onFailure(err -> pipe.close())
          .compose(file -> pipe.to(file));
      } else {
        return Future.failedFuture("Incorrect HTTP response");
      }
    }));
----

[[response-expectations]]
==== Response expectations

As seen above, you must perform sanity checks manually after the response is received.

You can trade flexibility for clarity and conciseness using _response expectations_.

`link:../../apidocs/io/vertx/core/http/HttpResponseExpectation.html[Response expectations]` can guard the control flow when the response does
not match a criteria.

The HTTP Client comes with a set of out of the box predicates ready to use:

[source,java]
----
Future<Buffer> fut = client
  .request(options)
  .compose(request -> request
    .send()
    .expecting(HttpResponseExpectation.SC_SUCCESS)
    .compose(response -> response.body()));
----

You can also create custom predicates when existing predicates don't fit your needs:

[source,java]
----
HttpResponseExpectation methodsPredicate =
  resp -> {
    String methods = resp.getHeader("Access-Control-Allow-Methods");
    return methods != null && methods.contains("POST");
  };

// Send pre-flight CORS request
client
  .request(new RequestOptions()
    .setMethod(HttpMethod.OPTIONS)
    .setPort(8080)
    .setHost("myserver.mycompany.com")
    .setURI("/some-uri")
    .putHeader("Origin", "Server-b.com")
    .putHeader("Access-Control-Request-Method", "POST"))
  .compose(request -> request
    .send()
    .expecting(methodsPredicate))
  .onSuccess(res -> {
    // Process the POST request now
  })
  .onFailure(err ->
    System.out.println("Something went wrong " + err.getMessage()));
----

==== Predefined expectations

As a convenience, the HTTP Client ships a few predicates for common uses cases .

For status codes, e.g. `link:../../apidocs/io/vertx/core/http/HttpResponseExpectation.html#SC_SUCCESS[HttpResponseExpectation.SC_SUCCESS]` to verify that the
response has a `2xx` code, you can also create a custom one:

[source,java]
----
client
  .request(options)
  .compose(request -> request
    .send()
    .expecting(HttpResponseExpectation.status(200, 202)))
  .onSuccess(res -> {
    // ....
  });
----

For content types, e.g. `link:../../apidocs/io/vertx/core/http/HttpResponseExpectation.html#JSON[HttpResponseExpectation.JSON]` to verify that the
response body contains JSON data, you can also create a custom one:

[source,java]
----
client
  .request(options)
  .compose(request -> request
    .send()
    .expecting(HttpResponseExpectation.contentType("some/content-type")))
  .onSuccess(res -> {
    // ....
  });
----

Please refer to the `link:../../apidocs/io/vertx/core/http/HttpResponseExpectation.html[HttpResponseExpectation]` documentation for a full list of predefined expectations.

==== Creating custom failures

By default, expectations (including the predefined ones) conveys a simple error message. You can customize the exception class by changing the error converter:

[source,java]
----
Expectation<HttpResponseHead> expectation = HttpResponseExpectation.SC_SUCCESS
  .wrappingFailure((resp, err) -> new MyCustomException(resp.statusCode(), err.getMessage()));
----

WARNING: creating exception in Java can have a performance cost when it captures a stack trace, so you might want
to create exceptions that do not capture the stack trace. By default exceptions are reported using an exception that
does not capture the stack trace.

==== Reading cookies from the response

You can retrieve the list of cookies from a response using `link:../../apidocs/io/vertx/core/http/HttpResponseHead.html#cookies--[cookies]`.

Alternatively you can just parse the `Set-Cookie` headers yourself in the response.

==== 30x redirection handling

The client can be configured to follow HTTP redirections provided by the `Location` response header when the client receives:

* a `301`, `302`, `307` or `308` status code along with an HTTP GET or HEAD method
* a `303` status code, in addition the directed request perform an HTTP GET method

Here's an example:

[source,java]
----
client
  .request(HttpMethod.GET, "some-uri")
  .onComplete(ar1 -> {
    if (ar1.succeeded()) {

      HttpClientRequest request = ar1.result();
      request.setFollowRedirects(true);
      request
        .send()
        .onComplete(ar2 -> {
          if (ar2.succeeded()) {

            HttpClientResponse response = ar2.result();
            System.out.println("Received response with status code " + response.statusCode());
          }
        });
    }
  });
----

The maximum redirects is `16` by default and can be changed with `link:../../apidocs/io/vertx/core/http/HttpClientOptions.html#setMaxRedirects-int-[setMaxRedirects]`.

[source,java]
----
HttpClientAgent client = vertx.createHttpClient(
    new HttpClientOptions()
        .setMaxRedirects(32));

client
  .request(HttpMethod.GET, "some-uri")
  .onComplete(ar1 -> {
    if (ar1.succeeded()) {

      HttpClientRequest request = ar1.result();
      request.setFollowRedirects(true);
      request
        .send()
        .onComplete(ar2 -> {
          if (ar2.succeeded()) {

            HttpClientResponse response = ar2.result();
            System.out.println("Received response with status code " + response.statusCode());
          }
        });
    }
  });
----

One size does not fit all and the default redirection policy may not be adapted to your needs.

The default redirection policy can changed with a custom implementation:

[source,java]
----
HttpClientAgent client = vertx.httpClientBuilder()
  .withRedirectHandler(response -> {

    // Only follow 301 code
    if (response.statusCode() == 301 && response.getHeader("Location") != null) {

      // Compute the redirect URI
      String absoluteURI = resolveURI(response.request().absoluteURI(), response.getHeader("Location"));

      // Create a new ready to use request that the client will use
      return Future.succeededFuture(new RequestOptions().setAbsoluteURI(absoluteURI));
    }

    // We don't redirect
    return null;
  })
  .build();
----

The policy handles the original `link:../../apidocs/io/vertx/core/http/HttpClientResponse.html[HttpClientResponse]` received and returns either `null`
or a `Future<HttpClientRequest>`.

- when `null` is returned, the original response is processed
- when a future is returned, the request will be sent on its successful completion
- when a future is returned, the exception handler set on the request is called on its failure

The returned request must be unsent so the original request handlers can be sent and the client can send it after.

Most of the original request settings will be propagated to the new request:

* request headers, unless if you have set some headers
* request body unless the returned request uses a `GET` method
* response handler
* request exception handler
* request timeout

==== 100-Continue handling

According to the http://www.w3.org/Protocols/rfc2616/rfc2616-sec8.html[HTTP 1.1 specification] a client can set a
header `Expect: 100-Continue` and send the request header before sending the rest of the request body.

The server can then respond with an interim response status `Status: 100 (Continue)` to signify to the client that
it is ok to send the rest of the body.

The idea here is it allows the server to authorise and accept/reject the request before large amounts of data are sent.
Sending large amounts of data if the request might not be accepted is a waste of bandwidth and ties up the server
in reading data that it will just discard.

Vert.x allows you to set a `link:../../apidocs/io/vertx/core/http/HttpClientRequest.html#continueHandler-io.vertx.core.Handler-[continueHandler]` on the
client request object

This will be called if the server sends back a `Status: 100 (Continue)` response to signify that it is ok to send
the rest of the request.

This is used in conjunction with `link:../../apidocs/io/vertx/core/http/HttpClientRequest.html#sendHead--[sendHead]`to send the head of the request.

Here's an example:

[source,java]
----
client.request(HttpMethod.PUT, "some-uri")
  .onSuccess(request -> {
    request.response().onSuccess(response -> {
      System.out.println("Received response with status code " + response.statusCode());
    });

    request.putHeader("Expect", "100-Continue");

    request.continueHandler(v -> {
      // OK to send rest of body
      request.write("Some data");
      request.write("Some more data");
      request.end();
    });

    request.sendHead();
});
----

On the server side a Vert.x http server can be configured to automatically send back 100 Continue interim responses
when it receives an `Expect: 100-Continue` header.

This is done by setting the option `link:../../apidocs/io/vertx/core/http/HttpServerOptions.html#setHandle100ContinueAutomatically-boolean-[setHandle100ContinueAutomatically]`.

If you'd prefer to decide whether to send back continue responses manually, then this property should be set to
`false` (the default), then you can inspect the headers and call `link:../../apidocs/io/vertx/core/http/HttpServerResponse.html#writeContinue--[writeContinue]`
to have the client continue sending the body:

[source,java]
----
httpServer.requestHandler(request -> {
  if (request.getHeader("Expect").equalsIgnoreCase("100-Continue")) {

    // Send a 100 continue response
    request.response().writeContinue();

    // The client should send the body when it receives the 100 response
    request.bodyHandler(body -> {
      // Do something with body
    });

    request.endHandler(v -> {
      request.response().end();
    });
  }
});
----

You can also reject the request by sending back a failure status code directly: in this case the body
should either be ignored or the connection should be closed (100-Continue is a performance hint and
cannot be a logical protocol constraint):

[source,java]
----
httpServer.requestHandler(request -> {
  if (request.getHeader("Expect").equalsIgnoreCase("100-Continue")) {

    //
    boolean rejectAndClose = true;
    if (rejectAndClose) {

      // Reject with a failure code and close the connection
      // this is probably best with persistent connection
      request.response()
          .setStatusCode(405)
          .putHeader("Connection", "close")
          .end();
    } else {

      // Reject with a failure code and ignore the body
      // this may be appropriate if the body is small
      request.response()
          .setStatusCode(405)
          .end();
    }
  }
});
----

==== Creating HTTP tunnels

HTTP tunnels can be created with `link:../../apidocs/io/vertx/core/http/HttpClientRequest.html#connect--[connect]`:

[source,java]
----
client.request(HttpMethod.CONNECT, "some-uri")
  .onSuccess(request -> {

    // Connect to the server
    request
      .connect()
      .onComplete(ar -> {
        if (ar.succeeded()) {
          HttpClientResponse response = ar.result();

          if (response.statusCode() != 200) {
            // Connect failed for some reason
          } else {
            // Tunnel created, raw buffers are transmitted on the wire
            NetSocket socket = response.netSocket();
          }
        }
      });
});
----

The handler will be called after the HTTP response header is received, the socket will be ready for tunneling
and will send and receive buffers.

`connect` works like `send`, but it reconfigures the transport to exchange
raw buffers.

==== Client push

Server push is a new feature of HTTP/2 that enables sending multiple responses in parallel for a single client request.

A push handler can be set on a request to receive the request/response pushed by the server:

[source,java]
----
client.request(HttpMethod.GET, "/index.html")
  .onSuccess(request -> {

    request
      .response().onComplete(response -> {
        // Process index.html response
      });

    // Set a push handler to be aware of any resource pushed by the server
    request.pushHandler(pushedRequest -> {

      // A resource is pushed for this request
      System.out.println("Server pushed " + pushedRequest.path());

      // Set an handler for the response
      pushedRequest.response().onComplete(pushedResponse -> {
        System.out.println("The response for the pushed request");
      });
    });

    // End the request
    request.end();
});
----

If the client does not want to receive a pushed request, it can reset the stream:

[source,java]
----
request.pushHandler(pushedRequest -> {
  if (pushedRequest.path().equals("/main.js")) {
    pushedRequest.reset();
  } else {
    // Handle it
  }
});
----

When no handler is set, any stream pushed will be automatically cancelled by the client with
a stream reset (`8` error code).

==== Receiving custom HTTP/2 frames

HTTP/2 is a framed protocol with various frames for the HTTP request/response model. The protocol allows other kind of
frames to be sent and received.

To receive custom frames, you can use the customFrameHandler on the request, this will get called every time a custom
frame arrives. Here's an example:

[source,java]
----
response.customFrameHandler(frame -> {

  System.out.println("Received a frame type=" + frame.type() +
      " payload" + frame.payload().toString());
});
----

=== Enabling compression on the client

The http client comes with support for HTTP Compression out of the box.

This means the client can let the remote http server know that it supports compression, and will be able to handle
compressed response bodies.

An http server is free to either compress with one of the supported compression algorithms or to send the body back
without compressing it at all. So this is only a hint for the Http server which it may ignore at will.

To tell the http server which compression is supported by the client it will include an `Accept-Encoding` header with
the supported compression algorithm as value. Multiple compression algorithms are supported. In case of Vert.x this
will result in the following header added:

[source,http]
----
Accept-Encoding: gzip, deflate
----

The server will choose then from one of these. You can detect if a server compressed the body by checking for the
`Content-Encoding` header in the response sent back from it.

If the body of the response was compressed via gzip it will include for example the following header:

[source,http]
----
Content-Encoding: gzip
----

To enable compression set `link:../../apidocs/io/vertx/core/http/HttpClientOptions.html#setDecompressionSupported-boolean-[setDecompressionSupported]` on the options
used when creating the client.

By default compression is disabled.

=== Client side load balancing

By default, when the client resolves a hostname to a list of several IP addresses, the client uses the first returned IP address.

The http client can be configured to perform client side load balancing instead

[source,java]
----
HttpClientAgent client = vertx
  .httpClientBuilder()
  .withLoadBalancer(LoadBalancer.ROUND_ROBIN)
  .build();
----

Vert.x provides out of the box several load balancing policies you can use

- `link:../../apidocs/io/vertx/core/net/endpoint/LoadBalancer.html#ROUND_ROBIN[Round-robin]`
- `link:../../apidocs/io/vertx/core/net/endpoint/LoadBalancer.html#LEAST_REQUESTS[Least requests]`
- `link:../../apidocs/io/vertx/core/net/endpoint/LoadBalancer.html#POWER_OF_TWO_CHOICES[Power of two choices]`
- `link:../../apidocs/io/vertx/core/net/endpoint/LoadBalancer.html#CONSISTENT_HASHING[Consistent hashing]`

Most load balancing policies are pretty much self-explanatory.

Hash based routing can be achieved with the `link:../../apidocs/io/vertx/core/net/endpoint/LoadBalancer.html#CONSISTENT_HASHING[LoadBalancer.CONSISTENT_HASHING]` policy.

[source,java]
----
HttpClientAgent client = vertx
  .httpClientBuilder()
  .withLoadBalancer(LoadBalancer.ROUND_ROBIN)
  .build();
----

The default consistent hashing policy uses 4 virtual nodes per server and uses a random policy in the absence of a routing key.

You can create a policy configuration that best fit your needs

[source,java]
----
LoadBalancer loadBalancer = LoadBalancer.consistentHashing(10, LoadBalancer.POWER_OF_TWO_CHOICES);
----

Custom load balancing policies can also be used.

[source,java]
----
LoadBalancer loadBalancer = endpoints -> {
  // Returns an endpoint selector for the given endpoints
  // a selector is a stateful view of the provided immutable list of endpoints
  return () -> indexOfEndpoint(endpoints);
};

HttpClientAgent client = vertx
  .httpClientBuilder()
  .withLoadBalancer(loadBalancer)
  .build();
----

=== HTTP/1.x pooling and keep alive

Http keep alive allows http connections to be used for more than one request. This can be a more efficient use of
connections when you're making multiple requests to the same server.

For HTTP/1.x versions, the http client supports pooling of connections, allowing you to reuse connections between requests.

For pooling to work, keep alive must be true using `link:../../apidocs/io/vertx/core/http/HttpClientOptions.html#setKeepAlive-boolean-[setKeepAlive]`
on the options used when configuring the client. The default value is true.

When keep alive is enabled. Vert.x will add a `Connection: Keep-Alive` header to each HTTP/1.0 request sent.
When keep alive is disabled. Vert.x will add a `Connection: Close` header to each HTTP/1.1 request sent to signal
that the connection will be closed after completion of the response.

The maximum number of connections to pool *for each server* is configured using `link:../../apidocs/io/vertx/core/http/PoolOptions.html#setHttp1MaxSize-int-[setHttp1MaxSize]`

When making a request with pooling enabled, Vert.x will create a new connection if there are less than the maximum number of
connections already created for that server, otherwise it will add the request to a queue.

Keep alive connections will be closed by the client automatically after a timeout. The timeout can be specified
by the server using the `keep-alive` header:

[source,http]
----
keep-alive: timeout=30
----

You can set the default timeout using `link:../../apidocs/io/vertx/core/http/HttpClientOptions.html#setKeepAliveTimeout-int-[setKeepAliveTimeout]` - any
connections not used within this timeout will be closed. Please note the timeout value is in seconds not milliseconds.

=== HTTP/1.1 pipe-lining

The client also supports pipe-lining of requests on a connection.

Pipe-lining means another request is sent on the same connection before the response from the preceding one has
returned. Pipe-lining is not appropriate for all requests.

To enable pipe-lining, it must be enabled using `link:../../apidocs/io/vertx/core/http/HttpClientOptions.html#setPipelining-boolean-[setPipelining]`.
By default, pipe-lining is disabled.

When pipe-lining is enabled requests will be written to connections without waiting for previous responses to return.

The number of pipe-lined requests over a single connection is limited by `link:../../apidocs/io/vertx/core/http/HttpClientOptions.html#setPipeliningLimit-int-[setPipeliningLimit]`.
This option defines the maximum number of http requests sent to the server awaiting for a response. This limit ensures the
fairness of the distribution of the client requests over the connections to the same server.

=== HTTP/2 multiplexing

HTTP/2 advocates to use a single connection to a server, by default the http client uses a single
connection for each server, all the streams to the same server are multiplexed over the same connection.

When the client needs to use more than a single connection and use pooling, the `link:../../apidocs/io/vertx/core/http/PoolOptions.html#setHttp2MaxSize-int-[setHttp2MaxSize]`
shall be used.

When it is desirable to limit the number of multiplexed streams per connection and use a connection
pool instead of a single connection, `link:../../apidocs/io/vertx/core/http/HttpClientOptions.html#setHttp2MultiplexingLimit-int-[setHttp2MultiplexingLimit]`
can be used.

[source,java]
----
HttpClient client = vertx.createHttpClient(
  new HttpClientOptions().setHttp2MultiplexingLimit(10),
  new PoolOptions().setHttp2MaxSize(3)
);
----

The multiplexing limit for a connection is a setting set on the client that limits the number of streams
of a single connection. The effective value can be even lower if the server sets a lower limit
with the `link:../../apidocs/io/vertx/core/http/Http2Settings.html#setMaxConcurrentStreams-long-[SETTINGS_MAX_CONCURRENT_STREAMS]` setting.

HTTP/2 connections will not be closed by the client automatically. To close them you can call `link:../../apidocs/io/vertx/core/http/HttpConnection.html#close--[close]`
or close the client instance.

Alternatively you can set idle timeout using `link:../../apidocs/io/vertx/core/http/HttpClientOptions.html#setIdleTimeout-int-[setIdleTimeout]` - any
connections not used within this timeout will be closed. Please note the idle timeout value is in seconds not milliseconds.

=== Un-pooled client connections

Most HTTP interactions are performed using {@code HttpClientAgent} request/response API: the client obtains
a connection from its pool of connections to perform a request.

Alternatively, you can connect directly to a server (bypassing the connection pool) and get an HTTP client connection.

[source,java]
----
HttpConnectOptions connectOptions = new HttpConnectOptions()
  .setHost("example.com")
  .setPort(80);

Future<HttpClientConnection> fut = client.connect(connectOptions);
----

The `link:../../apidocs/io/vertx/core/http/HttpClientConnection.html[HttpClientConnection]` can create `link:../../apidocs/io/vertx/core/http/HttpClientRequest.html[HttpClientRequest]`:

[source,java]
----
connection
  .request()
  .onSuccess(request -> {
    request.setMethod(HttpMethod.GET);
    request.setURI("/some-uri");
    Future<HttpClientResponse> response = request.send();
  });
----

A client connection can handle a certain amount of concurrent requests. When the max number of connection is reached, any subsequent request is queued until a slot is available.

=== HTTP connections

The `link:../../apidocs/io/vertx/core/http/HttpConnection.html[HttpConnection]` offers the API for dealing with HTTP connection events, lifecycle
and settings.

HTTP/2 implements fully the `link:../../apidocs/io/vertx/core/http/HttpConnection.html[HttpConnection]` API.

HTTP/1.x implements partially the `link:../../apidocs/io/vertx/core/http/HttpConnection.html[HttpConnection]` API: only the close operation,
the close handler and exception handler are implemented. This protocol does not provide semantics for
the other operations.

==== Server connections

The `link:../../apidocs/io/vertx/core/http/HttpServerRequest.html#connection--[connection]` method returns the request connection on the server:

[source,java]
----
HttpConnection connection = request.connection();
----

A connection handler can be set on the server to be notified of any incoming connection:

[source,java]
----
HttpServer server = vertx.createHttpServer(http2Options);

server.connectionHandler(connection -> {
  System.out.println("A client connected");
});
----

==== Client connections

The `link:../../apidocs/io/vertx/core/http/HttpClientRequest.html#connection--[connection]` method returns the request connection on the client:

[source,java]
----
HttpConnection connection = request.connection();
----

A connection handler can be set on a client builder to be notified when a connection has been established happens:

[source,java]
----
vertx
  .httpClientBuilder()
  .with(options)
  .withConnectHandler(connection -> {
    System.out.println("Connected to the server");
  })
  .build();
----

==== Connection settings

The configuration of an HTTP/2 is configured by the `link:../../apidocs/io/vertx/core/http/Http2Settings.html[Http2Settings]` data object.

Each endpoint must respect the settings sent by the other side of the connection.

When a connection is established, the client and the server exchange initial settings. Initial settings
are configured by `link:../../apidocs/io/vertx/core/http/HttpClientOptions.html#setInitialSettings-io.vertx.core.http.Http2Settings-[setInitialSettings]` on the client and
`link:../../apidocs/io/vertx/core/http/HttpServerOptions.html#setInitialSettings-io.vertx.core.http.Http2Settings-[setInitialSettings]` on the server.

The settings can be changed at any time after the connection is established:

[source,java]
----
connection.updateSettings(new Http2Settings().setMaxConcurrentStreams(100));
----

As the remote side should acknowledge on reception of the settings update, it's possible to give a callback
to be notified of the acknowledgment:

[source,java]
----
connection
  .updateSettings(new Http2Settings().setMaxConcurrentStreams(100))
  .onSuccess(v -> System.out.println("The settings update has been acknowledged "));
----

Conversely the `link:../../apidocs/io/vertx/core/http/HttpConnection.html#remoteSettingsHandler-io.vertx.core.Handler-[remoteSettingsHandler]` is notified
when the new remote settings are received:

[source,java]
----
connection.remoteSettingsHandler(settings -> {
  System.out.println("Received new settings");
});
----

NOTE: this only applies to the HTTP/2 protocol

==== Connection ping

HTTP/2 connection ping is useful for determining the connection round-trip time or check the connection
validity: `link:../../apidocs/io/vertx/core/http/HttpConnection.html#ping-io.vertx.core.buffer.Buffer-[ping]` sends a `PING` frame to the remote
endpoint:

[source,java]
----
Buffer data = Buffer.buffer();
for (byte i = 0;i < 8;i++) {
  data.appendByte(i);
}
connection
  .ping(data)
  .onSuccess(pong -> System.out.println("Remote side replied"));
----

Vert.x will send automatically an acknowledgement when a `PING` frame is received,
an handler can be set to be notified for each ping received:

[source,java]
----
connection.pingHandler(ping -> {
  System.out.println("Got pinged by remote side");
});
----

The handler is just notified, the acknowledgement is sent whatsoever. Such feature is aimed for
implementing  protocols on top of HTTP/2.

NOTE: this only applies to the HTTP/2 protocol

==== Connection shutdown and go away

Calling `link:../../apidocs/io/vertx/core/http/HttpConnection.html#shutdown--[shutdown]` will send a `GOAWAY` frame to the
remote side of the connection, asking it to stop creating streams: a client will stop doing new requests
and a server will stop pushing responses. After the `GOAWAY` frame is sent, the connection
waits some time (30 seconds by default) until all current streams closed and close the connection:

[source,java]
----
connection.shutdown();
----

The `link:../../apidocs/io/vertx/core/http/HttpConnection.html#shutdownHandler-io.vertx.core.Handler-[shutdownHandler]` notifies when all streams have been closed, the
connection is not yet closed.

It's possible to just send a `GOAWAY` frame, the main difference with a shutdown is that
it will just tell the remote side of the connection to stop creating new streams without scheduling a connection
close:

[source,java]
----
connection.goAway(0);
----

Conversely, it is also possible to be notified when `GOAWAY` are received:

[source,java]
----
connection.goAwayHandler(goAway -> {
  System.out.println("Received a go away frame");
});
----

The `link:../../apidocs/io/vertx/core/http/HttpConnection.html#shutdownHandler-io.vertx.core.Handler-[shutdownHandler]` will be called when all current streams
have been closed and the connection can be closed:

[source,java]
----
connection.goAway(0);
connection.shutdownHandler(v -> {

  // All streams are closed, close the connection
  connection.close();
});
----

This applies also when a `GOAWAY` is received.

NOTE: this only applies to the HTTP/2 protocol

==== Connection close

Connection `link:../../apidocs/io/vertx/core/http/HttpConnection.html#close--[close]` closes the connection:

- it closes the socket for HTTP/1.x
- a shutdown with no delay for HTTP/2, the `GOAWAY` frame will still be sent before the connection is closed.

The `link:../../apidocs/io/vertx/core/http/HttpConnection.html#closeHandler-io.vertx.core.Handler-[closeHandler]` notifies when a connection is closed.

=== Graceful shutdown

HTTP server and client support graceful shutdown.

You can shut down a `link:../../apidocs/io/vertx/core/http/HttpServer.html#shutdown--[server]` or `link:../../apidocs/io/vertx/core/http/HttpClient.html#shutdown--[client]`.

Calling `shutdown` initiates the shut-down phase whereby the server or client are given the opportunity to perform clean-up actions.

- A standalone HTTP server unbinds
- A shared HTTP server is removed from the set of accepting servers
- An HTTP client refuses to send any new requests

When all connections inflight requests are processed, the server or client is then closed.

In addition, HTTP/2 connections send a `GOAWAY` frame to signal the remote endpoint that the connection cannot be used anymore.

[source,java]
----
server
  .shutdown()
  .onSuccess(res -> {
    System.out.println("Server is now closed");
  });
----

Shut-down waits until all sockets are closed or the shut-down timeout fires. When the timeout fires, all sockets are
forcibly closed.

Each opened HTTP connections is notified with a shutdown event, allowing to perform cleanup before the
actual connection is closed.

[source,java]
----
server.connectionHandler(conn -> {
  conn.shutdownHandler(v -> {
    // Perform clean-up
  });
});
----

The default shut-down timeout is 30 seconds, you can override the timeout

[source,java]
----
server
  .shutdown(60, TimeUnit.SECONDS)
  .onSuccess(res -> {
    System.out.println("Server is now closed");
  });
----


=== Client sharing

You can share an HTTP client between multiple verticles or instances of the same verticle. Such client should be created outside
of a verticle otherwise it will be closed when the verticle that created it is undeployed

[source,java]
----
HttpClientAgent client = vertx.createHttpClient(new HttpClientOptions().setShared(true));
vertx.deployVerticle(() -> new AbstractVerticle() {
  @Override
  public void start() throws Exception {
    // Use the client
  }
}, new DeploymentOptions().setInstances(4));
----

You can also create a shared HTTP client in each verticle:

[source,java]
----
vertx.deployVerticle(() -> new AbstractVerticle() {
  HttpClientAgent client;
  @Override
  public void start() {
    // Get or create a shared client
    // this actually creates a lease to the client
    // when the verticle is undeployed, the lease will be released automaticaly
    client = vertx.createHttpClient(new HttpClientOptions().setShared(true).setName("my-client"));
  }
}, new DeploymentOptions().setInstances(4));
----

The first time a shared client is created it will create and return a client. Subsequent calls will reuse this client and
create a lease to this client. The client is closed after all leases have been disposed.

By default, a client reuses the current event-loop when it needs to create a TCP connection. The HTTP client will
therefore randomly use event-loops of verticles using it in a safe fashion.

You can assign a number of event loop a client will use independently of the client using it

[source,java]
----
vertx.deployVerticle(() -> new AbstractVerticle() {
  HttpClientAgent client;
  @Override
  public void start() {
    // The client creates and use two event-loops for 4 instances
    client = vertx.createHttpClient(new HttpClientOptions().setShared(true).setName("my-client"), new PoolOptions().setEventLoopSize(2));
  }
}, new DeploymentOptions().setInstances(4));
----

=== Server sharing

When several HTTP servers listen on the same port, vert.x orchestrates the request handling using a
round-robin strategy.

Let's take a verticle creating an HTTP server such as:

.io.vertx.examples.http.sharing.HttpServerVerticle
[source,java]
----
vertx.createHttpServer().requestHandler(request -> {
  request.response().end("Hello from server " + this);
}).listen(8080);
----

This service is listening on the port 8080.

So, when this verticle is instantiated multiple times as with: `deploymentOptions.setInstances(2)`, what's happening ?
If both verticles bound to the same port, you would receive a socket exception.
Fortunately, vert.x is handling this case for you.
When you deploy another server on the same host and port as an existing server it doesn't actually try and create a new server listening on the same host/port.
It binds only once to the socket.
When receiving a request it calls the server handlers following a round-robin strategy.

Let's now imagine a client such as:

[source,java]
----
vertx.setPeriodic(100, (l) -> {
  vertx
    .createHttpClient()
    .request(HttpMethod.GET, 8080, "localhost", "/")
    .onComplete(ar1 -> {
      if (ar1.succeeded()) {
        HttpClientRequest request = ar1.result();
        request
          .send()
          .onComplete(ar2 -> {
            if (ar2.succeeded()) {
              HttpClientResponse resp = ar2.result();
              resp.bodyHandler(body -> {
                System.out.println(body.toString("ISO-8859-1"));
              });
            }
          });
      }
    });
});
----

Vert.x delegates the requests to one of the server sequentially:

[source]
----
Hello from i.v.e.h.s.HttpServerVerticle@1
Hello from i.v.e.h.s.HttpServerVerticle@2
Hello from i.v.e.h.s.HttpServerVerticle@1
Hello from i.v.e.h.s.HttpServerVerticle@2
...
----

Consequently the servers can scale over available cores while each Vert.x verticle instance remains strictly
single threaded, and you don't have to do any special tricks like writing load-balancers in order to scale your
server on your multi-core machine.

You can bind on a shared random ports using a negative port value, the first bind will pick a port randomly, subsequent binds
on the same port value will share this random port.

.io.vertx.examples.http.sharing.HttpServerVerticle
[source,java]
----
vertx.createHttpServer().requestHandler(request -> {
  request.response().end("Hello from server " + this);
}).listen(-1);
----

=== Using HTTPS with Vert.x

Vert.x http servers and clients can be configured to use HTTPS in exactly the same way as net servers.

Please see <<ssl, configuring net servers to use SSL>> for more information.

SSL can also be enabled/disabled per request with `link:../../apidocs/io/vertx/core/http/RequestOptions.html[RequestOptions]` or when
specifying a scheme with `link:../../apidocs/io/vertx/core/http/RequestOptions.html#setAbsoluteURI-java.lang.String-[setAbsoluteURI]`
method.

[source,java]
----
client
  .request(new RequestOptions()
    .setHost("localhost")
    .setPort(8080)
    .setURI("/")
    .setSsl(true))
  .onComplete(ar1 -> {
    if (ar1.succeeded()) {
      HttpClientRequest request = ar1.result();
      request
        .send()
        .onComplete(ar2 -> {
          if (ar2.succeeded()) {
            HttpClientResponse response = ar2.result();
            System.out.println("Received response with status code " + response.statusCode());
          }
        });
    }
  });
----

The `link:../../apidocs/io/vertx/core/http/HttpClientOptions.html#setSsl-boolean-[setSsl]` setting acts as the default client setting.

The `link:../../apidocs/io/vertx/core/http/RequestOptions.html#setSsl-java.lang.Boolean-[setSsl]` overrides the default client setting

* setting the value to `false` will disable SSL/TLS even if the client is configured to use SSL/TLS
* setting the value to `true` will enable SSL/TLS  even if the client is configured to not use SSL/TLS, the actual
client SSL/TLS (such as trust, key/certificate, ciphers, ALPN, ...) will be reused

Likewise `link:../../apidocs/io/vertx/core/http/RequestOptions.html#setAbsoluteURI-java.lang.String-[setAbsoluteURI]` scheme
also overrides the default client setting.

==== Server Name Indication (SNI)

Vert.x http servers can be configured to use SNI in exactly the same way as {@linkplain io.vertx.core.net net servers}.

Vert.x http client will present the actual hostname as _server name_ during the TLS handshake.

=== WebSockets

http://en.wikipedia.org/wiki/WebSocket[WebSockets] are a web technology that allows a full duplex socket-like
connection between HTTP servers and HTTP clients (typically browsers).

Vert.x supports WebSockets on both the client and server-side.

==== WebSockets on the server

There are two ways of handling WebSockets on the server side.

===== WebSocket handler

The first way involves providing a `link:../../apidocs/io/vertx/core/http/HttpServer.html#webSocketHandler-io.vertx.core.Handler-[webSocketHandler]`
on the server instance.

When a WebSocket connection is made to the server, the handler will be called, passing in an instance of
`link:../../apidocs/io/vertx/core/http/ServerWebSocket.html[ServerWebSocket]`.

[source,java]
----
server.webSocketHandler(webSocket -> {
  System.out.println("Connected!");
});
----

===== Server WebSocket handshake

By default, the server accepts any inbound WebSocket.

You can set a WebSocket handshake handler to control the outcome of a WebSocket handshake, i.e. accept or reject an incoming WebSocket.

You can choose to reject the WebSocket by calling `link:../../apidocs/io/vertx/core/http/ServerWebSocketHandshake.html#accept--[accept]` or `link:../../apidocs/io/vertx/core/http/ServerWebSocketHandshake.html#reject--[reject]`.

[source,java]
----
server.webSocketHandshakeHandler(handshake -> {
  authenticate(handshake.headers(), ar -> {
    if (ar.succeeded()) {
      if (ar.result()) {
        // Terminate the handshake with the status code 101 (Switching Protocol)
        handshake.accept();
      } else {
        // Reject the handshake with 401 (Unauthorized)
        handshake.reject(401);
      }
    } else {
      // Will send a 500 error
      handshake.reject(500);
    }
  });
});
----

NOTE: the WebSocket will be automatically accepted after the handler is called unless the WebSocket's handshake has been set

===== Upgrading to WebSocket

The second way of handling WebSockets is to handle the HTTP Upgrade request that was sent from the client, and
call `link:../../apidocs/io/vertx/core/http/HttpServerRequest.html#toWebSocket--[toWebSocket]` on the server request.

[source,java]
----
server.requestHandler(request -> {
  if (request.path().equals("/myapi")) {

    Future<ServerWebSocket> fut = request.toWebSocket();
    fut.onSuccess(ws -> {
      // Do something
    });

  } else {
    // Reject
    request.response().setStatusCode(400).end();
  }
});
----

===== The server WebSocket

The `link:../../apidocs/io/vertx/core/http/ServerWebSocket.html[ServerWebSocket]` instance enables you to retrieve the `link:../../apidocs/io/vertx/core/http/WebSocketBase.html#headers--[headers]`,
`link:../../apidocs/io/vertx/core/http/ServerWebSocket.html#path--[path]`, `link:../../apidocs/io/vertx/core/http/ServerWebSocket.html#query--[query]` and
`link:../../apidocs/io/vertx/core/http/ServerWebSocket.html#uri--[URI]` of the HTTP request of the WebSocket handshake.

==== WebSockets on the client

e Vert.x `link:../../apidocs/io/vertx/core/http/WebSocketClient.html[WebSocketClient]` supports WebSockets.

 You can connect a WebSocket to a server using one of the `link:../../apidocs/io/vertx/core/http/WebSocketClient.html#connect-int-java.lang.String-java.lang.String-[connect]` operations.

 The returned future will be completed with an instance of `link:../../apidocs/io/vertx/core/http/WebSocket.html[WebSocket]` when the connection has been made:
[source,java]
----
WebSocketClient client = vertx.createWebSocketClient();

client
  .connect(80, "example.com", "/some-uri")
  .onComplete(res -> {
    if (res.succeeded()) {
      WebSocket ws = res.result();
      ws.textMessageHandler(msg -> {
        // Handle msg
      });
      System.out.println("Connected!");
    }
  });
----

en connecting from a non Vert.x thread, you can create a `link:../../apidocs/io/vertx/core/http/ClientWebSocket.html[ClientWebSocket]`, configure its handlers and
then connect to the server:

 [source,java]
 ----
 WebSocketClient client = vertx.createWebSocketClient();

client
  .webSocket()
  .textMessageHandler(msg -> {
    // Handle msg
  })
  .connect(80, "example.com", "/some-uri")
  .onComplete(res -> {
    if (res.succeeded()) {
      WebSocket ws = res.result();
    }
  });
 ----

By default, the client sets the `origin` header to the server host, e.g http://www.example.com. Some servers will refuse
such request, you can configure the client to not set this header.

[source,java]
----
WebSocketConnectOptions options = new WebSocketConnectOptions()
  .setHost(host)
  .setPort(port)
  .setURI(requestUri)
  .setAllowOriginHeader(false);
client
  .connect(options)
  .onComplete(res -> {
    if (res.succeeded()) {
      WebSocket ws = res.result();
      System.out.println("Connected!");
    }
  });
----

You can also set a different header:

[source,java]
----
WebSocketConnectOptions options = new WebSocketConnectOptions()
  .setHost(host)
  .setPort(port)
  .setURI(requestUri)
  .addHeader(HttpHeaders.ORIGIN, origin);
client
  .connect(options)
  .onComplete(res -> {
    if (res.succeeded()) {
      WebSocket ws = res.result();
      System.out.println("Connected!");
    }
  });
----

NOTE: older versions of the WebSocket protocol use `sec-websocket-origin` instead

==== Writing messages to WebSockets

If you wish to write a single WebSocket message to the WebSocket you can do this with
`link:../../apidocs/io/vertx/core/http/WebSocketBase.html#writeBinaryMessage-io.vertx.core.buffer.Buffer-[writeBinaryMessage]` or
`link:../../apidocs/io/vertx/core/http/WebSocketBase.html#writeTextMessage-java.lang.String-[writeTextMessage]` :

[source,java]
----
Buffer buffer = Buffer.buffer().appendInt(123).appendFloat(1.23f);
webSocket.writeBinaryMessage(buffer);

// Write a simple text message
String message = "hello";
webSocket.writeTextMessage(message);
----

If the WebSocket message is larger than the maximum WebSocket frame size as configured with
`link:../../apidocs/io/vertx/core/http/WebSocketClientOptions.html#setMaxFrameSize-int-[setMaxFrameSize]`
then Vert.x will split it into multiple WebSocket frames before sending it on the wire.

==== Writing frames to WebSockets

A WebSocket message can be composed of multiple frames. In this case the first frame is either a _binary_ or _text_ frame
followed by zero or more _continuation_ frames.

The last frame in the message is marked as _final_.

To send a message consisting of multiple frames you create frames using
`link:../../apidocs/io/vertx/core/http/WebSocketFrame.html#binaryFrame-io.vertx.core.buffer.Buffer-boolean-[WebSocketFrame.binaryFrame]`
, `link:../../apidocs/io/vertx/core/http/WebSocketFrame.html#textFrame-java.lang.String-boolean-[WebSocketFrame.textFrame]` or
`link:../../apidocs/io/vertx/core/http/WebSocketFrame.html#continuationFrame-io.vertx.core.buffer.Buffer-boolean-[WebSocketFrame.continuationFrame]` and write them
to the WebSocket using `link:../../apidocs/io/vertx/core/http/WebSocketBase.html#writeFrame-io.vertx.core.http.WebSocketFrame-[writeFrame]`.

Here's an example for binary frames:

[source,java]
----
WebSocketFrame frame1 = WebSocketFrame.binaryFrame(buffer1, false);
webSocket.writeFrame(frame1);

WebSocketFrame frame2 = WebSocketFrame.continuationFrame(buffer2, false);
webSocket.writeFrame(frame2);

// Write the final frame
WebSocketFrame frame3 = WebSocketFrame.continuationFrame(buffer2, true);
webSocket.writeFrame(frame3);
----

In many cases you just want to send a WebSocket message that consists of a single final frame, so we provide a couple
of shortcut methods to do that with `link:../../apidocs/io/vertx/core/http/WebSocketBase.html#writeFinalBinaryFrame-io.vertx.core.buffer.Buffer-[writeFinalBinaryFrame]`
and `link:../../apidocs/io/vertx/core/http/WebSocketBase.html#writeFinalTextFrame-java.lang.String-[writeFinalTextFrame]`.

Here's an example:

[source,java]
----
webSocket.writeFinalTextFrame("Geronimo!");

// Send a WebSocket message consisting of a single final binary frame:

Buffer buff = Buffer.buffer().appendInt(12).appendString("foo");

webSocket.writeFinalBinaryFrame(buff);
----

==== Reading frames from WebSockets

To read frames from a WebSocket you use the `link:../../apidocs/io/vertx/core/http/WebSocket.html#frameHandler-io.vertx.core.Handler-[frameHandler]`.

The frame handler will be called with instances of `link:../../apidocs/io/vertx/core/http/WebSocketFrame.html[WebSocketFrame]` when a frame arrives,
for example:

[source,java]
----
webSocket.frameHandler(frame -> {
  System.out.println("Received a frame of size!");
});
----

==== Closing WebSockets

Use `link:../../apidocs/io/vertx/core/http/WebSocketBase.html#close--[close]` to close the WebSocket connection when you have finished with it.

==== Piping WebSockets

The `link:../../apidocs/io/vertx/core/http/WebSocket.html[WebSocket]` instance is also a `link:../../apidocs/io/vertx/core/streams/ReadStream.html[ReadStream]` and a
`link:../../apidocs/io/vertx/core/streams/WriteStream.html[WriteStream]` so it can be used with pipes.

When using a WebSocket as a write stream or a read stream it can only be used with WebSockets connections that are
used with binary frames that are no split over multiple frames.

==== Event bus handlers

Every WebSocket can register two handlers on the event bus, and when any data are received in these handlers,
it writes the data to itself. Those are local subscriptions, not reachable from other clustered nodes.

This enables you to write data to a WebSocket which is potentially in a completely different verticle sending data
to the address of that handler.

This feature is disabled by default, however you can enable it using `link:../../apidocs/io/vertx/core/http/HttpServerOptions.html#setRegisterWebSocketWriteHandlers-boolean-[setRegisterWebSocketWriteHandlers]` or `link:../../apidocs/io/vertx/core/http/WebSocketConnectOptions.html#setRegisterWriteHandlers-boolean-[setRegisterWriteHandlers]`.

The addresses of the handlers are given by `link:../../apidocs/io/vertx/core/http/WebSocketBase.html#binaryHandlerID--[binaryHandlerID]` and
`link:../../apidocs/io/vertx/core/http/WebSocketBase.html#textHandlerID--[textHandlerID]`.

=== Using a proxy for HTTP/HTTPS connections

The http client supports accessing http/https URLs via an HTTP proxy (e.g. Squid) or _SOCKS4a_ or _SOCKS5_ proxy.
The CONNECT protocol uses HTTP/1.x but can connect to HTTP/1.x and HTTP/2 servers.

Connecting to h2c (unencrypted HTTP/2 servers) is likely not supported by http proxies since they will support
HTTP/1.1 only.

The proxy can be configured in the `link:../../apidocs/io/vertx/core/http/HttpClientOptions.html[HttpClientOptions]` by setting a
`link:../../apidocs/io/vertx/core/net/ProxyOptions.html[ProxyOptions]` object containing proxy type, hostname, port and optionally username and password.

Here's an example of using an HTTP proxy:

[source,java]
----
HttpClientOptions options = new HttpClientOptions()
    .setProxyOptions(new ProxyOptions().setType(ProxyType.HTTP)
        .setHost("localhost").setPort(3128)
        .setUsername("username").setPassword("secret"));
HttpClientAgent client = vertx.createHttpClient(options);
----

When the client connects to an http URL, it connects to the proxy server and provides the full URL in the
HTTP request ("GET http://www.somehost.com/path/file.html HTTP/1.1").

When the client connects to an https URL, it asks the proxy to create a tunnel to the remote host with
the CONNECT method.

For a SOCKS5 proxy:

[source,java]
----
HttpClientOptions options = new HttpClientOptions()
    .setProxyOptions(new ProxyOptions().setType(ProxyType.SOCKS5)
        .setHost("localhost").setPort(1080)
        .setUsername("username").setPassword("secret"));
HttpClientAgent client = vertx.createHttpClient(options);
----

The DNS resolution is always done on the proxy server, to achieve the functionality of a SOCKS4 client, it is necessary
to resolve the DNS address locally.

Proxy options can also be set per request:

[source,java]
----
client.request(new RequestOptions()
  .setHost("example.com")
  .setProxyOptions(proxyOptions))
  .compose(request -> request
    .send()
    .compose(HttpClientResponse::body))
  .onSuccess(body -> {
    System.out.println("Received response");
  });
----

NOTE: client connection pooling is aware of proxies (including authentication), consequently two requests to the same host through different proxies
do not share the same pooled connection

You can use `link:../../apidocs/io/vertx/core/http/HttpClientOptions.html#setNonProxyHosts-java.util.List-[setNonProxyHosts]` to configure a list of host bypassing
the proxy. The lists accept `*` wildcard for matching domains:

[source,java]
----
HttpClientOptions options = new HttpClientOptions()
  .setProxyOptions(new ProxyOptions().setType(ProxyType.SOCKS5)
    .setHost("localhost").setPort(1080)
    .setUsername("username").setPassword("secret"))
  .addNonProxyHost("*.foo.com")
  .addNonProxyHost("localhost");
HttpClientAgent client = vertx.createHttpClient(options);
----

==== Handling of other protocols

The HTTP proxy implementation supports getting ftp:// urls if the proxy supports
that.

When the HTTP request URI contains the full URL then the client will not compute a full HTTP url and instead
use the full URL specified in the request URI:

[source,java]
----
HttpClientOptions options = new HttpClientOptions()
    .setProxyOptions(new ProxyOptions().setType(ProxyType.HTTP));
HttpClientAgent client = vertx.createHttpClient(options);
client
  .request(HttpMethod.GET, "ftp://ftp.gnu.org/gnu/")
  .onComplete(ar -> {
    if (ar.succeeded()) {
      HttpClientRequest request = ar.result();
      request
        .send()
        .onComplete(ar2 -> {
          if (ar2.succeeded()) {
            HttpClientResponse response = ar2.result();
            System.out.println("Received response with status code " + response.statusCode());
          }
        });
    }
  });
----

=== Using HA PROXY protocol

https://www.haproxy.org/download/1.8/doc/proxy-protocol.txt[HA PROXY protocol] provides a convenient way to safely transport connection
information such as a client's address across multiple layers of NAT or TCP
proxies.

HA PROXY protocol can be enabled by setting the option `link:../../apidocs/io/vertx/core/http/HttpServerOptions.html#setUseProxyProtocol-boolean-[setUseProxyProtocol]`
and adding the following dependency in your classpath:

[source,xml]
----
<dependency>
  <groupId>io.netty</groupId>
  <artifactId>netty-codec-haproxy</artifactId>
  <!--<version>Should align with netty version that Vert.x uses</version>-->
</dependency>
----

[source,java]
----
HttpServerOptions options = new HttpServerOptions()
  .setUseProxyProtocol(true);

HttpServer server = vertx.createHttpServer(options);
server.requestHandler(request -> {
  // Print the actual client address provided by the HA proxy protocol instead of the proxy address
  System.out.println(request.remoteAddress());

  // Print the address of the proxy
  System.out.println(request.localAddress());
});
----

=== Automatic clean-up in verticles

If you're creating http servers and clients from inside verticles, those servers and clients will be automatically closed
when the verticle is undeployed.