https请求忽略ssl
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.zeekrlife.udepsvctasks.entity.push.Result;
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 java.io.IOException;
import java.nio.charset.Charset;
import java.security.KeyManagementException;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;
@Slf4j
public class HttpClientUtil {
public static JSONObject doPost(String url, String data) {
//创建post请求对象
HttpPost httpPost = new HttpPost(url);
JSONObject jsonObject = new JSONObject();
//创建CloseableHttpClient对象(忽略证书的重点)
CloseableHttpClient client = null;
try {
SSLConnectionSocketFactory scsf = new SSLConnectionSocketFactory(
SSLContexts.custom().loadTrustMaterial(null, new TrustSelfSignedStrategy()).build(),
NoopHostnameVerifier.INSTANCE);
client = HttpClients.custom().setSSLSocketFactory(scsf).build();
} catch (KeyManagementException e) {
e.printStackTrace();
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
} catch (KeyStoreException e) {
e.printStackTrace();
}
try {
//设置请求头
httpPost.setEntity(new StringEntity(data, Charset.forName("utf-8")));
//使用CloseableHttpClient发送请求
CloseableHttpResponse response = client.execute(httpPost);
//获取返回code
int statusCode = response.getStatusLine().getStatusCode();
//根据返回code进行处理
if (statusCode == 200) {
log.info("请求:" + statusCode);
//获取响应结果
HttpEntity entity = response.getEntity();
jsonObject = JSON.parseObject(EntityUtils.toString(entity, "UTF-8"));
} else {
HttpEntity entity = response.getEntity();
jsonObject = JSON.parseObject(EntityUtils.toString(entity, "UTF-8"));
Result result = JSON.toJavaObject(jsonObject, Result.class);
log.info("请求" + statusCode);
log.info("message" + result.getMessage());
return null;
}
} catch (IOException e) {
log.info("请求失败");
log.info(e.getLocalizedMessage());
e.printStackTrace();
}
return jsonObject;
}
}