国产一级a片免费看高清,亚洲熟女中文字幕在线视频,黄三级高清在线播放,免费黄色视频在线看

打開APP
userphoto
未登錄

開通VIP,暢享免費電子書等14項超值服

開通VIP
httpclient教程
Commons-httpclient項目就是專門設(shè)計來簡化HTTP客戶端與服務(wù)器進行各種通訊編程。


1. 讀取網(wǎng)頁(HTTP/HTTPS)內(nèi)容

   最簡單的HTTP客戶端,用來演示通過GET或者POST方式訪問某個頁面

Java代碼
  1. package http.demo;   
  2.   
  3. import java.io.IOException;   
  4. import org.apache.commons.httpclient.*;   
  5. import org.apache.commons.httpclient.methods.*;   
  6.   
  7. public class SimpleClient {   
  8.   
  9.     public static void main(String[] args) throws IOException   
  10.     {   
  11.         HttpClient client = new HttpClient();      
  12.   
  13.         //設(shè)置代理服務(wù)器地址和端口       
  14.   
  15.         //client.getHostConfiguration().setProxy("proxy_host_addr",proxy_port);   
  16.   
  17.         //使用GET方法,如果服務(wù)器需要通過HTTPS連接,那只需要將下面URL中的http換成https   
  18.   
  19.         HttpMethod method = new GetMethod("http://java.sun.com");   
  20.   
  21.         //使用POST方法   
  22.   
  23.         //HttpMethod method = new PostMethod("http://java.sun.com");   
  24.   
  25.         client.executeMethod(method);   
  26.   
  27.         //打印服務(wù)器返回的狀態(tài)   
  28.   
  29.         System.out.println(method.getStatusLine());   
  30.   
  31.         //打印返回的信息   
  32.   
  33.         System.out.println(method.getResponseBodyAsString());   
  34.   
  35.         //釋放連接   
  36.   
  37.         method.releaseConnection();   
  38.   
  39.     }   
  40. }  


2. 以GET或者POST方式向網(wǎng)頁提交參數(shù)


Java代碼
  1. package http.demo;   
  2.   
  3. import java.io.IOException;   
  4.   
  5. import org.apache.commons.httpclient.*;   
  6.   
  7. import org.apache.commons.httpclient.methods.*;   
  8.   
  9. /**  
  10.  
  11. * 提交參數(shù)演示  
  12.  
  13. * 該程序連接到一個用于查詢手機號碼所屬地的頁面  
  14.  
  15. * 以便查詢號碼段1330227所在的省份以及城市  
  16.  
  17. */  
  18.   
  19. public class SimpleHttpClient {   
  20.   
  21.     public static void main(String[] args) throws IOException   
  22.   
  23.     {   
  24.   
  25.         HttpClient client = new HttpClient();   
  26.   
  27.         client.getHostConfiguration().setHost("www.imobile.com.cn"80"http");   
  28.   
  29.         HttpMethod method = getPostMethod();//使用POST方式提交數(shù)據(jù)   
  30.   
  31.         client.executeMethod(method);   
  32.   
  33.        //打印服務(wù)器返回的狀態(tài)   
  34.   
  35.         System.out.println(method.getStatusLine());   
  36.   
  37.         //打印結(jié)果頁面   
  38.   
  39.         String response =   
  40.   
  41.            new String(method.getResponseBodyAsString().getBytes("8859_1"));   
  42.   
  43.        //打印返回的信息   
  44.   
  45.         System.out.println(response);   
  46.   
  47.         method.releaseConnection();   
  48.   
  49.     }   
  50.   
  51.     /**  
  52.  
  53.      * 使用GET方式提交數(shù)據(jù)  
  54.  
  55.      * @return  
  56.  
  57.      */  
  58.   
  59.     private static HttpMethod getGetMethod(){   
  60.   
  61.         return new GetMethod("/simcard.php?simcard=1330227");   
  62.   
  63.     }   
  64.   
  65.     /**  
  66.  
  67.      * 使用POST方式提交數(shù)據(jù)  
  68.  
  69.      * @return  
  70.  
  71.      */  
  72.   
  73.     private static HttpMethod getPostMethod(){   
  74.   
  75.         PostMethod post = new PostMethod("/simcard.php");   
  76.   
  77.         NameValuePair simcard = new NameValuePair("simcard","1330227");   
  78.   
  79.         post.setRequestBody(new NameValuePair[] { simcard});   
  80.   
  81.         return post;   
  82.   
  83.     }   
  84.   
  85. }  



