Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get content from CompleteListener in Jetty Client Async API

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.

like image 734
Alex Avatar asked Jun 24 '13 04:06

Alex


1 Answers

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).

like image 146
sbordet Avatar answered Sep 28 '22 01:09

sbordet