apache httpclient不多介紹這個工具是什么,具體請看官網,不贅述。
進行記錄的原因一個是把掉過坑的地方記住,另一個是自httpclient-4.4開始,官方對代碼進行了很多調整,4.4以前的很多class和method都過時了,而國內之前很多關于httpclient的分享都是4.4之前的。
個人感覺使用Httpclient比較重要的是看它的代碼,和官方的一些例子,可能是網絡知識比較短板的原因,官方的tutorial其實看起來挺不清晰的,感覺主線不明確,不能引導你很好的學習,建議初學的人同時結合官網、源碼、官方例子、tutorial進行學習。
先看第一個demo,把這個東西用起來再說。
/**
* 使用httpclient-4.5.2發送請求
* @author chmod400
* 2016.3.24
*/
public class FirstHttpClientDemo {
public static void main(String[] args) {
try {
String url = "http://www.baidu.com";
// 使用默認配置創建httpclient的實例
CloseableHttpClient client = HttpClients.createDefault();
HttpPost post = new HttpPost(url);
// HttpGet get = new HttpGet(url);
CloseableHttpResponse response = client.execute(post);
// CloseableHttpResponse response = client.execute(get);
// 服務器返回碼
int status_code = response.getStatusLine().getStatusCode();
System.out.println("status_code = " + status_code);
// 服務器返回內容
String respStr = null;
HttpEntity entity = response.getEntity();
if(entity != null) {
respStr = EntityUtils.toString(entity, "UTF-8");
}
System.out.println("respStr = " + respStr);
// 釋放資源
EntityUtils.consume(entity);
} catch (Exception e) {
e.printStackTrace();
}
}
}
這個demo主要是完成基本的交互過程,發送請求,接收消息,如果只是做小程序或者不是特別大并發量的系統,基本已經夠用了。
進行一些說明:
1.需要向服務器發送請求,我們需要一個org.apache.http.client.HttpClient
的實例對象,一般使用的都是org.apache.http.impl.client.CloseableHttpClient
,創建該對象的最簡單方法是CloseableHttpClient client = HttpClients.createDefault();
,HttpClients是負責創建CloseableHttpClient的工廠,現在我們用最簡單的方法就是使用默認配置去創建實例,后面我們再討論有參數定制需求的實例創建方法。我們可以通過打斷點的方式看到這個默認的實例對象的連接管理器 : org.apache.http.conn.HttpClientConnectionManager
、請求配置 : org.apache.http.client.config.RequestConfig
等配置的默認參數,這些都是后面需要了解的。
2.構造請求方法HttpPost post = new HttpPost(url);
表示我們希望用那種交互方法與服務器交互,HttpClient為每種交互方法都提供了一個類:HttpGet,
HttpHead, HttpPost, HttpPut, HttpDelete, HttpTrace, 還有 HttpOptions。
3.向服務器提交請求CloseableHttpResponse response = client.execute(post);
,很明顯`CloseableHttpResponse就是用了處理返回數據的實體,通過它我們可以拿到返回的狀態碼、返回實體等等我們需要的東西。
4.EntityUtils是官方提供一個處理返回實體的工具類,toString方法負責將返回實體裝換為字符串,官方是不太建議使用這個類的,除非返回數據的服務器絕對可信和返回的內容長度是有限的。官方建議是自己使用HttpEntity#getContent()或者HttpEntity#writeTo(OutputStream),需要提醒的是記得關閉底層資源。
5.EntityUtils.consume(entity);
負責釋放資源,通過源碼可知,是需要把底層的流關閉:
InputStream instream = entity.getContent();
if (instream != null) {
instream.close();
}
好了,到此已經完成了httpclient的第一個demo。
jar包地址:Apache HttpClient 4.5.2、Apache HttpCore 4.4