一、連接池參數說明
二、配置信息說明
三、開始封裝
package cn.lqdbh.util;
import java.io.IOException;
import java.net.URISyntaxException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import org.apache.http.Consts;
import org.apache.http.HttpEntity;
import org.apache.http.HttpHost;
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.client.utils.URIBuilder;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.apache.http.client.ResponseHandler;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.BasicResponseHandler;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
public class HttpUtil {
// private static final CloseableHttpClient httpclient = HttpClients.createDefault();
//設置代理訪問
private static HttpHost proxy = new HttpHost("183.154.49.68", 9999);
//請求配置
private static final RequestConfig CONFIG = RequestConfig.custom().setConnectTimeout(5*1000) //創建鏈接的最長時間
.setConnectionRequestTimeout(5*1000) //設置獲取鏈接的最長時間
.setSocketTimeout(10*1000) //設置數據傳輸的最長時間
.setProxy(proxy).build(); //設置代理
//連接池管理器
private PoolingHttpClientConnectionManager cm;
public HttpUtil() {
this.cm = new PoolingHttpClientConnectionManager();
}
/**
* 不設置參數的HttpGet請求
*
* @param url
* @return
*/
public String sendGet(String url) {
CloseableHttpClient httpclient = HttpClients.custom().setConnectionManager(this.cm).build();
HttpGet httpget = new HttpGet(url);
httpget.setConfig(CONFIG);
//設置請求頭
//// httpPost.setHeader("Host", "mobile.yangkeduo.com");
// httpget.setHeader("Connection", "keep-alive");
// httpget.setHeader("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3");
// httpget.setHeader("Origin", "https://mobile.yangkeduo.com");
// httpget.setHeader("User-Agent", "Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/78.0.3904.108 Safari/537.36");
// httpget.setHeader("Content-Type", "application/json;charset=UTF-8");
// httpget.setHeader("Sec-Fetch-Site", "same-origin");
// httpget.setHeader("Sec-Fetch-Mode", "navigate");
// httpget.setHeader("Referer", "https://mobile.yangkeduo.com/?refer_page_name=login&refer_page_id=10169_1576556331450_ryLM6CZ3Od&refer_page_sn=10169");
// httpget.setHeader("Accept-Encoding", "gzip, deflate, br");
// httpget.setHeader("Accept-Language", "zh-CN,zh;q=0.9,en;q=0.8");
// httpget.setHeader("Cookie", "");
CloseableHttpResponse response = null;
String resultString = "";
try {
response = httpclient.execute(httpget);
} catch (IOException e1) {
e1.printStackTrace();
}
try {
HttpEntity entity = response.getEntity();
// 判斷返回狀態是否爲200
if (response.getStatusLine().getStatusCode() == 200) {
resultString = EntityUtils.toString(response.getEntity(), "UTF-8");
} else {
System.out.println("狀態碼爲非200!");
}
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
response.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return resultString;
}
/**
* 設置參數的HttpGet請求
*
* @param url
* @return
*/
public String sendGet(URIBuilder uriBuilder) throws URISyntaxException {
CloseableHttpClient httpclient = HttpClients.custom().setConnectionManager(this.cm).build();
HttpGet httpget = new HttpGet(uriBuilder.build());
httpget.setConfig(CONFIG);
CloseableHttpResponse response = null;
String resultString = "";
try {
response = httpclient.execute(httpget);
} catch (IOException e1) {
e1.printStackTrace();
}
try {
HttpEntity entity = response.getEntity();
// 判斷返回狀態是否爲200
if (response.getStatusLine().getStatusCode() == 200) {
resultString = EntityUtils.toString(response.getEntity(), "UTF-8");
} else {
System.out.println("狀態碼爲非200!");
}
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
response.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return resultString;
}
/**
* 發送不帶參數的HttpPost請求
*
* @param url
* @return
*/
public String sendPost(String url) {
CloseableHttpClient httpclient = HttpClients.custom().setConnectionManager(this.cm).build();
HttpPost httppost = new HttpPost(url);
httppost.setConfig(CONFIG);
CloseableHttpResponse response = null;
try {
response = httpclient.execute(httppost);
} catch (IOException e) {
e.printStackTrace();
}
HttpEntity entity = response.getEntity();
String result = null;
try {
result = EntityUtils.toString(entity);
} catch (Exception e) {
e.printStackTrace();
}
return result;
}
/**
* 發送帶參數的HttpPost請求,參數爲json
*
* @param url
* @param map
* @return
*/
public String sendPost(String url, String json) {
CloseableHttpClient httpClient = HttpClients.custom().setConnectionManager(this.cm).build();
String returnValue = "這是默認返回值,接口調用失敗";
// CloseableHttpClient httpClient = HttpClients.createDefault();
ResponseHandler<String> responseHandler = new BasicResponseHandler();
try {
HttpPost httpPost = new HttpPost(url);
httpPost.setConfig(CONFIG);
//第三步:給httpPost設置JSON格式的參數
StringEntity requestEntity = new StringEntity(json, "utf-8");
requestEntity.setContentEncoding("UTF-8");
httpPost.setHeader("Content-type", "application/json");
httpPost.setEntity(requestEntity);
//第四步:發送HttpPost請求,獲取返回值
returnValue = httpClient.execute(httpPost, responseHandler); //調接口獲取返回值時,必須用此方法
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
httpClient.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
//第五步:處理返回值
return returnValue;
}
}
四、調用說明
1、使用設置參數的Get請求
//需要構建一個設置好參數的uriBuider
2、使用帶參Post請求
if (!openId.isEmpty() && !token.isEmpty()) {
Map<String, Object> param = new HashMap<>();
param.put("touser", openId);
param.put("template_id", "Jnb2e_raye3y9_FBUHmx3PR6izdRuyQIFEhRk");
param.put("page", "pages/logs/logs");
String result = HttpUtil.sendPost(url, JSON.toJSONString(param));//需要將對象專爲json串
System.out.println("請求結果:" + result);
}