隨筆 - 5, 文章 - 0, 評論 - 0, 引用 - 0
          數據加載中……

          2012年11月26日

          HttpAsyncClient

          HttpAsyncClient 是一個異步的 HTTP 客戶端開發包,基于 HttpCore NIO 和 HttpClient 組件。
          HttpAsyncClient 的出現并不是為了替換 HttpClient,而是作為一個補充用于需要大量并發連接,對性能要求非常高的基于HTTP的原生數據通信,而且提供了事件驅動的 API。

          代碼示例:

                 public Vector<Long> Gets(List<String> urls)
          throws IOReactorException, InterruptedException {
          List<HttpGet> requests = new ArrayList<HttpGet>();
          for (String url : urls) {
          HttpGet get = new HttpGet(url);
          requests.add(get);
          }
          final Vector<Long> dataPackages = new Vector<Long>();
          HttpAsyncClient httpclient = new DefaultHttpAsyncClient();
          httpclient.getParams().setIntParameter("http.socket.timeout", 5000)
          .setIntParameter("http.connection.timeout", 5000)
          .setIntParameter("http.socket.buffer-size", 8192)
          .setBooleanParameter("http.tcp.nodelay", true);
          final CountDownLatch latch = new CountDownLatch(requests.size());
          httpclient.start();
          try {
          for (final HttpGet request : requests) {
          httpclient.execute(request, new FutureCallback<HttpResponse>() {

          @Override
          public void completed(HttpResponse result) {
          String statInfo = "";
          try {
          statInfo = result.getFirstHeader("statInfo").getValue();
          if (statInfo != null) {
          Long size = Long.parseLong(statInfo.split(",")[0].split(":")[1]);
          dataPackages.add(size);
          }
          } catch (Exception e) {
          System.out.println(e);
          System.out.println(statInfo);
          }
          latch.countDown();
          }

          @Override
          public void failed(Exception ex) {
          latch.countDown();
          }

          @Override
          public void cancelled() {
          latch.countDown();
          }
          });
          }
          latch.await();
          } finally {
          httpclient.shutdown();
          }
          return dataPackages;
          }

           


          依賴的pom,
          httpasyncclient已經有4.0-beta3版本了
          <dependency>
              <groupId>org.apache.httpcomponents</groupId>
              <artifactId>httpasyncclient</artifactId>
              <version>4.0-beta1</version>
          </dependency>
          <dependency>
              <groupId>org.apache.httpcomponents</groupId>
              <artifactId>httpclient</artifactId>
              <version>4.2-beta1</version>
          </dependency>


          posted @ 2012-11-26 10:46 莊主游驥 閱讀(628) | 評論 (0)編輯 收藏

          主站蜘蛛池模板: 桐庐县| 习水县| 平邑县| 喀喇| 遂宁市| 九江县| 瓮安县| 武夷山市| 隆化县| 云和县| 土默特右旗| 城市| 开原市| 临颍县| 离岛区| 海兴县| 高平市| 扎鲁特旗| 双城市| 乌兰浩特市| 平乐县| 南宁市| 南阳市| 蓬莱市| 仙游县| 饶阳县| 镇康县| 汝州市| 休宁县| 内黄县| 芦溪县| 新和县| 鱼台县| 哈巴河县| 四川省| 酉阳| 南城县| 石阡县| 泾源县| 寿阳县| 宝山区|