RxJava 3 API
The RxJava HttpRequest
provides an rx-ified version of the original API,
the rxSend
method returns a Single<HttpResponse<Buffer>>
that
makes the HTTP request upon subscription, as consequence, the Single
can be subscribed many times.
Single<HttpResponse<Buffer>> single = client
.get(8080, "myserver.mycompany.com", "/some-uri")
.rxSend();
// Send a request upon subscription of the Single
single.subscribe(response -> System.out.println("Received 1st response with status code" + response.statusCode()), error -> System.out.println("Something went wrong " + error.getMessage()));
// Send another request
single.subscribe(response -> System.out.println("Received 2nd response with status code" + response.statusCode()), error -> System.out.println("Something went wrong " + error.getMessage()));
The obtained Single
can be composed and chained naturally with the RxJava API
Single<String> url = client
.get(8080, "myserver.mycompany.com", "/some-uri")
.rxSend()
.map(HttpResponse::bodyAsString);
// Use the flatMap operator to make a request on the URL Single
url
.flatMap(u -> client.getAbs(u).rxSend())
.subscribe(response -> System.out.println("Received response with status code" + response.statusCode()), error -> System.out.println("Something went wrong " + error.getMessage()));
The same APIs are available:
Single<HttpResponse<JsonObject>> single = client
.get(8080, "myserver.mycompany.com", "/some-uri")
.putHeader("some-header", "header-value")
.addQueryParam("some-param", "param value")
.as(BodyCodec.jsonObject())
.rxSend();
single.subscribe(resp -> {
System.out.println(resp.statusCode());
System.out.println(resp.body());
});
The rxSendStream
shall be preferred for sending bodies Flowable<Buffer>
.
Flowable<Buffer> body = getPayload();
Single<HttpResponse<Buffer>> single = client
.post(8080, "myserver.mycompany.com", "/some-uri")
.rxSendStream(body);
single.subscribe(resp -> {
System.out.println(resp.statusCode());
System.out.println(resp.body());
});
Upon subscription, the body
will be subscribed and its content used for the request.
HTTP Response Expectations
Interacting with an HTTP backend often involves verifying HTTP response codes and/or content types.
To streamline the process of verification, use the HttpResponseExpectation
methods:
Single<HttpResponse<Buffer>> single = client
.get(8080, "myserver.mycompany.com", "/some-uri")
.rxSend()
// Transforms the single into a failed single if the HTTP response is not successful
.compose(HttpResponseExpectation.status(200))
// Transforms the single into a failed single if the HTTP response content is not JSON
.compose(HttpResponseExpectation.contentType("application/json"));