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

          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 on 2012-11-26 10:46 莊主游驥 閱讀(629) 評論(0)  編輯  收藏


          只有注冊用戶登錄后才能發表評論。


          網站導航:
           
          主站蜘蛛池模板: 铅山县| 达州市| 奉新县| 镇安县| 眉山市| 晴隆县| 金门县| 东平县| 会同县| 海淀区| 泊头市| 武夷山市| 万山特区| 盐山县| 黄龙县| 息烽县| 潢川县| 原阳县| 乳山市| 寿阳县| 二手房| 宝鸡市| 紫金县| 建阳市| 南和县| 三台县| 遂川县| 祁连县| 曲阳县| 桃园县| 乳山市| 定日县| 长治县| 江都市| 资阳市| 特克斯县| 滦平县| 绍兴市| 大丰市| 佛山市| 禄丰县|