使用方法:
使用HttpClient發送請求、接收響應很簡單,一般需要如下幾步即可。
1. 創建HttpClient對象。
2. 創建請求方法的實例,並指定請求URL。如果需要發送GET請求,創建HttpGet對象;如果需要發送POST請求,創建HttpPost對象。
3. 如果需要發送請求參數,可調用HttpGet、HttpPost共同的setParams(HetpParams params)方法來添加請求參數;對於HttpPost對象而言,也可調用setEntity(HttpEntity entity)方法來設置請求參數。
4. 調用HttpClient對象的execute(HttpUriRequest request)發送請求,該方法返回一個HttpResponse。
5. 調用HttpResponse的getAllHeaders()、getHeaders(String name)等方法可獲取服務器的響應頭;調用HttpResponse的getEntity()方法可獲取HttpEntity對象,該對象包裝了服務器的響應內容。程序可通過該對象獲取服務器的響應內容。
6. 釋放連接。無論執行方法是否成功,都必須釋放連接
Maven pom.xml導入httpclient依賴
<!-- https://mvnrepository.com/artifact/org.apache.httpcomponents/httpclient -->
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
<version>4.5.2</version>
</dependency>
代碼:
import org.apache.http.HttpEntity;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class HttpClientUtil {
public static String get(String url){
CloseableHttpClient httpClient = null;
HttpGet httpGet = null;
try {
httpClient = HttpClients.createDefault();
//請求配置
RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(20000)
.setConnectTimeout(20000)
.build();
//創建HttpGet實例
httpGet = new HttpGet(url);
//對HttpGet指定配置
httpGet.setConfig(requestConfig);
//啓動httpget請求
CloseableHttpResponse response = httpClient.execute(httpGet);
HttpEntity entity = response.getEntity();
String reponseInformation = EntityUtils.toString(entity,"UTF-8");
return reponseInformation;
} catch (IOException e) {
e.printStackTrace();
}finally {
try {
if (httpGet != null) {
httpGet.releaseConnection();
}
if (httpClient != null ) {
httpClient.close();
}
}catch (Exception e) {
e.printStackTrace();
}
}
return null;
}
/*
* HTTPCLIENT-POST請求:x-www-form-urlencoded 類型
*
* */
public static String post(String url, Map<String,String> params){
CloseableHttpClient httpClient = null;
HttpPost httpPost = null;
try {
httpClient = HttpClients.createDefault();
//請求配置
RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(20000)
.setConnectTimeout(20000)
.build();
//創建HttpPost實例
httpPost = new HttpPost(url);
//對HttpPost指定配置
httpPost.setConfig(requestConfig);
List<NameValuePair> ps = new ArrayList<>();
for (String key : params.keySet()) {
NameValuePair nv = new BasicNameValuePair(key,params.get(key));
ps.add(nv);
}
UrlEncodedFormEntity requestEntity = new UrlEncodedFormEntity(ps);
httpPost.setEntity(requestEntity);
//啓動httpPost請求
CloseableHttpResponse response = httpClient.execute(httpPost);
HttpEntity entity = response.getEntity();
String reponseInformation = EntityUtils.toString(entity,"UTF-8");
return reponseInformation;
} catch (IOException e) {
e.printStackTrace();
}finally {
try {
if (httpPost != null) {
httpPost.releaseConnection();
}
if (httpClient != null ) {
httpClient.close();
}
}catch (Exception e) {
e.printStackTrace();
}
}
return null;
}
/*
* HTTPCLIENT-POST請求:APPLICATION_JSON類型數據
*
* */
public static String post(String url, String body){
CloseableHttpClient httpClient = null;
HttpPost httpPost = null;
try {
httpClient = HttpClients.createDefault();
//請求配置
RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(20000)
.setConnectTimeout(20000)
.build();
//創建HttpPost實例
httpPost = new HttpPost(url);
//對HttpPost指定配置
httpPost.setConfig(requestConfig);
// List<NameValuePair> ps = new ArrayList<>();
// for (String key : params.keySet()) {
// NameValuePair nv = new BasicNameValuePair(key,params.get(key));
// ps.add(nv);
// }
//闖入的參數,傳入的參數類型爲"APPLICATION_JSON"
StringEntity requestEntity = new StringEntity(body,ContentType.APPLICATION_JSON);
httpPost.setEntity(requestEntity);
//啓動httpPost請求
CloseableHttpResponse response = httpClient.execute(httpPost);
HttpEntity entity = response.getEntity();
String reponseInformation = EntityUtils.toString(entity,"UTF-8");
return reponseInformation;
} catch (IOException e) {
e.printStackTrace();
}finally {
try {
if (httpPost != null) {
httpPost.releaseConnection();
}
if (httpClient != null ) {
httpClient.close();
}
}catch (Exception e) {
e.printStackTrace();
}
}
return null;
}
public static void main (String [] args){
// //GET請求
// String s = get("http://v.juhe.cn/weather/index?format=2&cityname=北京&key=9679a0703822fe67b9cff961ba197b02");
// System.out.println(s);
//POST請求
Map<String,String> map = new HashMap<>();
map.put("subject","4");
map.put("model","a1");
map.put("testType","order");
map.put("key","5d5d6091ba01de0c27e84b4ab2fca5df");
String s1=post("http://v.juhe.cn/jztk/query",map);
System.out.println(s1);
String s2=post("http://v.juhe.cn/wepiao/query","{\"key\":\"24f59d857d2ad45011946fede9ae5d55\"}");
System.out.println(s2);
}
}