少年阿賓

          那些青春的歲月

            BlogJava :: 首頁 :: 聯(lián)系 :: 聚合  :: 管理
            500 Posts :: 0 Stories :: 135 Comments :: 0 Trackbacks
          HttpClient程序包是一個(gè)實(shí)現(xiàn)了 HTTP 協(xié)議的客戶端編程工具包,要想熟練的掌握它,必須熟悉 HTTP協(xié)議。一個(gè)最簡單的調(diào)用如下:
           
          import java.io.IOException;
          import org.apache.http.HttpResponse;
          import org.apache.http.client.ClientProtocolException;
          import org.apache.http.client.HttpClient;
          import org.apache.http.client.methods.HttpGet;
          import org.apache.http.client.methods.HttpUriRequest;
          import org.apache.http.impl.client.DefaultHttpClient;
           
          public class Test {
              public static void main(String[] args) {
           
                 // 核心應(yīng)用類
                 HttpClient httpClient = new DefaultHttpClient();
           
                  // HTTP請求
                  HttpUriRequest request =
                          new HttpGet("http://localhost/index.html");
           
                  // 打印請求信息
                  System.out.println(request.getRequestLine());
                  try {
                      // 發(fā)送請求,返回響應(yīng)
                      HttpResponse response = httpClient.execute(request);
           
                      // 打印響應(yīng)信息
                      System.out.println(response.getStatusLine());
                  } catch (ClientProtocolException e) {
                      // 協(xié)議錯(cuò)誤
                      e.printStackTrace();
                  } catch (IOException e) {
                      // 網(wǎng)絡(luò)異常
                      e.printStackTrace();
                  }
              }
          }
           
          如果HTTP服務(wù)器正常并且存在相應(yīng)的服務(wù),則上例會打印出兩行結(jié)果:
           
              GET http://localhost/index.html HTTP/1.1
              HTTP/1.1 200 OK 
           
          核心對象httpClient的調(diào)用非常直觀,其execute方法傳入一個(gè)request對象,返回一個(gè)response對象。使用 httpClient發(fā)出HTTP請求時(shí),系統(tǒng)可能拋出兩種異常,分別是ClientProtocolException和IOException。第一種異常的發(fā)生通常是協(xié)議錯(cuò)誤導(dǎo)致,如在構(gòu)造HttpGet對象時(shí)傳入的協(xié)議不對(例如不小心將”http”寫成”htp”),或者服務(wù)器端返回的內(nèi)容不符合HTTP協(xié)議要求等;第二種異常一般是由于網(wǎng)絡(luò)原因引起的異常,如HTTP服務(wù)器未啟動等。
          從實(shí)際應(yīng)用的角度看,HTTP協(xié)議由兩大部分組成:HTTP請求和HTTP響應(yīng)。那么HttpClient程序包是如何實(shí)現(xiàn)HTTP客戶端應(yīng)用的呢?實(shí)現(xiàn)過程中需要注意哪些問題呢?
          HTTP請求
           
          HTTP 1.1由以下幾種請求組成:GET, HEAD, POST, PUT, DELETE, TRACE and OPTIONS, 程序包中分別用HttpGet, HttpHead, HttpPost, HttpPut, HttpDelete, HttpTrace, and HttpOptions 這幾個(gè)類創(chuàng)建請求。所有的這些類均實(shí)現(xiàn)了HttpUriRequest接口,故可以作為execute的執(zhí)行參數(shù)使用。
          所有請求中最常用的是GET與POST兩種請求,與創(chuàng)建GET請求的方法相同,可以用如下方法創(chuàng)建一個(gè)POST請求:
           
          HttpUriRequest request = new HttpPost(
                  "http://localhost/index.html");
           
           
          HTTP請求格式告訴我們,有兩個(gè)位置或者說兩種方式可以為request提供參數(shù):request-line方式與request-body方式。
          request-line
           
          request-line方式是指在請求行上通過URI直接提供參數(shù)。
          (1)
          我們可以在生成request對象時(shí)提供帶參數(shù)的URI,如:
           
          HttpUriRequest request = new HttpGet(
                  "http://localhost/index.html?param1=value1&param2=value2");
           
          (2)
          另外,HttpClient程序包為我們提供了URIUtils工具類,可以通過它生成帶參數(shù)的URI,如:
           
          URI uri = URIUtils.createURI("http", "localhost", -1, "/index.html",
              "param1=value1&param2=value2", null);
          HttpUriRequest request = new HttpGet(uri);
          System.out.println(request.getURI());
           
          上例的打印結(jié)果如下:
           
              http://localhost/index.html?param1=value1&param2=value2
           
          (3)
          需要注意的是,如果參數(shù)中含有中文,需將參數(shù)進(jìn)行URLEncoding處理,如:
           
          String param = "param1=" + URLEncoder.encode("中國", "UTF-8") + "&param2=value2";
          URI uri = URIUtils.createURI("http", "localhost", 8080,
          "/sshsky/index.html", param, null);
          System.out.println(uri);
           
          上例的打印結(jié)果如下:
           
              http://localhost/index.html?param1=%E4%B8%AD%E5%9B%BD&param2=value2
           
          (4)
          對于參數(shù)的URLEncoding處理,HttpClient程序包為我們準(zhǔn)備了另一個(gè)工具類:URLEncodedUtils。通過它,我們可以直觀的(但是比較復(fù)雜)生成URI,如:
           
          List params = new ArrayList();
          params.add(new BasicNameValuePair("param1", "中國"));
          params.add(new BasicNameValuePair("param2", "value2"));
          String param = URLEncodedUtils.format(params, "UTF-8");
          URI uri = URIUtils.createURI("http", "localhost", 8080,
          "/sshsky/index.html", param, null);
          System.out.println(uri);
           
          上例的打印結(jié)果如下:
           
              http://localhost/index.html?param1=%E4%B8%AD%E5%9B%BD&param2=value2
           
          request-body
           
          與request-line方式不同,request-body方式是在request-body中提供參數(shù),此方式只能用于POST請求。在 HttpClient程序包中有兩個(gè)類可以完成此項(xiàng)工作,它們分別是UrlEncodedFormEntity類與MultipartEntity類。這兩個(gè)類均實(shí)現(xiàn)了HttpEntity接口。
          (1)
          使用最多的是UrlEncodedFormEntity類。通過該類創(chuàng)建的對象可以模擬傳統(tǒng)的HTML表單傳送POST請求中的參數(shù)。如下面的表單:
           
          <form action="http://localhost/index.html" method="POST">
              <input type="text" name="param1" value="中國"/>
              <input type="text" name="param2" value="value2"/>
              <inupt type="submit" value="submit"/>
          </form>
           
          我們可以用下面的代碼實(shí)現(xiàn):
           
          List formParams = new ArrayList();
          formParams.add(new BasicNameValuePair("param1", "中國"));
          formParams.add(new BasicNameValuePair("param2", "value2"));
          HttpEntity entity = new UrlEncodedFormEntity(formParams, "UTF-8");
           
          HttpPost request = new HttpPost(“http://localhost/index.html”);
          request.setEntity(entity);
           
          當(dāng)然,如果想查看HTTP數(shù)據(jù)格式,可以通過HttpEntity對象的各種方法取得。如:
           
          List formParams = new ArrayList();
          formParams.add(new BasicNameValuePair("param1", "中國"));
          formParams.add(new BasicNameValuePair("param2", "value2"));
          UrlEncodedFormEntity entity = new UrlEncodedFormEntity(formParams, "UTF-8");
           
          System.out.println(entity.getContentType());
          System.out.println(entity.getContentLength());
          System.out.println(EntityUtils.getContentCharSet(entity));
          System.out.println(EntityUtils.toString(entity));
           
          上例的打印結(jié)果如下:
           
              Content-Type: application/x-www-form-urlencoded; charset=UTF-8
              39
              UTF-8
              param1=%E4%B8%AD%E5%9B%BD&param2=value2 
           
          (2)
          除了傳統(tǒng)的application/x-www-form-urlencoded表單,我們另一個(gè)經(jīng)常用到的是上傳文件用的表單,這種表單的類型為 multipart/form-data。在HttpClient程序擴(kuò)展包(HttpMime)中專門有一個(gè)類與之對應(yīng),那就是 MultipartEntity類。此類同樣實(shí)現(xiàn)了HttpEntity接口。如下面的表單:
           
          <form action="http://localhost/index.html" method="POST"
                  enctype="multipart/form-data">
              <input type="text" name="param1" value="中國"/>
              <input type="text" name="param2" value="value2"/>
              <input type="file" name="param3"/>
              <inupt type="submit" value="submit"/>
          </form>
           
          我們可以用下面的代碼實(shí)現(xiàn):
           
          MultipartEntity entity = new MultipartEntity();
          entity.addPart("param1", new StringBody("中國", Charset.forName("UTF-8")));
          entity.addPart("param2", new StringBody("value2", Charset.forName("UTF-8")));
          entity.addPart("param3", new FileBody(new File("C:\\1.txt")));
           
          HttpPost request = new HttpPost(“http://localhost/index.html”);
          request.setEntity(entity);
           
          HTTP響應(yīng)
           
          HttpClient程序包對于HTTP響應(yīng)的處理較之HTTP請求來說是簡單多了,其過程同樣使用了HttpEntity接口。我們可以從 HttpEntity對象中取出數(shù)據(jù)流(InputStream),該數(shù)據(jù)流就是服務(wù)器返回的響應(yīng)數(shù)據(jù)。需要注意的是,HttpClient程序包不負(fù)責(zé)解析數(shù)據(jù)流中的內(nèi)容。如:
           
          HttpUriRequest request = ...;
          HttpResponse response = httpClient.execute(request);
           
          // 從response中取出HttpEntity對象
          HttpEntity entity = response.getEntity();
           
          // 查看entity的各種指標(biāo)
          System.out.println(entity.getContentType());
          System.out.println(entity.getContentLength());
          System.out.println(EntityUtils.getContentCharSet(entity));
           
          // 取出服務(wù)器返回的數(shù)據(jù)流
          InputStream stream = entity.getContent();
           
          // 以任意方式操作數(shù)據(jù)流stream
          // 調(diào)用方式 略
           
          附注:
           
          本文說明的是HttpClient 4.0.1,該程序包(包括依賴的程序包)由以下幾個(gè)JAR包組成:
           
          commons-logging-1.1.1.jar
          commons-codec-1.4.jar
          httpcore-4.0.1.jar
          httpclient-4.0.1.jar
          apache-mime4j-0.6.jar
          httpmime-4.0.1.jar
           
          可以在此處下載完整的JAR包。
           
           
           
           
          現(xiàn)在Apache已經(jīng)發(fā)布了:HttpCore 4.0-beta3、HttpClient 4.0-beta1。
          到此處可以去下載這些源代碼:http://hc.apache.org/downloads.cgi
          另外,還需要apache-mime4j-0.5.jar 包。
           
          在這里先寫個(gè)簡單的POST方法,中文資料不多,英文不太好。
          package test;
           
          import java.util.ArrayList;
          import java.util.List;
          import org.apache.http.Header;
          import org.apache.http.HttpEntity;
          import org.apache.http.HttpResponse;
          import org.apache.http.NameValuePair;
          import org.apache.http.client.entity.UrlEncodedFormEntity;
          import org.apache.http.client.methods.HttpPost;
          import org.apache.http.client.params.CookiePolicy;
          import org.apache.http.client.params.ClientPNames;
          import org.apache.http.impl.client.DefaultHttpClient;
          import org.apache.http.message.BasicNameValuePair;
          import org.apache.http.protocol.HTTP;
          import org.apache.http.util.EntityUtils;
           
          public class Test2 {
              public static void main(String[] args) throws Exception {
                  DefaultHttpClient httpclient = new DefaultHttpClient();      //實(shí)例化一個(gè)HttpClient
                  HttpResponse response = null;
                  HttpEntity entity = null;
                  httpclient.getParams().setParameter(
                          ClientPNames.COOKIE_POLICY, CookiePolicy.BROWSER_COMPATIBILITY);  //設(shè)置cookie的兼容性
                  HttpPost httpost = new HttpPost("http://127.0.0.1:8080/pub/jsp/getInfo");           //引號中的參數(shù)是:servlet的地址
                  List <NameValuePair> nvps = new ArrayList <NameValuePair>();                     
                  nvps.add(new BasicNameValuePair("jqm", "fb1f7cbdaf2bf0a9cb5d43736492640e0c4c0cd0232da9de"));  
                  //   BasicNameValuePair("name", "value"), name是post方法里的屬性, value是傳入的參數(shù)值
                  nvps.add(new BasicNameValuePair("sqm", "1bb5b5b45915c8"));
                  httpost.setEntity(new UrlEncodedFormEntity(nvps, HTTP.UTF_8));            //將參數(shù)傳入post方法中
                  response = httpclient.execute(httpost);                                               //執(zhí)行
                  entity = response.getEntity();                                                             //返回服務(wù)器響應(yīng)
                  try{
                      System.out.println("----------------------------------------");
                      System.out.println(response.getStatusLine());                           //服務(wù)器返回狀態(tài)
                      Header[] headers = response.getAllHeaders();                    //返回的HTTP頭信息
                      for (int i=0; i<headers.length; i++) {                              
                      System.out.println(headers[i]);
                      }
                      System.out.println("----------------------------------------");
                      String responseString = null;
                      if (response.getEntity() != null) {
                      responseString = EntityUtils.toString(response.getEntity());      / /返回服務(wù)器響應(yīng)的HTML代碼
                      System.out.println(responseString);                                   //打印出服務(wù)器響應(yīng)的HTML代碼
                      }
                  } finally {
                      if (entity != null)                          
                      entity.consumeContent();                                                   // release connection gracefully
                  }
                  System.out.println("Login form get: " + response.getStatusLine());
                  if (entity != null) {
                  entity.consumeContent();
                  }
                 
              }
          }
           
           
           
           
          HttpClient4.0 學(xué)習(xí)實(shí)例 - 頁面獲取
           
          HttpClient 4.0出來不久,所以網(wǎng)絡(luò)上面相關(guān)的實(shí)例教程不多,搜httpclient得到的大部分都是基于原 Commons HttpClient 3.1 (legacy) 包的,官網(wǎng)下載頁面:http://hc.apache.org/downloads.cgi,如果大家看了官網(wǎng)說明就明白httpclient4.0是從原包分支出來獨(dú)立成包的,以后原來那個(gè)包中的httpclient不會再升級,所以以后我們是用httpclient新分支,由于4.0與之前的3.1包結(jié)構(gòu)以及接口等都有較大變化,所以網(wǎng)上搜到的實(shí)例大部分都是不適合4.0的,當(dāng)然,我們可以通過那些實(shí)例去琢磨4.0的用法,我也是新手,記錄下學(xué)習(xí)過程方便以后檢索
           
          本實(shí)例我們來獲取抓取網(wǎng)頁編碼,內(nèi)容等信息
           
          默認(rèn)情況下,服務(wù)器端會根據(jù)客戶端的請求頭信息來返回服務(wù)器支持的編碼,像google.cn他本身支持utf-8,gb2312等編碼,所以如果你在頭部中不指定任何頭部信息的話他默認(rèn)會返回gb2312編碼,而如果我們在瀏覽器中直接訪問google.cn,通過httplook,或者firefox 的firebug插件查看返回頭部信息的話會發(fā)現(xiàn)他返回的是UTF-8編碼
           
          下面我們還是看實(shí)例來解說吧,注釋等我也放代碼里面解釋,放完整代碼,方便新手理解
           
          本實(shí)例將
           
          使用的httpclient相關(guān)包
          httpclient-4.0.jar
          httpcore-4.0.1.jar
          httpmime-4.0.jar
          commons-logging-1.0.4.jar等其它相關(guān)包
           
          // HttpClientTest.java
          package com.baihuo.crawler.test;
           
          import java.util.regex.Matcher;
          import java.util.regex.Pattern;
           
          import org.apache.http.Header;
          import org.apache.http.HttpEntity;
          import org.apache.http.HttpHost;
          import org.apache.http.HttpResponse;
          import org.apache.http.client.HttpClient;
          import org.apache.http.client.methods.HttpGet;
          import org.apache.http.impl.client.DefaultHttpClient;
          import org.apache.http.util.EntityUtils;
           
          class HttpClientTest {
           
              public final static void main(String[] args) throws Exception {
           
                  // 初始化,此處構(gòu)造函數(shù)就與3.1中不同
                  HttpClient httpclient = new DefaultHttpClient();
           
                  HttpHost targetHost = new HttpHost("www.google.cn");
                  //HttpGet httpget = new HttpGet("http://www.apache.org/");
                  HttpGet httpget = new HttpGet("/");
           
                  // 查看默認(rèn)request頭部信息
                  System.out.println("Accept-Charset:" + httpget.getFirstHeader("Accept-Charset"));
                  // 以下這條如果不加會發(fā)現(xiàn)無論你設(shè)置Accept-Charset為gbk還是utf-8,他都會默認(rèn)返回gb2312(本例針對google.cn來說)
                  httpget.setHeader("User-Agent", "Mozilla/5.0 (Windows; U; Windows NT 5.1; zh-CN; rv:1.9.1.2)");
                  // 用逗號分隔顯示可以同時(shí)接受多種編碼
                  httpget.setHeader("Accept-Language", "zh-cn,zh;q=0.5");
                  httpget.setHeader("Accept-Charset", "GB2312,utf-8;q=0.7,*;q=0.7");
                  // 驗(yàn)證頭部信息設(shè)置生效
                  System.out.println("Accept-Charset:" + httpget.getFirstHeader("Accept-Charset").getValue());
           
                  // Execute HTTP request
                  System.out.println("executing request " + httpget.getURI());
                  HttpResponse response = httpclient.execute(targetHost, httpget);
                  //HttpResponse response = httpclient.execute(httpget);
           
                  System.out.println("----------------------------------------");
                  System.out.println("Location: " + response.getLastHeader("Location"));
                  System.out.println(response.getStatusLine().getStatusCode());
                  System.out.println(response.getLastHeader("Content-Type"));
                  System.out.println(response.getLastHeader("Content-Length"));
                  
                  System.out.println("----------------------------------------");
           
                  // 判斷頁面返回狀態(tài)判斷是否進(jìn)行轉(zhuǎn)向抓取新鏈接
                  int statusCode = response.getStatusLine().getStatusCode();
                  if ((statusCode == HttpStatus.SC_MOVED_PERMANENTLY) ||
                          (statusCode == HttpStatus.SC_MOVED_TEMPORARILY) ||
                          (statusCode == HttpStatus.SC_SEE_OTHER) ||
                          (statusCode == HttpStatus.SC_TEMPORARY_REDIRECT)) {
                      // 此處重定向處理  此處還未驗(yàn)證
                      String newUri = response.getLastHeader("Location").getValue();
                      httpclient = new DefaultHttpClient();
                      httpget = new HttpGet(newUri);
                      response = httpclient.execute(httpget);
                  }
           
                  // Get hold of the response entity
                  HttpEntity entity = response.getEntity();
                  
                  // 查看所有返回頭部信息
                  Header headers[] = response.getAllHeaders();
                  int ii = 0;
                  while (ii < headers.length) {
                      System.out.println(headers[ii].getName() + ": " + headers[ii].getValue());
                      ++ii;
                  }
                  
                  // If the response does not enclose an entity, there is no need
                  // to bother about connection release
                  if (entity != null) {
                      // 將源碼流保存在一個(gè)byte數(shù)組當(dāng)中,因?yàn)榭赡苄枰獌纱斡玫皆摿鳎?/div>
                      byte[] bytes = EntityUtils.toByteArray(entity);
                      String charSet = "";
                      
                      // 如果頭部Content-Type中包含了編碼信息,那么我們可以直接在此處獲取
                      charSet = EntityUtils.getContentCharSet(entity);
           
                      System.out.println("In header: " + charSet);
                      // 如果頭部中沒有,那么我們需要 查看頁面源碼,這個(gè)方法雖然不能說完全正確,因?yàn)橛行┐植诘木W(wǎng)頁編碼者沒有在頁面中寫頭部編碼信息
                      if (charSet == "") {
                          regEx="(?=<meta).*?(?<=charset=[\\'|\\\"]?)([[a-z]|[A-Z]|[0-9]|-]*)";
                          p=Pattern.compile(regEx, Pattern.CASE_INSENSITIVE);
                          m=p.matcher(new String(bytes));  // 默認(rèn)編碼轉(zhuǎn)成字符串,因?yàn)槲覀兊钠ヅ渲袩o中文,所以串中可能的亂碼對我們沒有影響
                          result=m.find();
                          if (m.groupCount() == 1) {
                              charSet = m.group(1);
                          } else {
                              charSet = "";
                          }
                      }
                      System.out.println("Last get: " + charSet);
                      // 至此,我們可以將原byte數(shù)組按照正常編碼專成字符串輸出(如果找到了編碼的話)
                      System.out.println("Encoding string is: " + new String(bytes, charSet));
                  }
           
                  httpclient.getConnectionManager().shutdown();        
              }
           
          }



          http://www.cnblogs.com/loveyakamoz/archive/2011/07/21/2113252.html
          posted on 2012-09-26 16:46 abin 閱讀(5397) 評論(1)  編輯  收藏 所屬分類: httpClient

          Feedback

          # re: HttpClient_4 用法 由HttpClient_3 升級到 HttpClient_4 必看 2013-06-28 17:44 Neway
          相當(dāng)詳細(xì),謝謝博主  回復(fù)  更多評論
            

          主站蜘蛛池模板: 阿拉善左旗| 荆州市| 富阳市| 奎屯市| 桃源县| 阿坝| 安庆市| 略阳县| 乐都县| 神农架林区| 富裕县| 措美县| 萨迦县| 石景山区| 临汾市| 巴林左旗| 兴城市| 武清区| 固原市| 广安市| 梁山县| 鞍山市| 财经| 虞城县| 丹东市| 从化市| 黄骅市| 浦北县| 商都县| 博罗县| 伊通| 京山县| 雷山县| 洪洞县| 聊城市| 西安市| 措勤县| 和平区| 探索| 皋兰县| 中宁县|