httpClient工具类
依赖
<dependency>
<groupId>com.ning</groupId>
<artifactId>async-http-client</artifactId>
<version>1.8.13</version>
</dependency>
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
<version>4.5.9</version>
</dependency>
代码
import org.apache.commons.lang3.StringUtils;
import org.apache.http.HttpEntity;
import org.apache.http.NameValuePair;
import org.apache.http.StatusLine;
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.HttpPost;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.conn.ssl.SSLContextBuilder;
import org.apache.http.conn.ssl.TrustStrategy;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.net.ssl.SSLContext;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import java.util.*;
import java.util.Map.Entry;
/**
* 跨域工具类
*/
public class CrossDomainTool {
private static Logger log = LoggerFactory.getLogger(CrossDomainTool.class);
/**
* post的req.getParameterMap()
*
* @param req
* @return
*/
public static Map<String, String> getRequestParamMap(HttpServletRequest req) {
Map<String, String> notifyMap = new HashMap<>();
Map<String, String[]> parameterMap = req.getParameterMap();
for (Entry<String, String[]> stringEntry : parameterMap.entrySet()) {
if (stringEntry.getValue() != null
&& stringEntry.getValue().length > 0) {
notifyMap.put(stringEntry.getKey(), stringEntry.getValue()[0]);
}
}
return notifyMap;
}
// /**
// * 响应
// *
// * @param response
// */
// public static void doResponse(HttpServletResponse response,
// SystemResult systemResult) {
// log.info("响应参数打印|systemResult={}",
// JSONObject.toJSONString(systemResult));
// response.setContentType("application/json");
// PrintWriter out = null;
// try {
// out = response.getWriter();
// out.write(JSONObject.toJSONString(systemResult));
// } catch (IOException e) {
// // TODO Auto-generated catch block
// e.printStackTrace();
// log.error("系统响应异常|e={}", e);
// } finally {
// out.flush();
// out.close();
// }
// }
/**
* 响应
*
* @param response
*/
// public static void doResponse(HttpServletResponse response, String code,
// String msg, Object data) {
// log.info("响应参数打印|code={},msg={},data={}", code, msg, data);
// SystemResult systemResult = new SystemResult(code, msg, data);
// response.setContentType("application/json");
// PrintWriter out = null;
// try {
// out = response.getWriter();
// out.write(JSONObject.toJSONString(systemResult));
// } catch (IOException e) {
// // TODO Auto-generated catch block
// e.printStackTrace();
// log.error("系统响应异常|e={}", e);
// } finally {
// out.flush();
// out.close();
// }
// }
/**
* @description:使用httpClient对象执行 post 请求
* @param: uri 需要跨域请求的uri , formDataMap 模拟表单需要提交数据 (name - value 形式)
*/
public static String doPost(String uri, Map<String, Object> formDataMap)
throws ClientProtocolException, IOException {
if (StringUtils.isBlank(uri)) {
return null;
}
// 1、创建httpClient 对象
CloseableHttpClient httpClient = HttpClients.createDefault();
// 2、 创建post 对象
HttpPost post = new HttpPost(uri);
// 3、 创建一个list形式数据,模拟提交表单。
List<NameValuePair> formDataList = new ArrayList<>();
// TODO: 这里可以遍历模拟表单传递过来的数据 formDataMap
Iterator<Entry<String, Object>> iterator = formDataMap.entrySet()
.iterator();
while (iterator.hasNext()) {
Entry<String, Object> next = iterator.next();
String key = next.getKey();
String value = next.getValue().toString();
formDataList.add(new BasicNameValuePair(key, value));
}
// formDataList.add(new BasicNameValuePair("ids", "110"));
// formDataList.add(new BasicNameValuePair("name", "httpClient 请求数据"));
// 4、 把表单数据包装到entity 对象中 (StringEntity)
StringEntity formData = new UrlEncodedFormEntity(formDataList, "UTF-8");
post.setEntity(formData);
//post.setHeader("Content-type", "application/json;charset=utf-8");
// 5、 执行post请求
CloseableHttpResponse response = httpClient.execute(post);
// 6、 获取响应数据
HttpEntity entity = response.getEntity();
StatusLine statusLine = response.getStatusLine();
// 7、 响应数据转换为字符串
String data = EntityUtils.toString(entity,"utf-8");
// 8、 关闭 httpClient对象、关闭 response
response.close();
httpClient.close();
return data;
}
private static CloseableHttpClient buildSSLCloseableHttpClient()
throws Exception {
SSLContext sslContext = new SSLContextBuilder().loadTrustMaterial(null,
new TrustStrategy() {
// 信任所有
public boolean isTrusted(X509Certificate[] chain,
String authType) throws CertificateException {
return true;
}
}).build();
// ALLOW_ALL_HOSTNAME_VERIFIER:这个主机名验证器基本上是关闭主机名验证的,实现的是一个空操作,并且不会抛出javax.net.ssl.SSLException异常。
SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(
sslContext, new String[] { "TLSv1" }, null,
SSLConnectionSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
return HttpClients.custom().setSSLSocketFactory(sslsf).build();
}
// private static CloseableHttpClient getInstance() throws NoSuchProviderException, NoSuchAlgorithmException, KeyManagementException {
// // 创建SSLContext对象,并使用我们指定的信任管理器初始化
// TrustManager[] tm = { new MyX509TrustManager() };
// SSLContext sslContext = SSLContext.getInstance("SSL", "SunJSSE");
// sslContext.init(null, tm, new java.security.SecureRandom());
// // 从上述SSLContext对象中得到SSLSocketFactory对象
// SSLSocketFactory ssf = sslContext.getSocketFactory();
// return HttpClients.custom().setSSLSocketFactory(ssf).build();
// }
public static String doPostSSL(String uri, Map<String, Object> formDataMap)
throws Exception {
if (StringUtils.isBlank(uri)) {
return null;
}
// 1、创建httpClient 对象
CloseableHttpClient httpClient = buildSSLCloseableHttpClient();
// 2、 创建post 对象
HttpPost post = new HttpPost(uri);
// 3、 创建一个list形式数据,模拟提交表单。
List<NameValuePair> formDataList = new ArrayList<>();
// TODO: 这里可以遍历模拟表单传递过来的数据 formDataMap
Iterator<Entry<String, Object>> iterator = formDataMap.entrySet()
.iterator();
while (iterator.hasNext()) {
Entry<String, Object> next = iterator.next();
String key = next.getKey();
String value = next.getValue().toString();
formDataList.add(new BasicNameValuePair(key, value));
}
// formDataList.add(new BasicNameValuePair("ids", "110"));
// formDataList.add(new BasicNameValuePair("name", "httpClient 请求数据"));
// 4、 把表单数据包装到entity 对象中 (StringEntity)
StringEntity formData = new UrlEncodedFormEntity(formDataList, "UTF-8");
post.setEntity(formData);
//post.setHeader("Content-type", "application/json;charset=utf-8");
// 5、 执行post请求
CloseableHttpResponse response = httpClient.execute(post);
// 6、 获取响应数据
HttpEntity entity = response.getEntity();
StatusLine statusLine = response.getStatusLine();
// 7、 响应数据转换为字符串
String data = EntityUtils.toString(entity,"utf-8");
// 8、 关闭 httpClient对象、关闭 response
response.close();
httpClient.close();
return data;
}
}
package com.mozq.pojo;
import com.yuantiao.smartcardms.tools.CmUtil;
import lombok.Data;
import lombok.NoArgsConstructor;
import java.math.BigDecimal;
import java.util.Date;
import java.util.Map;
@Data
@NoArgsConstructor
/*
创建一个信和请求对象,拥有所有必须的参数,其他参数使用默认值
*/
public class XhPayReq {
//1 版本号
private String versionNo = "1.0.0";
//2 商户id
private String merchId;
//3 商户日期 YYYYMMDD
private String merchDate;
//4 商户支付订单号
private String merchOrderId;
//5 订单名称
private String orderName = "smartcard";
//6 子商户id
private String subMerchId;
//7 子商户名称
private String subMerchName;
//8 币种
private String ccy = "CNY";
//9 支付金额
private String txnAmt;
//10 订单生成时间 yyyy-mm-dd HH:MM:SS.SSS
private String orderTime;
//11 前端返回URL
private String frontURL = "http://www.baidu.com";
//12 后台通知URL
private String backURL = "http://www.baidu.com";
//13 商户请求保留域
private String reqReserved;
//14 订单备注
private String orderRemark = "smartcard";
//15 自定义域
private String merchReserved;
//16 是否生成二维码标志
private String qrpCodeFlag;
//17 签名数据
//private String signMsg;
{
Date now = new Date();
merchDate = CmUtil.format("yyyyMMdd", now);
orderTime = CmUtil.format("yyyy-mm-dd HH:MM:SS.SSS", now);
}
public XhPayReq(String merchId, String payNumber, BigDecimal txnAmt, Date merchDate){
this(merchId, payNumber, txnAmt, merchDate, "smartcard", "smartcard", null);
}
public XhPayReq(String merchId, String payNumber, BigDecimal txnAmt, Date merchDate, String orderName, String orderRemark, String qrpCodeFlag){
this.merchId = merchId;
this.merchDate = CmUtil.format("yyyyMMdd", merchDate);
this.merchOrderId = payNumber;
this.orderName = orderName;
this.txnAmt = txnAmt.toString();
this.orderTime = CmUtil.format("yyyy-mm-dd HH:MM:SS.SSS", merchDate);
this.orderRemark = orderRemark;
this.qrpCodeFlag = qrpCodeFlag;
}
public Map<String,String> convert2Map(){
return null;
}
public static void main(String[] args) {
XhPayReq xhPayReq = new XhPayReq("merchId001", "2019001", new BigDecimal("0.01"), new Date());
System.out.println(xhPayReq);
}
}