httpclient3.1簡單使用

1.httpclient採用的maven依賴html

<dependency>
  <groupId>commons-httpclient</groupId>
  <artifactId>commons-httpclient</artifactId>
  <version>3.1</version>
</dependency>

2.使用步驟maven

新建一個 HttpClient對象,做爲客戶端post

新建請求方法對象,好比GetMethod 或 PostMethodurl

客戶端執行所建立的GetMethod或PostMethodcode

獲取返回的數據htm

釋放鏈接對象

3.代碼展現get

public static void main(String[] args) {
		HttpClient httpClient = new HttpClient(); //建立客戶端
		String url ="http://news.163.com/16/0602/10/BOI4LUB400014PRF.html";
	       GetMethod getMethod = new GetMethod(url);  
	       try {  
	           int statusCode = httpClient.executeMethod(getMethod);  
	           if (statusCode != HttpStatus.SC_OK) {  //執行成功的標示狀態
	               System.err.println("Method failed: "  
	                       + getMethod.getStatusLine());  
	           }  
	           // 讀取內容  
	           byte[] responseBody = getMethod.getResponseBody();  
	          // String res = getMethod.getResponseBodyAsString();
	          /* 
                    //Post
                    PostMethod postMethod = new PostMethod(url);
	           httpClient.executeMethod(postMethod);
	           System.out.println(postMethod.getResponseBodyAsString());*/

	          處理內容  
	          String html = new String(responseBody); 
                     System.out.printlin(html);
	       } catch (Exception e) {  
	           System.err.println("頁面沒法訪問");  
	       }finally{  //不管成功與否都要釋放鏈接
	        getMethod.releaseConnection();  
	    }  

	}
相關文章
相關標籤/搜索