- Notifications
You must be signed in to change notification settings - Fork0
Asynchronous Http and WebSocket Client library for Java
sucode/async-http-client
Folders and files
| Name | Name | Last commit message | Last commit date | |
|---|---|---|---|---|
Repository files navigation
Getting startedHTMLPDFWithWebSockets
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.16</version></dependency>
You can also download the artifact
Then in your code you can simply do (Javadoc)
importcom.ning.http.client.*;importjava.util.concurrent.Future;AsyncHttpClientasyncHttpClient =newAsyncHttpClient();Future<Response>f =asyncHttpClient.prepareGet("http://www.ning.com/").execute();Responser =f.get();
Note that in this case all the content must be read fully in memory, even if you usedgetResponseBodyAsStream()' method on returnedResponse` 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:
importcom.ning.http.client.*;importjava.util.concurrent.Future;AsyncHttpClientasyncHttpClient =newAsyncHttpClient();asyncHttpClient.prepareGet("http://www.ning.com/").execute(newAsyncCompletionHandler<Response>(){@OverridepublicResponseonCompleted(Responseresponse)throwsException{// Do something with the Response// ...returnresponse; }@OverridepublicvoidonThrowable(Throwablet){// Something wrong happened. }});
(this will also fully readResponse in memory before callingonCompleted)
You can also mix Future with AsyncHandler to only retrieve part of the asynchronous response
importcom.ning.http.client.*;importjava.util.concurrent.Future;AsyncHttpClientasyncHttpClient =newAsyncHttpClient();Future<Integer>f =asyncHttpClient.prepareGet("http://www.ning.com/").execute(newAsyncCompletionHandler<Integer>(){@OverridepublicIntegeronCompleted(Responseresponse)throwsException{// Do something with the Responsereturnresponse.getStatusCode(); }@OverridepublicvoidonThrowable(Throwablet){// Something wrong happened. }});intstatusCode =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:
importcom.ning.http.client.*;importjava.util.concurrent.Future;AsyncHttpClientc =newAsyncHttpClient();Future<String>f =c.prepareGet("http://www.ning.com/").execute(newAsyncHandler<String>() {privateByteArrayOutputStreambytes =newByteArrayOutputStream();@OverridepublicSTATEonStatusReceived(HttpResponseStatusstatus)throwsException {intstatusCode =status.getStatusCode();// The Status have been read// If you don't want to read the headers,body or stop processing the responseif (statusCode >=500) {returnSTATE.ABORT; } }@OverridepublicSTATEonHeadersReceived(HttpResponseHeadersh)throwsException {Headersheaders =h.getHeaders();// The headers have been read// If you don't want to read the body, or stop processing the responsereturnSTATE.ABORT; }@OverridepublicSTATEonBodyPartReceived(HttpResponseBodyPartbodyPart)throwsException {bytes.write(bodyPart.getBodyPartBytes());returnSTATE.CONTINUE; }@OverridepublicStringonCompleted()throwsException {// Will be invoked once the response has been fully read or a ResponseComplete exception// has been thrown.// NOTE: should probably use Content-Encoding from headersreturnbytes.toString("UTF-8"); }@OverridepublicvoidonThrowable(Throwablet) { }});StringbodyResponse =f.get();
Finally, you can also configure the AsyncHttpClient via it's AsyncHttpClientConfig object:
AsyncHttpClientConfigcf =newAsyncHttpClientConfig.Builder()S.setProxyServer(newProxyServer("127.0.0.1",38080)).build();AsyncHttpClientc =newAsyncHttpClient(cf);
Async Http Client also support WebSocket by simply doing:
WebSocketwebsocket =c.prepareGet(getTargetUrl()) .execute(newWebSocketUpgradeHandler.Builder().addWebSocketListener(newWebSocketTextListener() {@OverridepublicvoidonMessage(Stringmessage) { }@OverridepublicvoidonOpen(WebSocketwebsocket) {websocket.sendTextMessage("...").sendBinaryMessage("..."); }@OverridepublicvoidonClose(.WebSocketwebsocket) {latch.countDown(); }@OverridepublicvoidonError(Throwablet) { } }).build()).get();
The library uses Java non blocking I/O for supporting asynchronous operations. The default asynchronous provider is build on top ofNetty, but the library exposes a configurable provider SPI which allows to easily plug in other frameworks likeGrizzly
AsyncHttpClientConfigconfig =newAsyncHttpClientConfig.Builder().build();AsyncHttpClientclient =newAsyncHttpClient(newGrizzlyAsyncHttpProvider(config),config);
Keep up to date on the library development by joining the Asynchronous HTTP Client discussion group
or follow us onTwitter
About
Asynchronous Http and WebSocket Client library for Java
Resources
Uh oh!
There was an error while loading.Please reload this page.