HttpResponse

When you send an HttpRequest instance using an HttpClient instance, you receive HttpResponse. Upon sending an HTTP request, a server typically returns the status code of the response, the response header, and the response body.

So, when can you access the response body? It depends on the BodyHandler that you specify to be used, when you send the request using the HttpClient send() or sendAsync() methods. Depending on the specified BodyHandler, you might be able to access the response body after the response status code and header are available (and before the response body is made available).

Let's revisit the first example from this chapter:

HttpClient client = HttpClient.newHttpClient();        
 
HttpRequest request = HttpRequest.newBuilder()         
                       .uri(URI.create("http://google.com/"))   
                       .build();                                       
 
HttpResponse<String> response = client.send(request, HttpResponse.
BodyHandlers.ofString()); System.out.println(response.body());

In the preceding example, the send() method specifies BodyHandler as BodyHandlers.ofString(). It converts the received response body bytes to a high-level Java type: string. You can also use BodyHandlers.ofFile(), BodyHandlers.ofInputStream(), or BodyHandlers.discard() to save the response to a file, use the response as an input stream, or discard it.

BodyHandler is a static interface defined within the HttpResponse interface. HttpResponse also defines a static class, BodyHandler, which defines a varied and useful implementation of the BodyHandler interface. For example, you could use BodyHandlers.ofFile() to write the received response to the specified file. Behind the scenes, BodyHandler uses BodySubscriber (a Reactive Stream), which subscribes to the response bytes from the server.

The convenient static methods of BodyHandlers (ofFile(), ofString(), ofInputStream(), and discard()) let you work with a reactive data stream: BodySubscriber.

Here's a list of the important methods of the HttpResponse interface: 

Method Return Type

Method Name

Method Description

T

body()

Returns the body

HttpHeaders

headers()

Returns the received response headers

Optional<HttpResponse<T>>

previousResponse()

Returns Optional containing the previous intermediate response, if one was received

HttpRequest

request()

Returns the HttpRequest instance corresponding to this response

Optional<SSLSession>

sslSession()

Returns Optional containing the SSLSession instance in effect for this response

int

statusCode()

Returns the status code for this response

URI

uri()

Returns the URI that the response was received from

HttpClient.Version

version()

Returns the HTTP protocol version that was used for this response

 

Let's work with some examples.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.222.167.183