java发送https请求并跳过SSL证书验证

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;

/**
 * @Description TODO
 * @Author gengweiqiang
 * @date 2021/12/13 11:52
 **/
@Slf4j
public class HttpUtils {

    /**
     * 如果你需要发送https请求并跳过ssl证书验证,请使用此方法
     * 条件:请求体格式为json
     *
     * @param url
     * @param body
     * @return
     */
    public static String sendPostByHttps(String url, Map<String, String> body, Map<String, String> header) {

        CloseableHttpResponse response = null;
        // 处理请求路径
        url = UriComponentsBuilder.fromHttpUrl(url)
                .toUriString();
        //创建httpclient对象
        CloseableHttpClient client = null;
        String respBody;
        try {
            client = HttpClients.custom()
                    .setSSLSocketFactory(new SSLConnectionSocketFactory(SSLContexts.custom()
                            //忽略掉对服务器端证书的校验
                            .loadTrustMaterial(null, new TrustSelfSignedStrategy())
                            .build(), NoopHostnameVerifier.INSTANCE))
                    .build();
            //创建post方式请求对象
            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传输,如有需要也可以自己进行方法重载,解决你的问题。

你可能感兴趣的:(java,https)