HttpClient是一款用Java寫的很是好用的基於Http協議的客戶端編程工具包。具體舉例來說,用它能夠模擬form表單提交數據動做,能夠模擬訪問網頁動做及獲得網頁源碼內容等等,這兩點或許是咱們在工做中最經常使用到的。 html
這裏也主要是以介紹模擬form表單提交數據來介紹一下HttpClient,準確地講主要是4.x版本,由於我發如今平常中,HttpClient的使用都仍是使用3.x的版本,而如今HttpClient的官網上,都已是最新版本4.1.3了,3.x版本在官網不見絲毫蹤跡,進入到下載頁面也見不着3.x版本的下載。 java
HttpClient對於使用者而言,一個很是大的好處就是它的例子很是豐富,幾乎每一個功能都有對應的例子代碼,這裏講的模擬form表單提交數據也是來源於HttpClient自帶的例子。 apache
1、Get提交方式 編程
DefaultHttpClient httpclient = new DefaultHttpClient(); try { //注:若是參數值爲中文的話,提交過去後可能會是亂碼 HttpGet httpget = new HttpGet("http://www.xxx.com/x.jsp?username=zhangsan&age=20"); HttpResponse response = httpclient.execute(httpget); HttpEntity entity = response.getEntity(); System.out.println("Login form get: " + response.getStatusLine()); //若是entity是流數據則關閉之 EntityUtils.consume(entity); } finally { // When HttpClient instance is no longer needed, // shut down the connection manager to ensure // immediate deallocation of all system resources httpclient.getConnectionManager().shutdown(); }
2、Form表單Post提交方式 jsp
DefaultHttpClient httpclient = new DefaultHttpClient(); try { HttpPost httpost = new HttpPost("http://www.xxx.com/x.jsp?"); List <NameValuePair> nvps = new ArrayList <NameValuePair>(); //提交兩個參數及值 nvps.add(new BasicNameValuePair("age", "20")); nvps.add(new BasicNameValuePair("username", "張三")); //設置表單提交編碼爲UTF-8 httpost.setEntity(new UrlEncodedFormEntity(nvps, HTTP.UTF_8)); HttpResponse response = httpclient.execute(httpost); HttpEntity entity = response.getEntity(); System.out.println("Login form get: " + response.getStatusLine()); EntityUtils.consume(entity); } finally { // When HttpClient instance is no longer needed, // shut down the connection manager to ensure // immediate deallocation of all system resources httpclient.getConnectionManager().shutdown(); }
在提交到的x.jsp中,咱們仍是像日常獲取一個form表單數據那樣處理就好了: 工具
String username = request.getParameter("username");
HttpClient官方網址:http://hc.apache.org/ post
關於HttpClient的例子頁面,見: 編碼
http://hc.apache.org/httpcomponents-client-ga/examples.html spa
或者在下載後的目錄: code
httpcomponents-client-4.1.3_src\httpclient\src\examples 。
目前HttpClient分兩部分,一部分是HttpClient,另外一部分是HttpCore,二者都要下載下來,上面的例子見:
httpcomponents-client-4.1.3_src\httpclient\src\examples\org\apache\http\examples\client\ClientFormLogin.java