package com.example.demo.util;
import java.io.IOException;
import java.security.KeyManagementException;
import java.security.NoSuchAlgorithmException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import javax.net.ssl.SSLContext;
import javax.net.ssl.X509TrustManager;
import org.apache.commons.beanutils.ConvertUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.http.HttpEntity;
import org.apache.http.NameValuePair;
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.util.Assert;
public class HttpClientHelper {
public static String post(String url, Map<String, Object> parameterMap) {
Assert.hasText(url, "");
String result = null;
CloseableHttpResponse httpResponse = null;
// 设置协议http和https对应的处理socket链接工厂的对象
CloseableHttpClient httpClient =null;
try {
httpClient=createHttpClient();
HttpPost httpPost = new HttpPost(url);
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
if (parameterMap != null) {
for (Entry<String, Object> entry : parameterMap.entrySet()) {
String name = entry.getKey();
String value = ConvertUtils.convert(entry.getValue());
if (StringUtils.isNotEmpty(name)) {
nameValuePairs.add(new BasicNameValuePair(name, value));
}
}
}
httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs, "UTF-8"));
httpResponse = httpClient.execute(httpPost);
HttpEntity httpEntity = httpResponse.getEntity();
result = EntityUtils.toString(httpEntity, "UTF-8");
EntityUtils.consume(httpEntity);
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
if(httpResponse!=null) {
httpResponse.close();
}
} catch (IOException e1) {
e1.printStackTrace();
}
try {
if(httpClient!=null) {
httpClient.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
return result;
}
public static String get(String url, Map<String, Object> parameterMap) {
Assert.hasText(url, "");
String result = null;
CloseableHttpResponse httpResponse = null;
// 设置协议http和https对应的处理socket链接工厂的对象
CloseableHttpClient httpClient =null;
try {
httpClient=createHttpClient();
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
if (parameterMap != null) {
for (Entry<String, Object> entry : parameterMap.entrySet()) {
String name = entry.getKey();
String value = ConvertUtils.convert(entry.getValue());
if (StringUtils.isNotEmpty(name)) {
nameValuePairs.add(new BasicNameValuePair(name, value));
}
}
}
HttpGet httpGet = new HttpGet(url + (StringUtils.contains(url, "?") ? "&" : "?")
+ EntityUtils.toString(new UrlEncodedFormEntity(nameValuePairs, "UTF-8")));
httpResponse = httpClient.execute(httpGet);
HttpEntity httpEntity = httpResponse.getEntity();
result = EntityUtils.toString(httpEntity, "UTF-8");
EntityUtils.consume(httpEntity);
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
if(httpResponse!=null) {
httpResponse.close();
}
} catch (IOException e1) {
e1.printStackTrace();
}
try {
if(httpClient!=null) {
httpClient.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
return result;
}
public static void main(String[] args) {
String url="https://www.toutiao.com/";
String result = HttpClientHelper.get(url, null);
System.out.println(result);
}
private static CloseableHttpClient createHttpClient() throws NoSuchAlgorithmException, KeyManagementException {
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);
CloseableHttpClient httpClient = HttpClients.custom().setConnectionManager(connManager).build();
return httpClient;
}
/**
* 绕过验证
*
* @return
* @throws NoSuchAlgorithmException
* @throws KeyManagementException
*/
private static SSLContext createIgnoreVerifySSL() throws KeyManagementException, NoSuchAlgorithmException {
// 构造SSL环境,指定SSL版本为3.0,SSLv3更加常用。
SSLContext sc = SSLContext.getInstance("SSLv3");
// 实现一个X509TrustManager接口,用于绕过验证,不用修改里面的方法
X509TrustManager trustManager = new X509TrustManager() {
@Override
public void checkClientTrusted(java.security.cert.X509Certificate[] paramArrayOfX509Certificate,
String paramString) {
}
@Override
public void checkServerTrusted(java.security.cert.X509Certificate[] paramArrayOfX509Certificate,
String paramString) {
}
@Override
public java.security.cert.X509Certificate[] getAcceptedIssuers() {
return null;
}
};
// sc.init(null, new TrustManager[] { trustManager }, null);
sc.init(null, null, null);
return sc;
}
}
分享一个用HttpClient 实现的post和get请求的工具类
猜你喜欢
转载自my.oschina.net/u/3574106/blog/1799423
今日推荐
周排行