验证中...
码云 Gitee IDE 全新上线——支持 Git 管理的轻量在线编码环境
语言: Java
分类: 常用工具包
最后更新于 2018-08-03 16:22
HttpUtil
原始数据 复制代码
import org.apache.commons.collections.MapUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.http.*;
import org.apache.http.client.entity.UrlEncodedFormEntity;
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.NoopHostnameVerifier;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.conn.ssl.TrustStrategy;
import org.apache.http.entity.EntityTemplate;
import org.apache.http.entity.FileEntity;
import org.apache.http.entity.SerializableEntity;
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.ssl.SSLContextBuilder;
import org.apache.http.util.EntityUtils;
import java.io.IOException;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import java.util.*;
public class HttpUtil {
private HttpUtil(){}
private static final String HTTP = "http";
private static final String HTTPS = "https";
private static SSLConnectionSocketFactory sslsf = null;
private static PoolingHttpClientConnectionManager cm = null;
private static SSLContextBuilder builder = null;
static {
try {
builder = new SSLContextBuilder();
// 全部信任 不做身份鉴定
builder.loadTrustMaterial(null, new TrustStrategy() {
@Override
public boolean isTrusted(X509Certificate[] x509Certificates, String s) throws CertificateException {
return true;
}
});
sslsf = new SSLConnectionSocketFactory(builder.build(), new String[]{"SSLv2Hello", "SSLv3", "TLSv1", "TLSv1.2"}, null, NoopHostnameVerifier.INSTANCE);
Registry<ConnectionSocketFactory> registry = RegistryBuilder.<ConnectionSocketFactory>create()
.register(HTTP, new PlainConnectionSocketFactory())
.register(HTTPS, sslsf)
.build();
cm = new PoolingHttpClientConnectionManager(registry);
cm.setMaxTotal(200);//max connection
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* httpClient post请求
* @param url 请求url
* @param header 头部信息
* @param param 请求参数 form提交适用
* @param entity 请求实体 json/xml提交适用
* @return 可能为空 需要处理
* @throws Exception
*
*/
public static String post(String url, Map<String, String> header, Map<String, String> param, HttpEntity entity) throws Exception {
String result = "";
CloseableHttpClient httpClient = null;
try {
httpClient = getHttpClient();
HttpPost httpPost = new HttpPost(url);
// 设置头信息
if (MapUtils.isNotEmpty(header)) {
for (Map.Entry<String, String> entry : header.entrySet()) {
httpPost.addHeader(entry.getKey(), entry.getValue());
}
}
// 设置请求参数
if (MapUtils.isNotEmpty(param)) {
List<NameValuePair> formparams = new ArrayList<NameValuePair>();
for (Map.Entry<String, String> entry : param.entrySet()) {
//给参数赋值
formparams.add(new BasicNameValuePair(entry.getKey(), entry.getValue()));
}
UrlEncodedFormEntity urlEncodedFormEntity = new UrlEncodedFormEntity(formparams, Consts.UTF_8);
httpPost.setEntity(urlEncodedFormEntity);
}
// 设置实体 优先级高
if (entity != null) {
httpPost.setEntity(entity);
}
HttpResponse httpResponse = httpClient.execute(httpPost);
int statusCode = httpResponse.getStatusLine().getStatusCode();
if (statusCode == HttpStatus.SC_OK) {
HttpEntity resEntity = httpResponse.getEntity();
result = EntityUtils.toString(resEntity);
} else {
result = readHttpResponse(httpResponse);
}
} catch (Exception e) {
throw e;
} finally {
if (httpClient != null) {
httpClient.close();
}
}
return result;
}
/**
* httpClient post请求
* @param url 请求url
* @param header 头部信息
* @param param 请求参数 form提交适用
* @return 可能为空 需要处理
* @throws Exception
*
*/
public static String post(String url, Map<String, String> header, Map<String, String> param) throws Exception {
return post(url,header,param,null);
}
/**
* httpClient post请求
* @param url 请求url
* @param param 请求参数 form提交适用
* @return 可能为空 需要处理
* @throws Exception
*
*/
public static String post(String url, Map<String, String> param) throws Exception {
return post(url,null,param,null);
}
/**
* httpClient post请求
* @param url 请求url
* @param header 头部信息
* @return 可能为空 需要处理
* @throws Exception
*
*/
public static String post(String url, Map<String, String> header, HttpEntity entity) throws Exception {
return post(url,header,null,entity);
}
/**
* httpClient post请求
* @param url 请求url
* @return 可能为空 需要处理
* @throws Exception
*
*/
public static String post(String url, HttpEntity entity) throws Exception {
return post(url,null,null,entity);
}
/**
* httpClient get请求
* @param url 请求url
* @param header 头部信息
* @param param 请求参数 form提交适用
* @return 可能为空 需要处理
* @throws Exception
*
*/
public static String get(String url, Map<String, String> header, Map<String, String> param) throws Exception {
String result = "";
CloseableHttpClient httpClient = null;
try {
httpClient = getHttpClient();
url = parseUrl(url, param);
HttpGet httpGet = new HttpGet(url);
// 设置头信息
if (MapUtils.isNotEmpty(header)) {
for (Map.Entry<String, String> entry : header.entrySet()) {
httpGet.addHeader(entry.getKey(), entry.getValue());
}
}
HttpResponse httpResponse = httpClient.execute(httpGet);
int statusCode = httpResponse.getStatusLine().getStatusCode();
if (statusCode == HttpStatus.SC_OK) {
HttpEntity resEntity = httpResponse.getEntity();
result = EntityUtils.toString(resEntity);
} else {
result = readHttpResponse(httpResponse);
}
} catch (Exception e) {
throw e;
} finally {
if (httpClient != null) {
httpClient.close();
}
}
return result;
}
/**
* httpClient get请求
* @param url 请求url
* @param param 请求参数 form提交适用
* @return 可能为空 需要处理
* @throws Exception
*
*/
public static String get(String url, Map<String, String> param) throws Exception {
return get(url,null,param);
}
/**
* httpClient get请求
* @param url 请求url
* @return 可能为空 需要处理
* @throws Exception
*
*/
public static String get(String url) throws Exception {
return get(url,null,null);
}
public static CloseableHttpClient getHttpClient() throws Exception {
RequestConfig requestConfig = RequestConfig.custom()
.setSocketTimeout(60000)//等待响应超时时间
.setConnectionRequestTimeout(5000)//获取请求超时时间
.setConnectTimeout(10000).build();//建立连接超时时间
CloseableHttpClient httpClient = HttpClients.custom()
.setSSLSocketFactory(sslsf)
.setConnectionManager(cm)
.setConnectionManagerShared(true)
.setDefaultRequestConfig(requestConfig)
.build();
return httpClient;
}
public static String readHttpResponse(HttpResponse httpResponse)
throws ParseException, IOException {
StringBuilder builder = new StringBuilder();
// 获取响应消息实体
HttpEntity entity = httpResponse.getEntity();
// 响应状态
builder.append("status:" + httpResponse.getStatusLine());
builder.append("headers:");
HeaderIterator iterator = httpResponse.headerIterator();
while (iterator.hasNext()) {
builder.append("\t" + iterator.next());
}
// 判断响应实体是否为空
if (entity != null) {
String responseString = EntityUtils.toString(entity);
builder.append("response length:" + responseString.length());
builder.append("response content:" + responseString.replace("\r\n", ""));
}
return builder.toString();
}
public static String parseUrl(String url,Map<String,String> params){
if(StringUtils.isBlank(url)){
return null;
}
if(MapUtils.isEmpty(params)){
return url;
}
if(url.contains("?")){
for (Map.Entry<String, String> entry : params.entrySet()) {
url += "&" + entry.getKey() + "=" +entry.getValue();
}
}else{
int c = 0;
for (Map.Entry<String, String> entry : params.entrySet()) {
if(c == 0){
url += "?" + entry.getKey() + "=" +entry.getValue();
c = 1;
}else{
url += "&" + entry.getKey() + "=" +entry.getValue();
}
}
}
return url;
}
public static List<String> urlParamToList(String url){
if(url == null || url.length() == 0){
return new ArrayList<>();
}
int st = url.indexOf("?");
if(st < 0){
return new ArrayList<>();
}
String durl = url.substring(st);
String[] sps = durl.split("\\?|&");
List<String> res = new ArrayList<>();
for (int i = 0; i < sps.length; i++) {
String sp = sps[i];
if(sp != null && sp.length() > 0){
res.add(sp);
}
}
return res;
}
public static Map<String,String> urlParamToMap(String url){
List<String> param = urlParamToList(url);
if(param != null && param.size() > 0){
Map<String,String> map = new HashMap<>();
for (String s : param) {
String[] sps = s.split("=");
if(sps.length == 2){
map.put(sps[0],sps[1]);
}else if(sps.length == 1){
map.put(sps[0],"");
}
}
return map;
}
return new HashMap<>();
}
}

评论列表( 0 )

你可以在登录后,发表评论

搜索帮助