当前位置:   article > 正文

AsyncHttpClient的介绍和使用_org.asynchttpclient

org.asynchttpclient

GitHub 地址:https://github.com/AsyncHttpClient/async-http-client

AsyncHttpClient目前版本2.1,内部采用Netty进行网络请求,因此比HttpClient更加优秀


maven

  1. <dependency>
  2. <groupId>org.asynchttpclient</groupId>
  3. <artifactId>async-http-client</artifactId>
  4. <version>2.1.0-alpha21</version>
  5. </dependency>


实例:

  1. AsyncHttpClient asyncHttpClient = new DefaultAsyncHttpClient();
  2. Future<Response> f = asyncHttpClient.prepareGet("http://www.example.com/").execute();
  3. Response r = f.get();


测试使用

  1. public class AsyncHttpUtil {
  2. public static Future<Response> get(String url, AsyncCompletionHandler<Response> completionHandler){
  3. AsyncHttpClient asyncHttpClient = new DefaultAsyncHttpClient(new DefaultAsyncHttpClientConfig.Builder()
  4. .setConnectTimeout(10000)
  5. .setRequestTimeout(10000)
  6. .build());
  7. RequestBuilder builder=new RequestBuilder();
  8. builder.setUrl(url);
  9. builder.addQueryParam("name","test");
  10. return asyncHttpClient.executeRequest(builder.build(),completionHandler);
  11. }
  12. public static void main(String[] args) {
  13. Future<Response> future= AsyncHttpUtil.get("http://www.baidu.com", new AsyncCompletionHandler<Response>() {
  14. @Override
  15. public Response onCompleted(Response response) throws Exception {
  16. if(response.hasResponseStatus()){
  17. System.out.println("1111");
  18. System.out.println(response.getResponseBody());
  19. }
  20. return response;
  21. }
  22. @Override
  23. public void onThrowable(Throwable t) {
  24. super.onThrowable(t);
  25. }
  26. });
  27. try {
  28. Response response= future.get();
  29. } catch (InterruptedException e) {
  30. e.printStackTrace();
  31. } catch (ExecutionException e) {
  32. e.printStackTrace();
  33. }
  34. }
  35. }


声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/笔触狂放9/article/detail/413592
推荐阅读
相关标签
  

闽ICP备14008679号