In the example below from Jetty's docs, a simple method of performing an efficient, asynchronous HTTP request is described. However, it never specifies how you are actually supposed to retrieve the server's reply in this example, and I can't seem to figure it out.
The Result object has getResponse() and getRequest(), but neither of these has methods to access content.
Anyone know?
Jetty's docs
A simple asynchronous GET request can be written in this way:
httpClient.newRequest("http://domain.com/path")
.send(new Response.CompleteListener()
{
@Override
public void onComplete(Result result)
{
// Your logic here
}
});
Method Request.send(Response.CompleteListener) returns void and does not block; the Response.CompleteListener provided as a parameter is notified when the request/response conversation is complete, and the Result parameter allows you to access the response object.
You may want to have the Jetty 9 HttpClient
documentation as a reference.
The long answer to your question is explained here, section Response Content Handling
.
If you pass a plain CompleteListener
to Request.send(CompleteListener)
, it means that you're not interested in content, which will be thrown away.
If you are interested in content, but only at the completion of the response, you can pass provided utility classes such as BufferingResponseListener
:
request.send(new BufferingResponseListener() { ... });
If you are interested in the content as it arrives, you should pass a Response.ContentListener
, which will notify you of the content chunk by chunk.
You can do this in two ways: using a Response.Listener
(which extends Response.ContentListener
):
request.send(new Response.Listener()
{
public void onContent(...) { ... }
public void onComplete(...) { ... }
});
or using multiple listeners:
request.onResponseContent(new Response.ContentListener() { ... });
request.send(new CompleteListener() { ... });
You have all the flexibility you want, and out-of-the-box utility classes that help you (no need to write complex buffering code, just use BufferingResponseListener
).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With