java发送https请求并跳过SSL证书验证
众所周知,https是http的加密版,调用时需要验证和加密数据,因此在ssl验证时,可能会验证不通过,此文的解决方案是跳过验证,进加密数据。
现将本人总结的工具类贴下:
import com.alibaba.fastjson.JSON;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.conn.ssl.NoopHostnameVerifier;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.conn.ssl.TrustSelfSignedStrategy;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.ssl.SSLContexts;
import org.apache.http.util.EntityUtils;
import org.springframework.web.util.UriComponentsBuilder;
import java.io.IOException;
import java.util.Map;
@Slf4j
public class HttpUtils {
public static String sendPostByHttps(String url, Map<String, String> body, Map<String, String> header) {
CloseableHttpResponse response = null;
url = UriComponentsBuilder.fromHttpUrl(url)
.toUriString();
CloseableHttpClient client = null;
String respBody;
try {
client = HttpClients.custom()
.setSSLSocketFactory(new SSLConnectionSocketFactory(SSLContexts.custom()
.loadTrustMaterial(null, new TrustSelfSignedStrategy())
.build(), NoopHostnameVerifier.INSTANCE))
.build();
HttpPost httpPost = new HttpPost(url);
httpPost.setHeader("Content-Type", "application/json");
if (header != null) {
for(String s:header.keySet()){
httpPost.setHeader(s,header.get(s));
}
}
if (body != null) {
httpPost.setEntity(new StringEntity(JSON.toJSONString(body), "utf-8"));
}
response = client.execute(httpPost);
HttpEntity entity = response.getEntity();
if (entity != null) {
respBody = EntityUtils.toString(entity);
return respBody;
}
} catch (Exception e) {
log.error("cmd:sendPostByHttps | result=请求失败 | e={}", ThrowableUtil.getStackTrace(e));
} finally {
try {
if (client != null) {
client.close();
}
if (response != null) {
response.close();
}
} catch (IOException e) {
log.error("cmd:sendPostByHttps | result=关闭资源失败 | e={}", ThrowableUtil.getStackTrace(e));
}
}
return null;
}
}
亲测可行,现在类中只有一个post请求方法,请求体参数用json传输,如有需要也可以自己进行方法重载,解决你的问题。
|