Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Asynchronous Http and WebSocket Client library for Java

NotificationsYou must be signed in to change notification settings

lovejavaee/async-http-client

 
 

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

Javadoc

Gettingstarted, and useWebSockets

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.

Installation

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.9.31</version></dependency>

You can also download the artifact

Maven Search

AHC is an abstraction layer that can work on top of the bare JDK, Netty and Grizzly.Note that the JDK implementation is very limited and you shouldREALLY use the otherreal providers.

You then have to add the Netty or Grizzly jars in the classpath.

For Netty:

<dependency>    <groupId>io.netty</groupId>    <artifactId>netty</artifactId>    <version>LATEST_NETTY_3_VERSION</version></dependency>

For Grizzly:

<dependency>    <groupId>org.glassfish.grizzly</groupId>    <artifactId>connection-pool</artifactId>    <version>LATEST_GRIZZLY_VERSION</version></dependency><dependency>    <groupId>org.glassfish.grizzly</groupId>    <artifactId>grizzly-websockets</artifactId>    <version>LATEST_GRIZZLY_VERSION</version></dependency>

Checkmigration guide for migrating from 1.8 to 1.9.

Usage

Then in your code you can simply do

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();

Configuration

Finally, you can also configure the AsyncHttpClient via its AsyncHttpClientConfig object:

AsyncHttpClientConfigcf =newAsyncHttpClientConfig.Builder()S.setProxyServer(newProxyServer("127.0.0.1",38080)).build();AsyncHttpClientc =newAsyncHttpClient(cf);

WebSocket

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();

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

User Group

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

Google Group

Contributing

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:
    • Ident with 4 spaces
    • Use a 140 chars line max length
    • Don't use * imports
    • Stick to the org, com, javax, java imports order
  • 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.
    • If not, you have to prove that the original code was published under Apache License 2 and properly mention original copyrights.

About

Asynchronous Http and WebSocket Client library for Java

Resources

Stars

Watchers

Forks

Packages

No packages published

Languages

  • Java100.0%

[8]ページ先頭

©2009-2025 Movatter.jp