赞
踩
GitHub 地址:https://github.com/AsyncHttpClient/async-http-client
AsyncHttpClient目前版本2.1,内部采用Netty进行网络请求,因此比HttpClient更加优秀
maven
- <dependency>
- <groupId>org.asynchttpclient</groupId>
- <artifactId>async-http-client</artifactId>
- <version>2.1.0-alpha21</version>
- </dependency>
实例:
- AsyncHttpClient asyncHttpClient = new DefaultAsyncHttpClient();
- Future<Response> f = asyncHttpClient.prepareGet("http://www.example.com/").execute();
- Response r = f.get();
测试使用
- public class AsyncHttpUtil {
-
- public static Future<Response> get(String url, AsyncCompletionHandler<Response> completionHandler){
- AsyncHttpClient asyncHttpClient = new DefaultAsyncHttpClient(new DefaultAsyncHttpClientConfig.Builder()
- .setConnectTimeout(10000)
- .setRequestTimeout(10000)
- .build());
- RequestBuilder builder=new RequestBuilder();
- builder.setUrl(url);
- builder.addQueryParam("name","test");
-
- return asyncHttpClient.executeRequest(builder.build(),completionHandler);
- }
-
- public static void main(String[] args) {
- Future<Response> future= AsyncHttpUtil.get("http://www.baidu.com", new AsyncCompletionHandler<Response>() {
- @Override
- public Response onCompleted(Response response) throws Exception {
- if(response.hasResponseStatus()){
- System.out.println("1111");
- System.out.println(response.getResponseBody());
- }
- return response;
- }
-
- @Override
- public void onThrowable(Throwable t) {
- super.onThrowable(t);
- }
- });
- try {
- Response response= future.get();
-
- } catch (InterruptedException e) {
- e.printStackTrace();
- } catch (ExecutionException e) {
- e.printStackTrace();
- }
- }
- }
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。