How to get content from CompleteListener in the Jetty Asynchronous Client API

The following example from the Jetty documentation describes a simple way to make an efficient asynchronous HTTP request. However, it never indicates how you should actually get the server response in this example, and I cannot understand it.

The Result object has getResponse () and getRequest (), but none of them have methods for accessing the content.

Somebody knows?


Jetty Docs

A simple asynchronous GET request can be written as follows:

httpClient.newRequest("http://domain.com/path") .send(new Response.CompleteListener() { @Override public void onComplete(Result result) { // Your logic here } }); 

The Request.send (Response.CompleteListener) method returns void and does not block; The Response.CompleteListener provided as a parameter is notified of the end of the request / response session, and the result parameter allows access to the response object.

+4
source share
2 answers

You can use the Jetty 9 HttpClient documentation as a reference.

The long answer to your question is explained here , the Response Content Handling section.

If you pass a simple CompleteListener to Request.send(CompleteListener) , it means that you are not interested in the content that will be thrown.

If you are interested in the content, but only at the end of the response, you can pass the provided utility classes, such as the 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 fragment in a block.

You can do this in two ways: using 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 everything you need and ready-made utility classes that help you (no need to write complex buffering code, just use the BufferingResponseListener ).

+6
source

While an early answer (first date: 2013-06_Jun-24) will help you get started, more is required than in the current (Jetty v9.2) documentation.

The first thing you need is a way to call HttpClient to complete / end processing. After completing CompleteListener, you need to call HttpClient.stop () . If that's all we do, the code will sometimes crash (Java Exception), here's one reliable method to properly close the HttpClient:

You must call the HttpClient.stop () method, otherwise the JVM may be hungry from Jetty threads (or resources). This has been discussed here:

It is also important to do a little housework to ensure a good play of threads in a parallel processing situation.

0
source

Source: https://habr.com/ru/post/1487797/


All Articles