How to get both HTTP response body and Status when using Reactor Netty HTTP Client

Viewed 2771

I am using the Reactor Netty HTTP client here as a stand alone dependency, ie not via spring-webflux because I do not want to drag in Spring related dependencies

As can be seen from the documentation it is possible to make a request that returns HttpClientResponse

import reactor.netty.http.client.HttpClient;
import reactor.netty.http.client.HttpClientResponse;

public class Application {

    public static void main(String[] args) {
        HttpClientResponse response =
                HttpClient.create()                   
                          .get()                      
                          .uri("http://example.com/") 
                          .response()                 
                          .block();
    }
}

Thing is HttpClientResponse only contains the headers and the staus. As can be seen from its Java Docs here

Also from the example to consume data one can do

import reactor.netty.http.client.HttpClient;

public class Application {

    public static void main(String[] args) {
        String response =
                HttpClient.create()
                          .get()
                          .uri("http://example.com/")
                          .responseContent() 
                          .aggregate()       
                          .asString()        
                          .block();
    }
}

But this only returns the http entity data as string. No information about the headers nor status code.

The problem I have now is I need to make a request and get a response that gives me both the headers, status etc alongside with the http response body.

I cannot seem to find how. Any ideas?qw

2 Answers

Take a look at the following methods:

They allow you to access response body, status, and http headers simultaneously.

For example using the responseSingle method you can do the following:

private Mono<Foo> getFoo() {
    return httpClient.get()
            .uri("foos/1")
            .responseSingle(
                    (response, bytes) ->
                            bytes.asString()
                                    .map(it -> new Foo(response.status().code(), it))
            );
}

The code above translates the response into some domain object Foo defined as follows:

public static class Foo {
    int status;
    String response;

    public Foo(int status, String response) {
        this.status = status;
        this.response = response;
    }
}

The Foo object is null when the http response does not have a body. For example, if HttpStatus 403 is returned, the Foo object is null. I was able to check response code and return just status.

(resp, bytes)-> {
  if (resp.status().code()=HttpResponseStatus.OK.code) {
        return bytes.asString().map(it->new Foo(resp.status(),it);
  } else {
        return Mono.just(new Foo(resp.status());
  }
}
Related