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 parameter){
//创建HTTPClient客户端
CloseableHttpClient httpClient = HttpClients.createDefault();
//用于拼接请求参数
StringBuffer buffer = new StringBuffer();
String str = "?";
buffer.append(url).append("?");
Iterator> iterator = parameter.entrySet().iterator();
while (iterator.hasNext()){
Map.Entry 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 parameter ,Map 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> headerIterator = header.entrySet().iterator();
while (headerIterator.hasNext()){
Map.Entry headerNext = headerIterator.next();
httpPost.setHeader(headerNext.getKey(),headerNext.getValue());
}
// 创建 HttpPost 参数
List params = new ArrayList();
Iterator> iterator = parameter.entrySet().iterator();
while (iterator.hasNext()){
Map.Entry 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引入包
org.apache.httpcomponents
httpclient
4.5.5
org.apache.httpcomponents
fluent-hc
4.5.5
org.apache.httpcomponents
httpmime
4.5.5