使用 Apache 工具類 HttpClients 進行 GET、POST請求
一、概述
在Java中進行 HTTP 請求是一種常見的編程需求,尤其是在調用第三方API的時候。因此,瞭解 HTTP 協議的原理、熟悉Apache工具類對此協議的實現至關重要。
HTTP 協議屬於應用層協議,同屬於應用層協議的還有DNS、FTP等協議。HTTP 是基於TCP的可靠傳輸協議,採用的是客戶端/服務器的(C/S)的工作方式,在 HTTP 的通信過程中,首先由客戶端向服務器發起建立鏈接的請求,通過 TCP三次握手來完成,然後客戶端向服務器發出請求,告訴服務器想得到的信息。服務器通過響應返回客戶端需要的信息。最後通過 TCP 四次握手關閉鏈接,從而完成一次基本的通信過程。
由於客戶端與服務器有不同的數據交換需求,爲了更高效的進行數據交換,HTTP 協議定義了多種不同的請求方法,服務器可以針對不同的請求方式進行優化,從而提高客戶端的響應速度和服務器的性能。常見的請求方式有GET, POST, PUT, DELETE等。當需要查詢和獲取服務器資源時,一般使用GET請求;當需要向服務器提交大量表單數據時,POST則更爲常用。
HttpClient 是Apache Jakarta Common 下的子項目,可以用來提供高效的、功能豐富的支持 HTTP 協議的客戶端編程工具包,並且它支持 HTTP 協議最新的版本和建議。熟悉HttpClient 工具類對我們的項目開發非常的有幫助。
二、程序代碼示例
2.1 POST 請求
/*
* POST請求
* 參數是:URL,jsonObject(請求參數封裝成json對象)
*
* */
public static String post(String url,JSONObject jsonObject) {
//創建HttpClients對象
CloseableHttpClient httpClient = HttpClients.createDefault();
//創建post請求對象
HttpPost httpPost = new HttpPost(url);
//創建封裝請求參數對象,設置post請求參數
StringEntity myEntity = new StringEntity(jsonObject.toJSONString(), ContentType.APPLICATION_JSON);
httpPost.setEntity(myEntity);
try {
//執行POST請求,獲取請求結果
HttpResponse httpResponse = httpClient.execute(httpPost);
if (httpResponse.getStatusLine().getStatusCode() == 200) {
// 發送成功
String resutlEntity = EntityUtils.toString(httpResponse.getEntity());
return resutlEntity;
} else {
// 發送失敗
return null;
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally {
try {
if (httpClient != null) {
// 釋放資源
httpClient.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
return null;
}
2.1 GET 請求
/*
* GET請求,如果有請求參數,則拼接到到url後面
* */
public static String get(String url) {
//創建HttpClients對象
CloseableHttpClient httpClient = HttpClients.createDefault();
//創建get請求對象
HttpGet httpGet = new HttpGet(url);
//設置請求配置參數
RequestConfig config = RequestConfig.custom()
.setConnectTimeout(5000)
.setSocketTimeout(5000)
.setConnectionRequestTimeout(5000)
.setRedirectsEnabled(true)
.build();
httpGet.setConfig(config);
try {
//執行get請求
HttpResponse response = httpClient.execute(httpGet);
//獲取返回結果
if (response.getStatusLine().getStatusCode() == 200) {
// 發送成功
String resutlEntity = EntityUtils.toString(response.getEntity());
return resutlEntity;
} else {
// 發送失敗
return null;
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally {
try {
if (httpClient != null) {
// 釋放資源
httpClient.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
return null;
}