基本每个项目都用此类,可以避免每次创建http出现N多wait连接,可以根据自己需求更改
package com.mcp.util;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.mcp.cons.McpCons;
import com.mcp.cons.SmsConstants;
import com.mcp.cons.YeePayConstants;
import org.apache.http.Consts;
import org.apache.http.NameValuePair;
import org.apache.http.client.config.CookieSpecs;
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.client.protocol.HttpClientContext;
import org.apache.http.config.ConnectionConfig;
import org.apache.http.config.MessageConstraints;
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.protocol.HttpContext;
import org.apache.http.util.EntityUtils;
import java.io.IOException;
import java.nio.charset.CodingErrorAction;
import java.text.SimpleDateFormat;
import java.util.*;
public class HttpClientWrapper {
private static CloseableHttpClient httpClient;
protected synchronized static CloseableHttpClient getHttpClient() {
if (httpClient == null) {
PoolingHttpClientConnectionManager conManager = new PoolingHttpClientConnectionManager();
MessageConstraints messageConstraints = MessageConstraints.custom().setMaxHeaderCount(200).setMaxLineLength(2000).build();
//ConnectionConfig
ConnectionConfig connectionConfig = ConnectionConfig.custom()
.setMalformedInputAction(CodingErrorAction.IGNORE)
.setUnmappableInputAction(CodingErrorAction.IGNORE).setCharset(Consts.UTF_8)
.setMessageConstraints(messageConstraints).build();
conManager.setDefaultConnectionConfig(connectionConfig);
RequestConfig defaultRequestConfig = RequestConfig.custom()
.setSocketTimeout(60000)
.setConnectTimeout(60000)
.setCookieSpec(CookieSpecs.IGNORE_COOKIES)
.setConnectionRequestTimeout(60000)
.setStaleConnectionCheckEnabled(true)
.build();
httpClient = HttpClients.custom().setConnectionManager(conManager).setDefaultRequestConfig(defaultRequestConfig).build();
}
return httpClient;
}
public static String mcpPost(String cmd, String body) {
try {
JSONObject cvRequest = new JSONObject();
String DATE_FORMAT = "yyyyMMddHHmmss";
SimpleDateFormat format = new SimpleDateFormat(DATE_FORMAT, Locale.getDefault());
String msgId = UUID.randomUUID().toString().replace("-", "");
String timestamp = format.format(new Date());
JSONObject head = new JSONObject();
head.put("version", McpCons.VERSION);
head.put("messageid", msgId);
head.put("userId", McpCons.USER_ID);
head.put("userType", McpCons.USER_TYPE);
head.put("digest", MD5.MD5Encode(body + timestamp + McpCons.DIGEST));
head.put("digestType", McpCons.DIGEST_TYPE);
head.put("cmd", cmd);
head.put("timestamp", timestamp);
cvRequest.put("head", head);
cvRequest.put("body", body);
HttpPost request = new HttpPost(McpCons.URL);
try {
List<NameValuePair> reqParams = new ArrayList<NameValuePair>();
reqParams.add(new BasicNameValuePair("message", cvRequest.toString()));
request.setEntity(new UrlEncodedFormEntity(reqParams, Consts.UTF_8));
HttpContext context = HttpClientContext.create();
CloseableHttpResponse response = null;
try {
response = getHttpClient().execute(request, context);
String retString = EntityUtils.toString(response.getEntity());
JSONObject obj = JSON.parseObject(retString);
String bodyStr = obj.getString("body");
if (!"".equals(bodyStr)) {
return bodyStr.toString();
} else {
return "";
}
} finally {
if (response != null) {
response.close();
}
}
} catch (Exception e) {
e.printStackTrace();
try {
JSONObject obj = new JSONObject();
obj.put("repCode", "-1");
obj.put("description", "远程请求失败");
return obj.toString();
} catch (Exception ex) {
return null;
}
}
} catch (Exception e) {
return null;
}
}
public static String yeePayPost(String service, String data) {
HttpPost request = new HttpPost(YeePayConstants.RequestUrl.RequestDirectUrl);
List<NameValuePair> reqParams = new ArrayList<NameValuePair>();
reqParams.add(new BasicNameValuePair("service", service));
reqParams.add(new BasicNameValuePair("req", data));
String sign = YeePaySignUtil.sign(data);
reqParams.add(new BasicNameValuePair("sign", sign));
request.setEntity(new UrlEncodedFormEntity(reqParams, Consts.UTF_8));
HttpContext context = HttpClientContext.create();
String res = "";
try {
CloseableHttpResponse response = getHttpClient().execute(request, context);
res = EntityUtils.toString(response.getEntity());
res = new String(res.getBytes("ISO-8859-1"), "UTF-8");
} catch (IOException e) {
e.printStackTrace();
}
return res;
}
public static String smsPost(String mobileNumber, String[] content, String smsType,String plat) {
HttpPost request = new HttpPost(SmsConstants.Config.RequestDirectUrl);
List<NameValuePair> reqParams = new ArrayList<NameValuePair>();
reqParams.add(new BasicNameValuePair(SmsConstants.SmsKeyCons.MOBILE_NUMBER, mobileNumber));
reqParams.add(new BasicNameValuePair(SmsConstants.SmsKeyCons.AGENTFLAG, plat));
reqParams.add(new BasicNameValuePair(SmsConstants.SmsKeyCons.SMS_TYPE, smsType));
String tempContent = Arrays.toString(content);
reqParams.add(new BasicNameValuePair(SmsConstants.SmsKeyCons.CONTENT, tempContent));
String DATE_FORMAT = "yyyyMMddHHmmss";
SimpleDateFormat format = new SimpleDateFormat(DATE_FORMAT, Locale.getDefault());
String timestamp = format.format(new Date());
reqParams.add(new BasicNameValuePair(SmsConstants.SmsKeyCons.TIMESTAMP, timestamp));
String secert=MD5.MD5Encode(mobileNumber + smsType + SmsConstants.Config.SECRET + timestamp).substring(8,24).toUpperCase();
reqParams.add(new BasicNameValuePair(SmsConstants.SmsKeyCons.SECERT, secert));
request.setEntity(new UrlEncodedFormEntity(reqParams, Consts.UTF_8));
HttpContext context = HttpClientContext.create();
String res = "";
try {
CloseableHttpResponse response = getHttpClient().execute(request, context);
res = EntityUtils.toString(response.getEntity());
} catch (IOException e) {
e.printStackTrace();
}
return res;
}
}