HttpClientUtil調用遠程接口
package com.jeagine.util;
import org.apache.http.HttpEntity;
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.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.URL;
import java.net.URLConnection;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
/**
* httpclient-4.3.1.jar
* @ClassName: HttpClientUtil
* @Description: TODO
* @author zemel
* @date 2017年9月8日 下午3:29:49
*
*/
public class HttpClientUtil {
private static final Logger log = LoggerFactory.getLogger(HttpClientUtil.class);
/**
* 向指定 URL 發送POST方法的請求
* @param url 發送請求的 URL
* @param param 請求參數,請求參數應該是 name1=value1&name2=value2 的形式。
* @return 所代表遠程資源的響應結果
*/
public static String sendPost(String url, String param) {
PrintWriter out = null;
BufferedReader in = null;
String result = "";
try {
URL realUrl = new URL(url);
// 打開和URL之間的連接
URLConnection conn = realUrl.openConnection();
// 設置通用的請求屬性
conn.setRequestProperty("accept", "*/*");
conn.setRequestProperty("connection", "Keep-Alive");
conn.setRequestProperty("user-agent","Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
// 發送POST請求必須設置如下兩行
conn.setDoOutput(true);
conn.setDoInput(true);
//1.獲取URLConnection對象對應的輸出流
out = new PrintWriter(conn.getOutputStream());
//2.中文有亂碼的需要將PrintWriter改爲如下
//out=new OutputStreamWriter(conn.getOutputStream(),"UTF-8")
// 發送請求參數
out.print(param);
// flush輸出流的緩衝
out.flush();
// 定義BufferedReader輸入流來讀取URL的響應
in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
String line;
while ((line = in.readLine()) != null) {
result += line;
}
} catch (Exception e) {
log.error("發送 POST 請求出現異常!"+e);
e.printStackTrace();
}
//使用finally塊來關閉輸出流、輸入流
finally{
try{
if(out!=null){
out.close();
}
if(in!=null){
in.close();
}
}
catch(IOException ex){
ex.printStackTrace();
}
}
log.info("post推送結果:"+result);
return result;
}
/**
* Get帶參請求
* @param url URL
* @param parameter 請求參數Map集合
* @return
*/
public static String getAndParm(String url , Map<String,String> parameter){
//創建HTTPClient客戶端
CloseableHttpClient httpClient = HttpClients.createDefault();
//用於拼接請求參數
StringBuffer buffer = new StringBuffer();
String str = "?";
buffer.append(url).append("?");
Iterator<Map.Entry<String, String>> iterator = parameter.entrySet().iterator();
while (iterator.hasNext()){
Map.Entry<String, String> entry = iterator.next();
str = str + entry.getKey() + "=" + entry.getValue() + "&";
// if (iterator.hasNext()){
// buffer.append(entry.getKey()).append("=").append(entry.getValue()).append("&");
// }else {
// buffer.append(entry.getKey()).append("=").append(entry.getValue());
// }
}
//創建HttpClient請求
HttpGet httpGet = new HttpGet(url+str);
log.info("--------------請求數據中心接口: "+url+str);
//設置長鏈接
httpGet.setHeader("Connection","Keep-alive");
//設置代理
httpGet.setHeader("User-Agent", "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/63.0.3239.132 Safari/537.36");
//設置Cookie
httpGet.setHeader("Cookie", "UM_distinctid=16442706a09352-0376059833914f-3c604504-1fa400-16442706a0b345; CNZZDATA1262458286=1603637673-1530123020-%7C1530123020; JSESSIONID=805587506F1594AE02DC45845A7216A4");
//接收相應結果
CloseableHttpResponse response = null;
String result = "";
try {
response = httpClient.execute(httpGet);
HttpEntity entity = response.getEntity();
result = EntityUtils.toString(entity);
} catch (IOException e) {
e.printStackTrace();
}
//無論如何必須關閉連接!
finally {
if (response != null){
try {
response.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (httpClient != null){
try {
httpClient.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
log.info("--------------數據中心響應數據:" + result);
return result;
}
/**
* Post帶參數請求
* @param url URL
* @param parameter 請求參數Map集合
* @param header 請求頭Map集合
* @return
*/
public static String postAndParm(String url, Map<String,String> parameter ,Map<String,String> header){
//創建HTTPClient客戶端
CloseableHttpClient httpClient = HttpClients.createDefault();
// 創建 HttpPost 請求
HttpPost httpPost = new HttpPost(url);
//設置長鏈接
httpPost.setHeader("Connection","Keep-alive");
//設置代理
httpPost.setHeader("User-Agent", "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/63.0.3239.132 Safari/537.36");
//設置Cookie
httpPost.setHeader("Cookie", "UM_distinctid=16442706a09352-0376059833914f-3c604504-1fa400-16442706a0b345; CNZZDATA1262458286=1603637673-1530123020-%7C1530123020; JSESSIONID=805587506F1594AE02DC45845A7216A4");
//設置請求頭參數
Iterator<Map.Entry<String, String>> headerIterator = header.entrySet().iterator();
while (headerIterator.hasNext()){
Map.Entry<String, String> headerNext = headerIterator.next();
httpPost.setHeader(headerNext.getKey(),headerNext.getValue());
}
// 創建 HttpPost 參數
List<BasicNameValuePair> params = new ArrayList<BasicNameValuePair>();
Iterator<Map.Entry<String,String>> iterator = parameter.entrySet().iterator();
while (iterator.hasNext()){
Map.Entry<String, String> entry = iterator.next();
params.add(new BasicNameValuePair(entry.getKey(), entry.getValue()));
}
//接收相應結果
CloseableHttpResponse response = null;
String result = "";
try {
// 設置 HttpPost 參數
httpPost.setEntity(new UrlEncodedFormEntity(params, "UTF-8"));
response = httpClient.execute(httpPost);
HttpEntity entity = response.getEntity();
result = EntityUtils.toString(entity);
} catch (IOException e) {
e.printStackTrace();
}
//無論如何必須關閉連接!
finally {
if (response != null){
try {
response.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (httpClient != null){
try {
httpClient.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
log.info("--------------數據中心響應數據:" + result);
return result;
}
}
2、maven引入包
<!-- Apache Http Begin -->
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
<version>4.5.5</version>
</dependency>
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>fluent-hc</artifactId>
<version>4.5.5</version>
</dependency>
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpmime</artifactId>
<version>4.5.5</version>
</dependency>