Apache的HttpClient可以被用于從客戶端發(fā)送HTTP請求到服務(wù)器端,下面給出一個用HttpClient執(zhí)行GET和POST請求的操作方法
添加maven依賴
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
<version>4.5.2</version>
</dependency>
請求步驟
- 使用幫助類HttpClients創(chuàng)建CloseableHttpClient對象.
- 基于要發(fā)送的HTTP請求類型創(chuàng)建HttpGet或者HttpPost實例.
- 使用addHeader方法添加請求頭部,諸如User-Agent, Accept-Encoding等參數(shù).
- 可調(diào)用HttpGet窟社、HttpPost共同的setParams(HetpParams params)方法來添加請求參數(shù);對于HttpPost對象而言这弧,也可調(diào)用setEntity(HttpEntity entity)方法來設(shè)置請求參數(shù)捷凄。
- 通過執(zhí)行此HttpGet或者HttpPost請求獲取CloseableHttpResponse實例
- 從此CloseableHttpResponse實例中獲取狀態(tài)碼,錯誤信息,以及響應(yīng)頁面等等.
- 釋放連接忱详。無論執(zhí)行方法是否成功,都必須釋放連接
示例如下
public static String httpPost(String host, int port, byte[] buf)
{
CloseableHttpClient httpClient = HttpClients.createDefault();
CloseableHttpResponse httpResponse = null;
BufferedReader reader = null;
StringBuffer response = new StringBuffer();
try {
String url = "http://" + host + ":" + port;
HttpPost httpPost = new HttpPost(url);
RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(6000).setConnectTimeout(6000).build();//設(shè)置請求和傳輸超時時間
httpPost.setConfig(requestConfig);
httpPost.addHeader("User-Agent", "Mozilla/5.0");
ByteArrayEntity entity = new ByteArrayEntity(buf);
httpPost.setEntity(entity);
httpResponse = httpClient.execute(httpPost);
reader = new BufferedReader(new InputStreamReader(
httpResponse.getEntity().getContent()));
String inputLine;
while ((inputLine = reader.readLine()) != null) {
response.append(inputLine);
}
}catch (Exception var){
var.printStackTrace();
}finally {
if(reader != null){
reader.close();
}
if(httpResponse != null){
httpResponse.close();
}
httpClient.close();
}
return response.toString();
}
public void httpGet() {
CloseableHttpClient httpclient = HttpClients.createDefault();
try {
// 創(chuàng)建httpget.
HttpGet httpget = new HttpGet("http://www.baidu.com/");
System.out.println("executing request " + httpget.getURI());
// 執(zhí)行g(shù)et請求.
CloseableHttpResponse response = httpclient.execute(httpget);
try {
// 獲取響應(yīng)實體
HttpEntity entity = response.getEntity();
// 打印響應(yīng)狀態(tài)
System.out.println(response.getStatusLine());
if (entity != null) {
// 打印響應(yīng)內(nèi)容長度
System.out.println("Response content length: " + entity.getContentLength());
// 打印響應(yīng)內(nèi)容
System.out.println("Response content: " + EntityUtils.toString(entity));
}
} finally {
response.close();
}
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (ParseException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
// 關(guān)閉連接,釋放資源
try {
httpclient.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}