一、依赖导入:
<!--HttpClient-->
<dependency>
<groupId>commons-httpclient</groupId>
<artifactId>commons-httpclient</artifactId>
<version>3.1</version>
</dependency>
<!--CloseableHttpClient-->
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
<version>4.5.10</version>
</dependency>
二、Post请求:
public String doPost(String url, Map<String,Object> map,String accountKey) {
String uuid=UuidUtils.getUUID();
String signFormat = accountKey + uuid;
String sign = DigestUtils.md5Hex(signFormat.getBytes());
//转成json字符串
String params= JSON.toJSONString(map);
CloseableHttpClient httpclient = StringUtils.startsWith("https", url) ? (CloseableHttpClient) SkipHttpsUtil.wrapClient() : HttpClients.createDefault();
// 创建httpPost
HttpPost httpPost = new HttpPost(url);
httpPost.setHeader("Accept", "application/json");
httpPost.setHeader("Content-Type", "application/json");
// header中参数
httpPost.setHeader("accountKey",accountKey);
httpPost.setHeader("sign",sign);
// 请求体参数
StringEntity entity = new StringEntity(params, "UTF-8");
httpPost.setEntity(entity);
CloseableHttpResponse response = null;
try {
response = httpclient.execute(httpPost);
StatusLine status = response.getStatusLine();
int state = status.getStatusCode();
if (state == HttpStatus.SC_OK) {
HttpEntity responseEntity = response.getEntity();
String jsonString = EntityUtils.toString(responseEntity);
return jsonString;
}
}catch (Exception e){
e.printStackTrace();
}
return null;
}
三、SkipHttpSUtil:
import org.apache.http.client.HttpClient;
import org.apache.http.conn.ssl.NoopHostnameVerifier;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
public class SkipHttpsUtil {
//绕过证书
public static HttpClient wrapClient() {
try {
SSLContext ctx = SSLContext.getInstance("TLS");
X509TrustManager tm = new X509TrustManager() {
@Override
public X509Certificate[] getAcceptedIssuers() {
return null;
}
@Override
public void checkClientTrusted(X509Certificate[] arg0,
String arg1) throws CertificateException {
}
@Override
public void checkServerTrusted(X509Certificate[] arg0,
String arg1) throws CertificateException {
}
};
ctx.init(null, new TrustManager[] { tm }, null);
SSLConnectionSocketFactory ssf = new SSLConnectionSocketFactory(
ctx, NoopHostnameVerifier.INSTANCE);
CloseableHttpClient httpclient = HttpClients.custom()
.setSSLSocketFactory(ssf).build();
return httpclient;
} catch (Exception e) {
return HttpClients.createDefault();
}
}
}