- Notifications
You must be signed in to change notification settings - Fork0
Asynchronous Http and WebSocket Client library for Java
License
chakra-coder/async-http-client
Folders and files
| Name | Name | Last commit message | Last commit date | |
|---|---|---|---|---|
Repository files navigation
Async Http Client (@AsyncHttpClient on twitter)
Gettingstarted, and useWebSockets
The Async Http Client library's 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.
It's built on top ofNetty and currently requires JDK8.
First, in order to add it to your Maven project, simply download from Maven central or add this dependency:
<dependency><groupId>org.asynchttpclient</groupId><artifactId>async-http-client</artifactId><version>LATEST_VERSION</version></dependency>
Then in your code you can simply do
importorg.asynchttpclient.*;importjava.util.concurrent.Future;AsyncHttpClientasyncHttpClient =newDefaultAsyncHttpClient();Future<Response>f =asyncHttpClient.prepareGet("http://www.example.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:
importorg.asynchttpclient.*;importjava.util.concurrent.Future;AsyncHttpClientasyncHttpClient =newDefaultAsyncHttpClient();asyncHttpClient.prepareGet("http://www.example.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)
Alternatively you may use continuations (through Java 8 classCompletableFuture<T>) to accomplish asynchronous (non-blocking) solution. The equivalent continuation approach to the previous example is:
importstaticorg.asynchttpclient.Dsl.*;importorg.asynchttpclient.*;importjava.util.concurrent.CompletableFuture;AsyncHttpClientasyncHttpClient =asyncHttpClient();CompletableFuture<Response>promise =asyncHttpClient .prepareGet("http://www.example.com/") .execute() .toCompletableFuture() .exceptionally(t -> {/* Something wrong happened... */ } ) .thenApply(resp -> {/* Do something with the Response */returnresp; });promise.join();// wait for completion
You may get the complete maven project for this simple demo fromorg.asynchttpclient.example
You can also mix Future with AsyncHandler to only retrieve part of the asynchronous response
importorg.asynchttpclient.*;importjava.util.concurrent.Future;AsyncHttpClientasyncHttpClient =newDefaultAsyncHttpClient();Future<Integer>f =asyncHttpClient.prepareGet("http://www.example.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:
importstaticorg.asynchttpclient.Dsl.*;importorg.asynchttpclient.*;importjava.util.concurrent.Future;AsyncHttpClientc =asyncHttpClient();Future<String>f =c.prepareGet("http://www.example.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 its AsyncHttpClientConfig object:
AsyncHttpClientConfigcf =newDefaultAsyncHttpClientConfig.Builder() .setProxyServer(newProxyServer.Builder("127.0.0.1",38080)).build();AsyncHttpClientc =newDefaultAsyncHttpClient(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("...").sendMessage("..."); }@OverridepublicvoidonClose(WebSocketwebsocket) {latch.countDown(); }@OverridepublicvoidonError(Throwablet) { } }).build()).get();
Keep up to date on the library development by joining the Asynchronous HTTP Client discussion group
Of course, Pull Requests are welcome.
Here a the few rules we'd like you to respect if you do so:
- Only edit the code related to the suggested change, so DON'T automatically format the classes you've edited.
- Respect the formatting rules:
- Indent with 4 spaces
- Your PR can contain multiple commits when submitting, but once it's been reviewed, we'll ask you to squash them into a single one
- Regarding licensing:
- You must be the original author of the code you suggest.
- You must give the copyright to "the AsyncHttpClient Project"
About
Asynchronous Http and WebSocket Client library for Java
Resources
License
Uh oh!
There was an error while loading.Please reload this page.
Stars
Watchers
Forks
Packages0
Languages
- Java99.9%
- Other0.1%