隨筆 - 5, 文章 - 0, 評論 - 0, 引用 - 0
          數(shù)據(jù)加載中……

          HttpAsyncClient

          HttpAsyncClient 是一個異步的 HTTP 客戶端開發(fā)包,基于 HttpCore NIO 和 HttpClient 組件。
          HttpAsyncClient 的出現(xiàn)并不是為了替換 HttpClient,而是作為一個補充用于需要大量并發(fā)連接,對性能要求非常高的基于HTTP的原生數(shù)據(jù)通信,而且提供了事件驅(qū)動的 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已經(jīng)有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)  編輯  收藏


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


          網(wǎng)站導(dǎo)航:
           
          主站蜘蛛池模板: 左权县| 永寿县| 宁河县| 弥渡县| 丘北县| 新泰市| 西乡县| 宣武区| 滦平县| 大连市| 克什克腾旗| 彰武县| 富阳市| 茶陵县| 健康| 府谷县| 来宾市| 徐闻县| 洛宁县| 依安县| 乌什县| 蓬安县| 达拉特旗| 高雄县| 嵩明县| 阿拉善右旗| 南郑县| 翼城县| 合江县| 车致| 靖安县| 互助| 阿拉善左旗| 丰都县| 洛川县| 波密县| 峨眉山市| 元朗区| 迭部县| 民丰县| 乐东|