使用HttpAsyncClients在java中触发和忘记

时间:2014-05-12 13:08:33

标签: java http apache-httpclient-4.x

我正在尝试将HTTPAsyncCLient用于火灾并忘记在我的应用中。

http://hc.apache.org/httpcomponents-asyncclient-4.0.x/

我在这里给出了这个例子: http://hc.apache.org/httpcomponents-asyncclient-4.0.x/httpasyncclient/examples/org/apache/http/examples/nio/client/AsyncClientHttpExchange.java

我的代码如下:

           CloseableHttpAsyncClient httpclient = HttpAsyncClients.createDefault();
           httpclient.start();
           HttpGet request = new HttpGet(url);
           Future<HttpResponse> future = httpclient.execute(request, null);
          /*try {
            HttpResponse resp = future.get();
            StringBuilder sb = new StringBuilder();
            BufferedReader reader = new BufferedReader(new InputStreamReader(resp.getEntity().getContent()));
            String line = null;

            while ((line = reader.readLine()) != null) {
                sb.append(line);
            }
            String fr = sb.toString();
          } catch (InterruptedException e) {
          // TODO Auto-generated catch block
          e.printStackTrace();
          } catch (ExecutionException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
          }*/
       httpclient.close();

如果我取消注释评论部分,一切正常。 但我想要做的是一个火灾和忘记请求。因此,当我按上述方式注释掉该部分时,不会发出HTTP请求。 知道我做错了什么吗?我该怎么办才能解决火灾和忘记请求?

1 个答案:

答案 0 :(得分:0)

在请求完成之前,您的httpclient实例无法关闭。

虽然我不确定,但我会建议

// ONCE
CloseableHttpAsyncClient httpclient = HttpAsyncClients.createDefault();
httpclient.start();


// for every fire and forget request
HttpGet request = new HttpGet(url);
httpclient.execute(request, null);`

让您的客户端在请求之间保持活动状态,因此不要调用close(重新使用实例)