HttpClient 是 Apache Jakarta Common 下的子項目,可以用來提供高效的、最新的、功能豐富的支持 HTTP 協議的客戶端編程工具包,並且它支持 HTTP 協議最新的版本和建議。當前官網最新版介紹頁是:http://hc.apache.org/httpcomponents-client-4.5.x/index.html
許多需要後臺模擬請求的系統或者框架都用的是httpclient。所以作爲一個Java開發人員,有必要學一學。本文提供了一個簡單的demo,供初學者參考。
使用HttpClient發送請求、接收響應很簡單,一般需要如下幾步即可:
1.創建CloseableHttpClient對象。
2.創建請求方法的實例,並指定請求URL。如果需要發送GET請求,創建HttpGet對象;如果需要發送POST請求,創建HttpPost對象。
3.如果需要發送請求參數,可可調用setEntity(HttpEntity entity)方法來設置請求參數。setParams方法已過時(4.4.1版本)。
4.調用HttpGet、HttpPost對象的setHeader(String name, String value)方法設置header信息,或者調用setHeaders(Header[] headers)設置一組header信息。
5.調用CloseableHttpClient對象的execute(HttpUriRequest request)發送請求,該方法返回一個CloseableHttpResponse。
6.調用HttpResponse的getEntity()方法可獲取HttpEntity對象,該對象包裝了服務器的響應內容。程序可通過該對象獲取服務器的響應內容;調用CloseableHttpResponse的getAllHeaders()、getHeaders(String name)等方法可獲取服務器的響應頭。
7.釋放連接。無論執行方法是否成功,都必須釋放連接
具體代碼如下(HttpClient-4.4.1):
/**
* 簡單httpclient實例
*
* @author arron
* @date 2015年11月11日 下午6:36:49
* @version 1.0
*/
public class SimpleHttpClientDemo {
/**
* 模擬請求
*
* @param url 資源地址
* @param map 參數列表
* @param encoding 編碼
* @return
* @throws ParseException
* @throws IOException
*/
public static String send(String url, Map<String,String> map,String encoding) throws ParseException, IOException{
String body = "";
//創建httpclient對象
CloseableHttpClient client = HttpClients.createDefault();
//創建post方式請求對象
HttpPost httpPost = new HttpPost(url);
//裝填參數
List<NameValuePair> nvps = new ArrayList<NameValuePair>();
if(map!=null){
for (Entry<String, String> entry : map.entrySet()) {
nvps.add(new BasicNameValuePair(entry.getKey(), entry.getValue()));
}
}
//設置參數到請求對象中
httpPost.setEntity(new UrlEncodedFormEntity(nvps, encoding));
System.out.println("請求地址:"+url);
System.out.println("請求參數:"+nvps.toString());
//設置header信息
//指定報文頭【Content-type】、【User-Agent】
httpPost.setHeader("Content-type", "application/x-www-form-urlencoded");
httpPost.setHeader("User-Agent", "Mozilla/4.0 (compatible; MSIE 5.0; Windows NT; DigExt)");
//執行請求操作,並拿到結果(同步阻塞)
CloseableHttpResponse response = client.execute(httpPost);
//獲取結果實體
HttpEntity entity = response.getEntity();
if (entity != null) {
//按指定編碼轉換結果實體爲String類型
body = EntityUtils.toString(entity, encoding);
}
EntityUtils.consume(entity);
//釋放鏈接
response.close();
return body;
}
}
在main方法中測試一下:
public static void main(String[] args) throws ParseException, IOException {
String url="http://php.weather.sina.com.cn/iframe/index/w_cl.php";
Map<String, String> map = new HashMap<String, String>();
map.put("code", "js");
map.put("day", "0");
map.put("city", "上海");
map.put("dfc", "1");
map.put("charset", "utf-8");
String body = send(url, map,"utf-8");
System.out.println("交易響應結果:");
System.out.println(body);
System.out.println("-----------------------------------");
map.put("city", "北京");
body = send(url, map, "utf-8");
System.out.println("交易響應結果:");
System.out.println(body);
}
結果如下:
請求地址:http://php.weather.sina.com.cn/iframe/index/w_cl.php
請求參數:[dfc=1, charset=utf-8, day=0, code=js, city=上海]
交易響應結果:
(function(){var w=[];w['上海']=[{s1:'小雨',s2:'小雨',f1:'xiaoyu',f2:'xiaoyu',t1:'21',t2:'16',p1:'≤3',p2:'≤3',d1:'南風',d2:'北風'}];var add={now:'2015-11-16 13:16:23',time:'1447650983',update:'北京時間11月16日08:10更新',error:'0',total:'1'};window.SWther={w:w,add:add};})();//0
-----------------------------------
請求地址:http://php.weather.sina.com.cn/iframe/index/w_cl.php
請求參數:[dfc=1, charset=utf-8, day=0, code=js, city=北京]
交易響應結果:
(function(){var w=[];w['北京']=[{s1:'多雲',s2:'多雲',f1:'duoyun',f2:'duoyun',t1:'9',t2:'1',p1:'≤3',p2:'≤3',d1:'無持續風向',d2:'無持續風向'}];var add={now:'2015-11-16 13:18:35',time:'1447651115',update:'北京時間11月16日08:10更新',error:'0',total:'1'};window.SWther={w:w,add:add};})();//0
現在我們測試一下https鏈接:https://www.qingyidai.com/investmanagement/invest.shtml
public static void main(String[] args) throws ParseException, IOException {
String url = "https://www.qingyidai.com/investmanagement/invest.shtml";
String body = send(url, null, "utf-8");
System.out.println("交易響應結果:");
System.out.println(body);
結果發現,居然正常拿到結果了:
原來如果網站的證書已經被ca機構認證通過了,那麼用HttpClient來調用的話,會直接成功的。不用再單獨配置htts鏈接了。不過如果是自簽名的證書,還是需要配置https的