package com.itmoll.yinlianpay.until;
import org.apache.http.HttpEntity;
import org.apache.http.NameValuePair;
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.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 java.io.IOException;
import java.util.*;
/**
* 调用第三方httpPost和httpGet请求方式
*/
public class HttpRequestUtil {
private static CloseableHttpClient httpClient;
static {
PoolingHttpClientConnectionManager cm = new PoolingHttpClientConnectionManager();
cm.setMaxTotal(100);// 整个连接池最大连接数
cm.setDefaultMaxPerRoute(20); // 每路由最大连接数,默认值是2
httpClient = HttpClients.custom().setConnectionManager(cm).build();
}
public static String doHttpGet(String url) {
CloseableHttpResponse response = null;
try {
HttpGet httpGet = new HttpGet(url);
RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(30000).setConnectionRequestTimeout(30000).setSocketTimeout(30000).build();
httpGet.setConfig(requestConfig);
// 设置提交方式
httpGet.addHeader("Content-type", "application/json; charset=utf-8");
// 执行http请求
response = httpClient.execute(httpGet);
// 获得http响应体
HttpEntity entity = response.getEntity();
System.out.println("entity:" + entity);
if (entity != null) {
// 响应的结果
String content = EntityUtils.toString(entity, "UTF-8");
return content;
}
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
/**
* 表单方式提交
*/
public static String doHttpPostForm(String url, Map<String,String> param) {
CloseableHttpResponse response = null;
try {
HttpPost httpPost = new HttpPost(url);
RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(30000).setConnectionRequestTimeout(30000).setSocketTimeout(30000).build();
httpPost.setConfig(requestConfig);
// 设置提交方式
httpPost.addHeader("Content-type", "application/x-www-form-urlencoded");
// 添加参数
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
if (param.size() != 0) {
// 将param中的key存在set集合中,通过迭代器取出所有的key,再获取每一个键对应的值
Set keySet = param.keySet();
Iterator it = keySet.iterator();
while (it.hasNext()) {
String k = (String) it.next();// key
String v = param.get(k);// value
nameValuePairs.add(new BasicNameValuePair(k, v));
}
}
httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
// 执行http请求
response = httpClient.execute(httpPost);
// 获得http响应体
HttpEntity entity = response.getEntity();
System.out.println("entity:" + entity);
if (entity != null) {
// 响应的结果
String content = EntityUtils.toString(entity, "UTF-8");
return content;
}
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
}
调用第三方接口,POST表单提交
于 2020-12-25 15:07:29 首次发布