Giter Site home page Giter Site logo

async-http-client's Introduction

Async Http Client

Getting started HTML PDF With WebSockets

Async Http Client library purpose is to allow Java applications to easily execute HTTP requests and asynchronously process the HTTP responses. The library also supports the WebSocket Protocol. The Async HTTP Client library is simple to use. First, in order to add it to your Maven project, simply add this dependency:

         <dependency>
             <groupId>com.ning</groupId>
             <artifactId>async-http-client</artifactId>
             <version>1.7.4</version>
         </dependency>

You can also download the artifact

Maven Search

Then in your code you can simply do (Javadoc)

    import com.ning.http.client.*;
    import java.util.concurrent.Future;

    AsyncHttpClient asyncHttpClient = new AsyncHttpClient();
    Future<Response> f = asyncHttpClient.prepareGet("http://www.ning.com/ ").execute();
    Response r = f.get();

Note that in this case all the content must be read fully in memory, even if you used getResponseBodyAsStream()' method on returned Response` object.

You can also accomplish asynchronous (non-blocking) operation without using a Future if you want to receive and process the response in your handler:

    import com.ning.http.client.*;
    import java.util.concurrent.Future;

    AsyncHttpClient asyncHttpClient = new AsyncHttpClient();
    asyncHttpClient.prepareGet("http://www.ning.com/ ").execute(new AsyncCompletionHandler<Response>(){
        
        @Override
        public Response onCompleted(Response response) throws Exception{
            // Do something with the Response
            // ...
            return response;
        }
        
        @Override
        public void onThrowable(Throwable t){
            // Something wrong happened.
        }
    });

(this will also fully read Response in memory before calling onCompleted)

You can also mix Future with AsyncHandler to only retrieve part of the asynchronous response

    import com.ning.http.client.*;
    import java.util.concurrent.Future;

    AsyncHttpClient asyncHttpClient = new AsyncHttpClient();
    Future<Integer> f = asyncHttpClient.prepareGet("http://www.ning.com/ ").execute(
       new AsyncCompletionHandler<Integer>(){
        
        @Override
        public Integer onCompleted(Response response) throws Exception{
            // Do something with the Response
            return response.getStatusCode();
        }
        
        @Override
        public void onThrowable(Throwable t){
            // Something wrong happened.
        }
    });
    
    int statusCode = f.get();

which is something you want to do for large responses: this way you can process content as soon as it becomes available, piece by piece, without having to buffer it all in memory.

You have full control on the Response life cycle, so you can decide at any moment to stop processing what the server is sending back:

      import com.ning.http.client.*;
      import java.util.concurrent.Future;

      AsyncHttpClient c = new AsyncHttpClient();
      Future<String> f = c.prepareGet("http://www.ning.com/ ").execute(new AsyncHandler<String>() {
          private ByteArrayOutputStream bytes = new ByteArrayOutputStream();

          @Override
          public STATE onStatusReceived(HttpResponseStatus status) throws Exception {
              int statusCode = status.getStatusCode();
              // The Status have been read
              // If you don't want to read the headers,body or stop processing the response
              if (statusCode >= 500) {
                  return STATE.ABORT;
              }
          }

          @Override
          public STATE onHeadersReceived(HttpResponseHeaders h) throws Exception {
              Headers headers = h.getHeaders();
               // The headers have been read
               // If you don't want to read the body, or stop processing the response
               return STATE.ABORT;
          }

          @Override
          public STATE onBodyPartReceived(HttpResponseBodyPart bodyPart) throws Exception {
               bytes.write(bodyPart.getBodyPartBytes());
               return STATE.CONTINUE
          }

          @Override
          public String onCompleted() throws Exception {
               // Will be invoked once the response has been fully read or a ResponseComplete exception
               // has been thrown.
               // NOTE: should probably use Content-Encoding from headers
               return bytes.toString("UTF-8");
          }

          @Override
          public void onThrowable(Throwable t) {
          }
      });
      
      String bodyResponse = f.get();

Finally, you can also configure the AsyncHttpClient via it's AsyncHttpClientConfig object:

        AsyncHttpClientConfig cf = new AsyncHttpClientConfig.Builder()
            S.setProxyServer(new ProxyServer("127.0.0.1", 38080)).build();
        AsyncHttpClient c = new AsyncHttpClient(cf);

Async Http Client also support WebSocket by simply doing:

         WebSocket websocket = c.prepareGet(getTargetUrl())
                .execute(new WebSocketUpgradeHandler.Builder().addWebSocketListener(
                    new WebSocketTextListener() {

                    @Override
                    public void onMessage(String message) {
                    }

                    @Override
                    public void onOpen(WebSocket websocket) {
                        websocket.sendTextMessage("...").sendBinaryMessage("...");
                    }

                    @Override
                    public void onClose(.WebSocket websocket) {
                        latch.countDown();
                    }

                    @Override
                    public void onError(Throwable t) {
                    }
                }).build()).get();

The library uses Java non blocking I/O for supporting asynchronous operations. The default asynchronous provider is build on top of Netty, but the library exposes a configurable provider SPI which allows to easily plug in other frameworks like Grizzly

       AsyncHttpClientConfig config = new AsyncHttpClientConfig.Builder().build();
       AsyncHttpClient client = new AsyncHttpClient(new GrizzlyAsyncHttpProvider(config), config);

Keep up to date on the library development by joining the Asynchronous HTTP Client discussion group

Google Group

or follow us on Twitter

async-http-client's People

Contributors

alaz avatar basil3whitehouse avatar bclozel avatar bd808 avatar bentmann avatar brianm avatar coderunner avatar cowtowncoder avatar cstamas avatar erwan avatar fromage avatar gailh avatar gerdriesselmann avatar havocp avatar jfarcand avatar jloomis avatar jossulli avatar marekzebrowski avatar mbknor avatar mpilquist avatar nabcos avatar neotyk avatar njbartlett avatar nremond avatar pkulak avatar rlubke avatar rsertelon avatar simonetripodi avatar sterwill avatar taer avatar

Stargazers

 avatar

Watchers

 avatar  avatar

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.