使用Java通過HttpClient發送HTTP請求
前言:在目前的一個項目中,我們的項目的資料來源内部的一個完善的移動端系統,想要內建他們系統的資料就得使用Java發送http模拟前端請求他們的接口,由此在項目中使用HttpClient來發送請求通路接口,此篇記錄使用HttpClient的心得。
1.HttpClient介紹
HttpClient是Apache提供的一個用于在Java中處理HTTP請求、響應操作的工具,它不是一個浏覽器隻是一個用戶端的 HTTP 通信實作庫。HttpClient的目标是發送請求和接收HTTP 封包,它不會去緩存内容和執行内嵌的js代碼等相應的浏覽器的功能。
2.HttpClient的使用-流程說明
第一步:使用CloseableHttpClient來建立一個httpClient對象。
第二步:聲明請求類型,并傳入相應的URL。
第三步:使用httpClient的excute()方法來傳遞請求對象,并擷取響應對象。
第四步:擷取伺服器的狀态碼,并判斷該狀态碼是否正常。
第五步:正常的話則将伺服器發送的資料封裝成HttpEntity對象。
第六步:将所得對象轉化成字元串。
第七步:關閉連接配接,釋放資源。
2.HttpClient的使用-代碼
1.依賴
jar包:

ps:需要引入3個主要jar包,httpclient-cache可以不引入。
maven:
org.apache.httpcomponents
httpclient
4.3.3
org.apache.httpcomponents
httpclient-cache
4.2.2
org.apache.httpcomponents
httpcore
4.3.2
org.apache.httpcomponents
httpmime
4.2.2
2. 發送get請求
PS:代碼僅提供參考,需根據業務情況進行修改代碼。
public static String getNeedApprove(String appId,String appPassword,String account) {
String result = "";
CloseableHttpClient httpclient = null;
CloseableHttpResponse res = null;
try {
HttpClientContext context = HttpClientContext.create();
// 建立一個httpClient對象
httpclient = HttpClients.createDefault();
//登陸 從配置檔案中讀取url(也可以寫成參數)
HttpGet httpGet = new HttpGet(Constants.APPLOGIN);
// 設定參數
List formparams = new ArrayList();
formparams.add(new BasicNameValuePair("xxx", appId));
formparams.add(new BasicNameValuePair("xxx", appPassword));
formparams.add(new BasicNameValuePair("xxx", account));
UrlEncodedFormEntity uefEntity = new UrlEncodedFormEntity(formparams, "UTF-8");
httpGet.setEntity(uefEntity);
// 得到響應狀态碼
res = httpclient.execute(httpGet,context);
// 擷取傳回對象
HttpEntity entity = res.getEntity();
// 通過EntityUtils擷取傳回結果内容
result = EntityUtils.toString(entity);
} catch (Exception e) {
e.printStackTrace();
} finally {
// 最後一定要釋放資源
if(httpclient!=null) {
try {
httpclient.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
return result;
}
3. 發送post請求
PS:代碼僅提供參考,需根據業務情況進行修改代碼。
public static String postNeedApprove(String Id,String Password,String account) {
String result = "";
CloseableHttpClient httpclient = null;
CloseableHttpResponse res = null;
try {
HttpClientContext context = HttpClientContext.create();
// 建立一個httpClient對象
httpclient = HttpClients.createDefault();
//登陸 從配置檔案中讀取url(也可以寫成參數)
HttpPost httpPost = new HttpPost(Constants.APPLOGIN);
// 設定參數
List formparams = new ArrayList();
formparams.add(new BasicNameValuePair("xxx", Id));
formparams.add(new BasicNameValuePair("xxx", Password));
formparams.add(new BasicNameValuePair("xxx", account));
UrlEncodedFormEntity uefEntity = new UrlEncodedFormEntity(formparams, "UTF-8");
httpPost.setEntity(uefEntity);
// 得到響應狀态碼
res = httpclient.execute(httpPost,context);
// 擷取傳回對象
HttpEntity entity = res.getEntity();
// 通過EntityUtils擷取傳回結果内容
result = EntityUtils.toString(entity);
} catch (Exception e) {
e.printStackTrace();
} finally {
// 最後一定要釋放資源
if(httpclient!=null) {
try {
httpclient.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
return result;
}
3. 擷取登入的cookie
PS:代碼僅提供參考,需根據業務情況進行修改代碼。
public static String getCookie(String account) {
String mpApi = "";
// 建立存儲cookie的空間
CookieStore store = new BasicCookieStore();
CloseableHttpClient httpclient = null;
HttpPost httppost = null;
try {
httpclient = HttpClients.custom().setDefaultCookieStore(store).build();// 設定逾時時間
// 登陸
httppost = new HttpPost(CommonVar.APPLOGIN); // 測試環境
// 設定請求需傳參數
List formparams = new ArrayList();
formparams.add(new BasicNameValuePair("xxx", CommonVar.ID));
formparams.add(new BasicNameValuePair("xxx", CommonVar.PASSWORD));
formparams.add(new BasicNameValuePair("xxx", account));
UrlEncodedFormEntity uefEntity = new UrlEncodedFormEntity(formparams, "UTF-8");
httppost.setEntity(uefEntity);
// 擷取響應的cookie
CloseableHttpResponse res = httpclient.execute(httppost);
// 周遊cookie存儲store
for (Iterator iterator = store.getCookies().iterator(); iterator.hasNext();) {
Cookie cookie = (Cookie) iterator.next();
System.out.println(cookie.getName() + "," + cookie.getValue());
if (cookie.getName().equals("mpApi")) {
mpApi = cookie.getValue();
}
}
} catch (Exception e) {
e.printStackTrace();
} finally {
if (httpclient != null) {
try {
httpclient.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
return mpApi;
}
4. 帶cookie通路接口
PS:代碼僅提供參考,需根據業務情況進行修改代碼。
public static String queryUser(HttpServletRequest request, String account, String cookie) {
String result = "";
CloseableHttpClient httpclient = null;
HttpPost httppost = null;
try {
// 将擷取的cookie放入CloseableHttpClient中
httpclient = getHttpClient(cookie);
List detailparams = new ArrayList();
detailparams.add(new BasicNameValuePair("xxx", account));
UrlEncodedFormEntity detailEntity = new UrlEncodedFormEntity(detailparams, "UTF-8");
httppost = new HttpPost(CommonVar.QUERYUSER);
httppost.setHeader("Id", CommonVar.ID);
httppost.setEntity(detailEntity);
CloseableHttpResponse res = httpclient.execute(httppost);
HttpEntity entity = res.getEntity();
result = EntityUtils.toString(entity);
} catch (Exception e) {
e.printStackTrace();
} finally {
if (httpclient != null) {
try {
httpclient.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
return result;
}