import org.apache.http.HttpEntity;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
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.config.Registry;
import org.apache.http.config.RegistryBuilder;
import org.apache.http.conn.socket.ConnectionSocketFactory;
import org.apache.http.conn.socket.PlainConnectionSocketFactory;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
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.springframework.stereotype.Component;
import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;
import java.io.IOException;
import java.security.KeyManagementException;
import java.security.NoSuchAlgorithmException;
import java.security.cert.CertificateException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
/**
* Author: Pagegle李義根
* Date: 2020/2/22 21:55
* Content:
*/
@Component
public class HttpUtil {
/**
* 繞過驗證
*
* @return
* @throws NoSuchAlgorithmException
* @throws KeyManagementException
*/
public static SSLContext createIgnoreVerifySSL() throws NoSuchAlgorithmException, KeyManagementException {
SSLContext sc = SSLContext.getInstance("SSLv3");
// 實現一個X509TrustManager接口,用於繞過驗證,不用修改裏面的方法
X509TrustManager trustManager = new X509TrustManager() {
@Override
public void checkClientTrusted(
java.security.cert.X509Certificate[] paramArrayOfX509Certificate,
String paramString) throws CertificateException {
}
@Override
public void checkServerTrusted(
java.security.cert.X509Certificate[] paramArrayOfX509Certificate,
String paramString) throws CertificateException {
}
@Override
public java.security.cert.X509Certificate[] getAcceptedIssuers() {
return null;
}
};
sc.init(null, new TrustManager[] { trustManager }, null);
return sc;
}
/**
* 模擬請求
*
* @param url 訪問地址https://api.weixin.qq.com/sns/jscode2session
* @return
* @throws NoSuchAlgorithmException
* @throws KeyManagementException
* @throws IOException
* @throws ClientProtocolException
*/
public String getway(String url) throws KeyManagementException, NoSuchAlgorithmException, ClientProtocolException, IOException {
String encoding="UTF-8";
String body = "";
//採用繞過驗證的方式處理https請求
SSLContext sslcontext = createIgnoreVerifySSL();
// 設置協議http和https對應的處理socket鏈接工廠的對象
Registry<ConnectionSocketFactory> socketFactoryRegistry = RegistryBuilder.<ConnectionSocketFactory>create()
.register("http", PlainConnectionSocketFactory.INSTANCE)
.register("https", new SSLConnectionSocketFactory(sslcontext))
.build();
PoolingHttpClientConnectionManager connManager = new PoolingHttpClientConnectionManager(socketFactoryRegistry);
HttpClients.custom().setConnectionManager(connManager);
//創建自定義的httpclient對象
CloseableHttpClient client = HttpClients.custom().setConnectionManager(connManager).build();
// CloseableHttpClient client = HttpClients.createDefault();
//創建post方式請求對象
HttpGet httpGet = new HttpGet(url);
System.out.println("請求地址:"+url);
//設置header信息
//指定報文頭【Content-type】、【User-Agent】
httpGet.setHeader("Content-type", "application/x-www-form-urlencoded");
httpGet.setHeader("User-Agent", "Mozilla/4.0 (compatible; MSIE 5.0; Windows NT; DigExt)");
//執行請求操作,並拿到結果(同步阻塞)
CloseableHttpResponse response = client.execute(httpGet);
//獲取結果實體
HttpEntity entity = response.getEntity();
if (entity != null) {
//按指定編碼轉換結果實體爲String類型
body = EntityUtils.toString(entity, encoding);
}
EntityUtils.consume(entity);
//釋放鏈接
response.close();
return body;
}
/**
* 模擬請求 form表單提交
*
* @param url 訪問地址 https://api.weixin.qq.com/sns/jscode2session
* @param map 參數列表
* @param encoding 編碼
* @return
* @throws NoSuchAlgorithmException
* @throws KeyManagementException
* @throws IOException
* @throws ClientProtocolException
*/
public static String postway(String url, Map<String,String> map, String encoding) throws KeyManagementException, NoSuchAlgorithmException, ClientProtocolException, IOException {
String body = "";
//採用繞過驗證的方式處理https請求
SSLContext sslcontext = createIgnoreVerifySSL();
// 設置協議http和https對應的處理socket鏈接工廠的對象
Registry<ConnectionSocketFactory> socketFactoryRegistry = RegistryBuilder.<ConnectionSocketFactory>create()
.register("http", PlainConnectionSocketFactory.INSTANCE)
.register("https", new SSLConnectionSocketFactory(sslcontext))
.build();
PoolingHttpClientConnectionManager connManager = new PoolingHttpClientConnectionManager(socketFactoryRegistry);
HttpClients.custom().setConnectionManager(connManager);
//創建自定義的httpclient對象
CloseableHttpClient client = HttpClients.custom().setConnectionManager(connManager).build();
// CloseableHttpClient client = HttpClients.createDefault();
//創建post方式請求對象
HttpPost httpPost = new HttpPost(url);
//裝填參數
List<NameValuePair> nvps = new ArrayList<NameValuePair>();
if(map!=null){
for (Map.Entry<String, String> entry : map.entrySet()) {
nvps.add(new BasicNameValuePair(entry.getKey(), entry.getValue()));
}
}
//設置參數到請求對象中
httpPost.setEntity(new UrlEncodedFormEntity(nvps, encoding));
System.out.println("請求地址:"+url);
System.out.println("請求參數:"+nvps.toString());
//設置header信息
//指定報文頭【Content-type】、【User-Agent】
httpPost.setHeader("Content-type", "application/x-www-form-urlencoded");
httpPost.setHeader("User-Agent", "Mozilla/4.0 (compatible; MSIE 5.0; Windows NT; DigExt)");
//執行請求操作,並拿到結果(同步阻塞)
CloseableHttpResponse response = client.execute(httpPost);
//獲取結果實體
HttpEntity entity = response.getEntity();
if (entity != null) {
//按指定編碼轉換結果實體爲String類型
body = EntityUtils.toString(entity, encoding);
}
EntityUtils.consume(entity);
//釋放鏈接
response.close();
return body;
}
/**
* 模擬請求 Json數據提交
*
* @param url 資源地址
* @param 參數 對傳參實體類進行json轉換,String param=JSONObject.toJSONString(object);
* @param encoding 編碼
* @return
* @throws NoSuchAlgorithmException
* @throws KeyManagementException
* @throws IOException
* @throws ClientProtocolException
*/
public String postway(String url,String param, String encoding) throws KeyManagementException, NoSuchAlgorithmException, ClientProtocolException, IOException {
String body = "";
//採用繞過驗證的方式處理https請求
SSLContext sslcontext = createIgnoreVerifySSL();
// 設置協議http和https對應的處理socket鏈接工廠的對象
Registry<ConnectionSocketFactory> socketFactoryRegistry = RegistryBuilder.<ConnectionSocketFactory>create()
.register("http", PlainConnectionSocketFactory.INSTANCE)
.register("https", new SSLConnectionSocketFactory(sslcontext))
.build();
PoolingHttpClientConnectionManager connManager = new PoolingHttpClientConnectionManager(socketFactoryRegistry);
HttpClients.custom().setConnectionManager(connManager);
//創建自定義的httpclient對象
CloseableHttpClient client = HttpClients.custom().setConnectionManager(connManager).build();
// CloseableHttpClient client = HttpClients.createDefault();
//創建post方式請求對象
HttpPost httpPost = new HttpPost(url);
//設置參數到請求對象中
// httpPost.setEntity(new StringEntity(JSONObject.toJSONString(map), Charset.forName(encoding)));
httpPost.setEntity(new StringEntity(param, Charset.forName(encoding)));
System.out.println("請求地址:"+url);
//設置header信息
//指定報文頭【Content-type】、【User-Agent】
// httpPost.setHeader("Content-type", "application/x-www-form-urlencoded");
httpPost.setHeader("Content-type", "application/json");
httpPost.setHeader("User-Agent", "Mozilla/4.0 (compatible; MSIE 5.0; Windows NT; DigExt)");
//執行請求操作,並拿到結果(同步阻塞)
CloseableHttpResponse response = client.execute(httpPost);
//獲取結果實體
HttpEntity entity = response.getEntity();
if (entity != null) {
//按指定編碼轉換結果實體爲String類型
body = EntityUtils.toString(entity, encoding);
}
EntityUtils.consume(entity);
//釋放鏈接
response.close();
return body;
}
}