在线时间:8:00-16:00
迪恩网络APP
随时随地掌握行业动态
扫描二维码
关注迪恩网络微信公众号
开源软件名称:AsyncHttpClient/async-http-client开源软件地址:https://github.com/AsyncHttpClient/async-http-client开源编程语言:Java 99.9%开源软件介绍:Async Http ClientFollow @AsyncHttpClient on Twitter. The AsyncHttpClient (AHC) library allows Java applications to easily execute HTTP requests and asynchronously process HTTP responses. The library also supports the WebSocket Protocol. It's built on top of Netty. It's currently compiled on Java 8 but runs on Java 9 too. New Roadmap RFCs!Well, not really RFCs, but as I am ramping up to release a new version, I would appreciate the comments from the community. Please add an issue and label it RFC and I'll take a look! InstallationBinaries are deployed on Maven Central. Import the AsyncHttpClient Bill of Materials (BOM) to add dependency management for AsyncHttpClient artifacts to your project: <dependencyManagement>
<dependencies>
<dependency>
<groupId>org.asynchttpclient</groupId>
<artifactId>async-http-client-bom</artifactId>
<version>LATEST_VERSION</version>
<type>pom</type>
<scope>import</scope>
</dependency>
</dependencies>
</dependencyManagement> Add a dependency on the main AsyncHttpClient artifact: <dependencies>
<dependency>
<groupId>org.asynchttpclient</groupId>
<artifactId>async-http-client</artifactId>
</dependency>
</dependencies> The VersionAHC doesn't use SEMVER, and won't.
Check CHANGES.md for migration path between versions. BasicsFeel free to check the Javadoc or the code for more information. DslImport the Dsl helpers to use convenient methods to bootstrap components: import static org.asynchttpclient.Dsl.*; Clientimport static org.asynchttpclient.Dsl.*;
AsyncHttpClient asyncHttpClient = asyncHttpClient(); AsyncHttpClient instances must be closed (call the AsyncHttpClient instances are intended to be global resources that share the same lifecycle as the application. Typically, AHC will usually underperform if you create a new client for each request, as it will create new threads and connection pools for each. It's possible to create shared resources (EventLoop and Timer) beforehand and pass them to multiple client instances in the config. You'll then be responsible for closing those shared resources. ConfigurationFinally, you can also configure the AsyncHttpClient instance via its AsyncHttpClientConfig object: import static org.asynchttpclient.Dsl.*;
AsyncHttpClient c = asyncHttpClient(config().setProxyServer(proxyServer("127.0.0.1", 38080))); HTTPSending RequestsBasicsAHC provides 2 APIs for defining requests: bound and unbound.
import org.asynchttpclient.*;
// bound
Future<Response> whenResponse = asyncHttpClient.prepareGet("http://www.example.com/").execute();
// unbound
Request request = get("http://www.example.com/").build();
Future<Response> whenResponse = asyncHttpClient.executeRequest(request); Setting Request BodyUse the This body can be of type:
MultipartUse the This part can be of type:
Dealing with ResponsesBlocking on the Future
Future<Response> whenResponse = asyncHttpClient.prepareGet("http://www.example.com/").execute();
Response response = whenResponse.get(); This is useful for debugging but you'll most likely hurt performance or create bugs when running such code on production. The point of using a non blocking client is to NOT BLOCK the calling thread! Setting callbacks on the ListenableFuture
ListenableFuture<Response> whenResponse = ???;
Runnable callback = () -> {
try {
Response response = whenResponse.get();
System.out.println(response);
} catch (InterruptedException | ExecutionException e) {
e.printStackTrace();
}
};
java.util.concurrent.Executor executor = ???;
whenResponse.addListener(() -> ???, executor); If the Using custom AsyncHandlers
The below sample just capture the response status and skips processing the response body chunks. Note that returning import static org.asynchttpclient.Dsl.*;
import org.asynchttpclient.*;
import io.netty.handler.codec.http.HttpHeaders;
Future<Integer> whenStatusCode = asyncHttpClient.prepareGet("http://www.example.com/")
.execute(new AsyncHandler<Integer>() {
private Integer status;
@Override
public State onStatusReceived(HttpResponseStatus responseStatus) throws Exception {
status = responseStatus.getStatusCode();
return State.ABORT;
}
@Override
public State onHeadersReceived(HttpHeaders headers) throws Exception {
return State.ABORT;
}
@Override
public State onBodyPartReceived(HttpResponseBodyPart bodyPart) throws Exception {
return State.ABORT;
}
@Override
public Integer onCompleted() throws Exception {
return status;
}
@Override
public void onThrowable(Throwable t) {
}
});
Integer statusCode = whenStatusCode.get(); Using Continuations
CompletableFuture<Response> whenResponse = asyncHttpClient
.prepareGet("http://www.example.com/")
.execute()
.toCompletableFuture()
.exceptionally(t -> { /* Something wrong happened... */ } )
.thenApply(response -> { /* Do something with the Response */ return resp; });
whenResponse.join(); // wait for completion You may get the complete maven project for this simple demo from org.asynchttpclient.example WebSocketAsync Http Client also supports WebSocket.
You need to pass a WebSocket websocket = c.prepareGet("ws://demos.kaazing.com/echo")
.execute(new WebSocketUpgradeHandler.Builder().addWebSocketListener(
new WebSocketListener() {
@Override
public void onOpen(WebSocket websocket) {
websocket.sendTextFrame("...").sendTextFrame("...");
}
@Override
public void onClose(WebSocket websocket) {
}
@Override
public void onTextFrame(String payload, boolean finalFragment, int rsv) {
System.out.println(payload);
}
@Override
public void onError(Throwable t) {
}
}).build()).get(); Reactive StreamsAsyncHttpClient has built-in support for reactive streams. You can pass a request body as a You can also pass a See tests in package WebDAVAsyncHttpClient has build in support for the WebDAV protocol. The API can be used the same way normal HTTP request are made: Request mkcolRequest = new RequestBuilder("MKCOL").setUrl("http://host:port/folder1").build();
Response response = c.executeRequest(mkcolRequest).get(); or Request propFindRequest = new RequestBuilder("PROPFIND").setUrl("http://host:port").build();
Response response = c.executeRequest(propFindRequest, new AsyncHandler() {
// ...
}).get(); MoreYou can find more information on Jean-François Arcand's blog. Jean-François is the original author of this library. Code is sometimes not up-to-date but gives a pretty good idea of advanced features.
User GroupKeep up to date on the library development by joining the Asynchronous HTTP Client discussion group ContributingOf course, Pull Requests are welcome. Here are the few rules we'd like you to respect if you do so:
|
2023-10-27
2022-08-15
2022-08-17
2022-09-23
2022-08-13
请发表评论