3. 處理頁面重定向

詳細描述:

狀態(tài)碼  對應(yīng)HttpServletResponse的常量

301   SC_MOVED_PERMANENTLY  頁面已經(jīng)永久移到另外一個新地址

302   SC_MOVED_TEMPORARILY  頁面暫時移動到另外一個新的地址

303   SC_SEE_OTHER  客戶端請求的地址必須通過另外的URL來訪問

307   SC_TEMPORARY_REDIRECT  同 SC_MOVED_TEMPORARILY


下面的代碼片段演示如何處理頁面的重定向

Java代碼
  1. client.executeMethod(post);   
  2.   
  3. System.out.println(post.getStatusLine().toString());   
  4.   
  5. post.releaseConnection();   
  6.   
  7. //檢查是否重定向   
  8.   
  9. int statuscode = post.getStatusCode();   
  10.   
  11. if ((statuscode == HttpStatus.SC_MOVED_TEMPORARILY) ||   
  12.   
  13.     (statuscode == HttpStatus.SC_MOVED_PERMANENTLY) ||   
  14.   
  15.     (statuscode == HttpStatus.SC_SEE_OTHER) ||   
  16.   
  17.     statuscode == HttpStatus.SC_TEMPORARY_REDIRECT))    
  18.   
  19.   
  20.     //讀取新的URL地址   
  21.   
  22.     Header header = post.getResponseHeader("location");   
  23.   
  24.     if (header != null)   
  25.     {   
  26.   
  27.         String newuri = header.getValue();   
  28.   
  29.         if ((newuri == null) || (newuri.equals("")))   
  30.   
  31.                    newuri = "/";   
  32.   
  33.   
  34.         GetMethod redirect = new GetMethod(newuri);   
  35.   
  36.         client.executeMethod(redirect);   
  37.   
  38.         System.out.println("Redirect:"+   
  39.                  redirect.getStatusLine().toString());   
  40.   
  41.         redirect.releaseConnection();   
  42.   
  43.     } else  
  44.   
  45.          System.out.println("Invalid redirect");   
  46.   
  47.    }   


4. 模擬輸入用戶名和口令進行登錄


     本小節(jié)應(yīng)該說是HTTP客戶端編程中最常碰見的問題,很多網(wǎng)站的內(nèi)容都只是對注冊用戶可見的,這種情況下就必須要求使用正確的用戶名和口令登錄成功后,方可瀏覽到想要的頁面。因為HTTP協(xié)議是無狀態(tài)的,也就是連接的有效期只限于當前請求,請求內(nèi)容結(jié)束后連接就關(guān)閉了。在這種情況下為了保存用戶的登錄信息必須使用到Cookie機制。以JSP/Servlet為例,當瀏覽器請求一個JSP或者是Servlet的頁面時,應(yīng)用服務(wù)器會返回一個參數(shù),名為jsessionid(因不同應(yīng)用服務(wù)器而異),值是一個較長的唯一字符串的Cookie,這個字符串值也就是當前訪問該站點的會話標識。瀏覽器在每訪問該站點的其他頁面時候都要帶上jsessionid這樣的Cookie信息,應(yīng)用服務(wù)器根據(jù)讀取這個會話標識來獲取對應(yīng)的會話信息。

     對于需要用戶登錄的網(wǎng)站,一般在用戶登錄成功后會將用戶資料保存在服務(wù)器的會話中,這樣當訪問到其他的頁面時候,應(yīng)用服務(wù)器根據(jù)瀏覽器送上的Cookie中讀取當前請求對應(yīng)的會話標識以獲得對應(yīng)的會話信息,然后就可以判斷用戶資料是否存在于會話信息中,如果存在則允許訪問頁面,否則跳轉(zhuǎn)到登錄頁面中要求用戶輸入賬號和口令進行登錄。這就是一般使用JSP開發(fā)網(wǎng)站在處理用戶登錄的比較通用的方法。
 
     對于HTTP的客戶端來講,如果要訪問一個受保護的頁面時就必須模擬瀏覽器所做的工作,首先就是請求登錄頁面,然后讀取Cookie值;再次請求登錄頁面并加入登錄頁所需的每個參數(shù);最后就是請求最終所需的頁面。當然在除第一次請求外其他的請求都需要附帶上 Cookie信息以便服務(wù)器能判斷當前請求是否已經(jīng)通過驗證。


