AsyncHttpClient发送异步请求调用url

AsyncHttpClient访问Htt请求

首先需要在pom中添加

   org.asynchttpclient
   async-http-client
   2.4.7
  

发送同步请求,发送之后等待返回结果的方法用get获取

CountDownLatch latch = newCountDownLatch(1);用来计数

String url = new String("http://127.0.0.1:8080 ");

       CountDownLatch latch = new CountDownLatch(1);

       AsyncHttpClient client = new DefaultAsyncHttpClient();

       BoundRequestBuilder builder = client.preparePost(url);

       builder.addHeader("Content-Type", "application/json;charset=UTF-8");

       Resource source=new ClassPathResource(path);

           InputStream in=   source.getInputStream();

           int length=in.available();

           byte[] buff =new byte[length];

           org.apache.tomcat.util.http.fileupload.IOUtils.read(in, buff, 0, length);

           String result = "";

       builder.setBody(buff);

       try {

           Response res = builder.execute().get(15, TimeUnit.SECONDS);

           result = res.getResponseBody();

       } catch (ExecutionException | TimeoutException e1) {

           // TODO Auto-generatedcatch block

           System.out.println(e1.getMessage());

           e1.printStackTrace();

       }

      

       client.close();

用get方法来获取最后的返回结果,get的第二个参数为等等的时间,Response然后再根据Response来获取返回值

发送异步的http请求:

只需要在同步的build后面添加一个AsyncHandler

builder.execute(new AsyncHandler(){

           ByteArrayOutputStream content = new ByteArrayOutputStream();

           int statusCode;

          

           @Override

           public State onStatusReceived(HttpResponseStatus responseStatus) throws Exception {

              statusCode = responseStatus.getStatusCode();

              return State.CONTINUE;

           }

           @Override

           public State onHeadersReceived(HttpHeaders headers) throws Exception {

              return State.CONTINUE;

           }

           @Override

           public State onBodyPartReceived(HttpResponseBodyPart bodyPart) throws Exception {

              content.write(bodyPart.getBodyPartBytes());

              return State.CONTINUE;

           }

           @Override

           public void onThrowable(Throwable t) {

              callback.run(statusCode, t.getMessage());

           }

           @Override

           public String onCompleted() throws Exception {

              String data = content.toString();

              content.close();

              content = null;

              callback.run(statusCode, data);

              return "";

           }

onCompleted处理请求返回的数据返回一个Future对象然后在将Future放在一个List集合里面,用for循环在list遍历,然后用Futureget方法获取返回onCompleted返回的值。

用注解的方法使用AsyncHttpClient 将AsyncHttpClient 引入项目中Spring管理。

@Bean(destroyMethod="close")// 参数会调用下面注解的参数AsyncHttpClientConfig进行注入
    public AsyncHttpClient asyncHttpClient(AsyncHttpClientConfig config) {
        return new DefaultAsyncHttpClient(config);
    }

    @Bean
    public AsyncHttpClientConfig clientConfig() {
        AsyncHttpClientConfig config = new DefaultAsyncHttpClientConfig.Builder()
                // .setMaxConnectionsPerHost(2000)
                .setConnectTimeout(connectTimeout)
                .setReadTimeout(readTimeout)
                .setRequestTimeout(requestTimeout)
                .build();
        return config;
    }
    
    使用的时候只需要:
    @Autowired
    private AsyncHttpClient asyncHttpClient;//引入上面的bean对象AsyncHttpClient
    //自定义异步处理Handler
    private AsyncHandler newAsyncHandler() {
        return new AsyncHandler() {

            private ByteArrayOutputStream buffer = new ByteArrayOutputStream();

            @Override
            public State onStatusReceived(HttpResponseStatus responseStatus) throws Exception {
                return State.CONTINUE;
            }

            @Override
            public State onHeadersReceived(HttpHeaders headers) throws Exception {
                return State.CONTINUE;
            }

            @Override
            public State onBodyPartReceived(HttpResponseBodyPart bodyPart) throws Exception {
                buffer.write(bodyPart.getBodyPartBytes()); //接受到部分返回值时将值写入buffer缓存
                return State.CONTINUE;
            }

            @Override
            public void onThrowable(Throwable t) {
                t.printStackTrace();
            }

            @Override
            public String onCompleted() throws Exception {
                return buffer.toString(); // 调用完成时返回值
            }
        };
    }
    使用:
    String  body="";//请求体
    String  url="";//请求url
    BoundRequestBuilder builder = asyncHttpClient.preparePost(url).setBody(
                body);
        builder.setHeader("Content-Type", "application/json; charset=utf-8");
        return builder. execute(newAsyncHandler()); // 调用上面定义的newAsyncHandler 返回值为handler的返回值、

 builder. execute(newAsyncHandler()) 的返回值为一个Fulter。用法如下

Futere future = builder. execute(newAsyncHandler());

String   result=future.get();

 

 

 

下面是一个案例:

private static String dispatcherURL = "http://127.0.0.1:8081/dispatch/v1";
    public static JSONObject  post(JSONObject params) {

       AsyncHttpClient httpClient =new DefaultAsyncHttpClient();,
        BoundRequestBuilder builder = httpClient.preparePost(dispatcherURL);
        builder.addHeader("Content-Type", "application/json;charset=UTF-8");
        builder.setBody(params.toJSONString());
        try {
            Response res = builder.execute().get();
            return JSONObject.parseObject(res.getResponseBody());
        } catch (InterruptedException | ExecutionException e) {
            return new JSONObject();
        }
    }

 

 

你可能感兴趣的:(java相关)