Java代碼
  1. package http.demo;   
  2.   
  3. import org.apache.commons.httpclient.*;   
  4.   
  5. import org.apache.commons.httpclient.cookie.*;   
  6.   
  7. import org.apache.commons.httpclient.methods.*;   
  8.   
  9. /**  
  10.  
  11. * 用來演示登錄表單的示例  
  12.  
  13. */  
  14.   
  15. public class FormLoginDemo {   
  16.   
  17.     static final String LOGON_SITE = "localhost";   
  18.   
  19.     static final int    LOGON_PORT = 8080;   
  20.   
  21.       
  22.   
  23.     public static void main(String[] args) throws Exception{   
  24.   
  25.         HttpClient client = new HttpClient();   
  26.   
  27.         client.getHostConfiguration().setHost(LOGON_SITE, LOGON_PORT);   
  28.   
  29.          
  30.   
  31.        //模擬登錄頁面login.jsp->main.jsp   
  32.   
  33.         PostMethod post = new PostMethod("/main.jsp");   
  34.   
  35.         NameValuePair name = new NameValuePair("name""ld");       
  36.   
  37.         NameValuePair pass = new NameValuePair("password""ld");       
  38.   
  39.         post.setRequestBody(new NameValuePair[]{name,pass});   
  40.   
  41.        int status = client.executeMethod(post);   
  42.   
  43.         System.out.println(post.getResponseBodyAsString());   
  44.   
  45.         post.releaseConnection();   
  46.   
  47.          
  48.   
  49.        //查看cookie信息   
  50.   
  51.         CookieSpec cookiespec = CookiePolicy.getDefaultSpec();   
  52.   
  53.         Cookie[] cookies = cookiespec.match(LOGON_SITE, LOGON_PORT, "/"false, client.getState().getCookies());   
  54.   
  55.        if (cookies.length == 0) {   
  56.   
  57.            System.out.println("None");      
  58.   
  59.        } else {   
  60.   
  61.            for (int i = 0; i < cookies.length; i++) {   
  62.   
  63.                System.out.println(cookies[i].toString());      
  64.   
  65.            }   
  66.   
  67.        }   
  68.   
  69.        //訪問所需的頁面main2.jsp   
  70.   
  71.         GetMethod get = new GetMethod("/main2.jsp");   
  72.   
  73.         client.executeMethod(get);   
  74.   
  75.         System.out.println(get.getResponseBodyAsString());   
  76.   
  77.         get.releaseConnection();   
  78.   
  79.     }   
  80.   
  81. }  


5. 提交XML格式參數(shù)

提交XML格式的參數(shù)很簡單,僅僅是一個提交時候的ContentType問題,下面的例子演示從文件文件中讀取XML信息并提交給服務(wù)器的過程,該過程可以用來測試Web服務(wù)。

Java代碼
  1. import java.io.File;   
  2.   
  3. import java.io.FileInputStream;   
  4.   
  5. import org.apache.commons.httpclient.HttpClient;   
  6.   
  7. import org.apache.commons.httpclient.methods.EntityEnclosingMethod;   
  8.   
  9. import org.apache.commons.httpclient.methods.PostMethod;   
  10.   
  11. /**  
  12.  
  13. * 用來演示提交XML格式數(shù)據(jù)的例子  
  14.  
  15. */  
  16.   
  17. public class PostXMLClient {   
  18.   
  19.     public static void main(String[] args) throws Exception {   
  20.   
  21.         File input = new File(“test.xml”);   
  22.   
  23.         PostMethod post = new PostMethod(“http://localhost:8080/httpclient/xml.jsp”);   
  24.   
  25.         // 設(shè)置請求的內(nèi)容直接從文件中讀取   
  26.   
  27.         post.setRequestBody(new FileInputStream(input));   
  28.   
  29.           
  30.   
  31.         if (input.length() < Integer.MAX_VALUE)   
  32.   
  33.             post.setRequestContentLength(input.length());   
  34.   
  35.         else            post.setRequestContentLength(EntityEnclosingMethod.CONTENT_LENGTH_CHUNKED);   
  36.   
  37.           
  38.   
  39.         // 指定請求內(nèi)容的類型   
  40.   
  41.         post.setRequestHeader("Content-type""text/xml; charset=GBK");   
  42.   
  43.           
  44.   
  45.         HttpClient httpclient = new HttpClient();   
  46.   
  47.         int result = httpclient.executeMethod(post);   
  48.   
  49.         System.out.println("Response status code: " + result);   
  50.   
  51.         System.out.println("Response body: ");   
  52.   
  53.         System.out.println(post.getResponseBodyAsString());   
  54.   
  55.         post.releaseConnection();   
  56.   
  57.     }   
  58.   
  59. }  


6. 通過HTTP上傳文件

        httpclient使用了單獨的一個HttpMethod子類來處理文件的上傳,這個類就是MultipartPostMethod,該類已經(jīng)封裝了文件上傳的細節(jié),我們要做的僅僅是告訴它我們要上傳文件的全路徑即可,下面的代碼片段演示如何使用這個類。

Java代碼
  1. MultipartPostMethod filePost = new MultipartPostMethod(targetURL);   
  2.   
  3. filePost.addParameter("fileName", targetFilePath);   
  4.   
  5. HttpClient client = new HttpClient();   
  6.   
  7. //由于要上傳的文件可能比較大,因此在此設(shè)置最大的連接超時時間   
  8.   
  9. client.getHttpConnectionManager().getParams().setConnectionTimeout(5000);   
  10.   
  11. int status = client.executeMethod(filePost);  


上面代碼中,targetFilePath即為要上傳的文件所在的路徑。

7. 訪問啟用認證的頁面

     我們經(jīng)常會碰到這樣的頁面,當訪問它的時候會彈出一個瀏覽器的對話框要求輸入用戶名和密碼后方可,這種用戶認證的方式不同于我們在前面介紹的基于表單的用戶身份驗證。

    這是HTTP的認證策略,httpclient支持三種認證方式包括: 基本、摘要以及NTLM認證。

    其中基本認證最簡單、通用但也最不安全;摘要認證是在HTTP 1.1中加入的認證方式,
而NTLM則是微軟公司定義的而不是通用的規(guī)范,最新版本的NTLM是比摘要認證還要安全的一種方式。


Java代碼
  1. import org.apache.commons.httpclient.HttpClient;   
  2.   
  3. import org.apache.commons.httpclient.UsernamePasswordCredentials;   
  4.   
  5. import org.apache.commons.httpclient.methods.GetMethod;   
  6.   
  7. public class BasicAuthenticationExample {   
  8.   
  9.     public BasicAuthenticationExample() {   
  10.   
  11.     }   
  12.   
  13.     public static void main(String[] args) throws Exception {   
  14.   
  15.         HttpClient client = new HttpClient();   
  16.   
  17.         client.getState().setCredentials(   
  18.   
  19.             "www.verisign.com",   
  20.   
  21.             "realm",   
  22.   
  23.             new UsernamePasswordCredentials("username""password")   
  24.   
  25.         );   
  26.   
  27.         GetMethod get = new GetMethod("https://www.verisign.com/products/index.html");   
  28.   
  29.         get.setDoAuthentication( true );   
  30.   
  31.         int status = client.executeMethod( get );   
  32.   
  33.         System.out.println(status+""+ get.getResponseBodyAsString());   
  34.   
  35.         get.releaseConnection();   
  36.   
  37.     }   
  38.   
  39. }  


8. 多線程模式下使用httpclient
  
    多線程同時訪問httpclient,例如同時從一個站點上下載多個文件。對于同一個HttpConnection 同一個時間只能有一個線程訪問,為了保證多線程工作環(huán)境下不產(chǎn)生沖突,httpclient使用了一個多線程連接管理器類:MultiThreadedHttpConnectionManager,要使用這個類很簡單,只需要在構(gòu)造HttpClient實例的時候傳入即可,代碼如下:

Java代碼
  1. MultiThreadedHttpConnectionManager connectionManager =   
  2.   
  3.    new MultiThreadedHttpConnectionManager();   
  4.   
  5. HttpClient client = new HttpClient(connectionManager);  


以后盡管訪問client實例即可。
本站僅提供存儲服務(wù),所有內(nèi)容均由用戶發(fā)布,如發(fā)現(xiàn)有害或侵權(quán)內(nèi)容,請點擊舉報。
打開APP,閱讀全文并永久保存 查看更多類似文章
猜你喜歡
類似文章
用HttpClient來模擬瀏覽器GET POST
HttpClient登錄人人網(wǎng)
HttpClient中使用代理連接
運用Apache HttpClient實作Get與Post動作 - 小嘴冰涼 - ITey...
Apache Commons工具集簡介
httpclient 學(xué)習(xí)測試 實例 示例
更多類似文章 >>
生活服務(wù)
分享 收藏 導(dǎo)長圖 關(guān)注 下載文章
綁定賬號成功
后續(xù)可登錄賬號暢享VIP特權(quán)!
如果VIP功能使用有故障,
可點擊這里聯(lián)系客服!

聯(lián)系客服