忽略ssl验证的https的post请求工具类

需apache httpclient 4.4+版本,JDK 1.8
推荐以下依赖:

<dependency>
    <groupId>org.apache.httpcomponents</groupId>
    <artifactId>httpclient</artifactId>
    <version>4.5.13</version>
</dependency>
<dependency>
    <groupId>com.alibaba</groupId>
    <artifactId>fastjson</artifactId>
    <version>1.2.75</version>
</dependency>
<dependency>
    <groupId>org.projectlombok</groupId>
    <artifactId>lombok</artifactId>
    <version>1.18.16</version>
    <scope>provided</scope>
</dependency>

步骤:
1、创建HttpClient(CloseableHttpClient)
2、设置请求头、组装参数(工具类中提供了json传参方法)
3、发送post请求
4、接收反参

import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.NameValuePair;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;

import javax.net.ssl.*;
import java.io.IOException;
import java.security.KeyManagementException;
import java.security.NoSuchAlgorithmException;
import java.security.cert.X509Certificate;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

/**
 * 跳过ssl验证,支持自定义签名SSL证书的HTTPS请求.
 */
@Slf4j
public class SSLClientUtil {

    private static RequestConfig requestConfig = RequestConfig.custom()
            .setSocketTimeout(5000)
            .setConnectTimeout(5000)
            .setConnectionRequestTimeout(5000)
            .build();//设置请求和传输超时时间
    private final static String charset = "UTF-8";

    public static void main(String[] args) throws IOException {
        String jsonStr = "{\n" +
                "  \"id\": 999,\n" +
                "  \"a\": \"bcontent\",\n" +
                "  \"b\": \"汉字测试\"\n" +
                "}";

        JSONObject jsonObject = JSONObject.parseObject(jsonStr);
//        String post = post("https://test.xxx.com/test", jsonObject);
        String post = post("http://localhost:6601/test", jsonStr);
        System.out.println(post);
    }

    /**
     * 忽略SSL证书校验的POST请求.
     * @param url
     * @param params JSONObject
     * @return
     * @throws IOException
     */
    public static String post (String url, JSONObject params) throws IOException {
        return post(url, params.toString());
    }

    /**
     * 忽略SSL证书校验的POST请求.
     * @param url
     * @param JsonStr JSON String
     * @return
     * @throws IOException
     */
    public static String post (String url, String JsonStr) throws IOException {
        StringEntity stringEntity = new StringEntity(JsonStr,charset);
        stringEntity.setContentType(ContentType.APPLICATION_JSON.toString());
        HttpResponse res = post(url, stringEntity);
        if (res.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
            return EntityUtils.toString(res.getEntity(), charset);
        }
        return null;
    }

    /**
     * 忽略SSL证书校验的POST.
     * @param httpUrl
     * @param map Map
     * @return
     */
    public static String post(String httpUrl, Map<String, Object> map) throws IOException {
        //设置参数
        List<NameValuePair> list = new ArrayList<NameValuePair>();
        Iterator iterator = map.entrySet().iterator();
        while(iterator.hasNext()){
            Map.Entry<String,String> entry = (Map.Entry<String, String>) iterator.next();
            list.add(new BasicNameValuePair(entry.getKey(),String.valueOf(entry.getValue())));
        }
        if(list.size() > 0){
            UrlEncodedFormEntity entity = new UrlEncodedFormEntity(list, charset);
            HttpResponse res = post(httpUrl, entity);
            if (res.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
                return EntityUtils.toString(res.getEntity(), charset);
            }
        }
        return null;
    }

    /**
     * 忽略SSL证书校验的POST.
     * @param url
     * @param httpEntity HttpEntity
     * @return
     * @throws IOException
     */
    public static HttpResponse post(String url, HttpEntity httpEntity) throws IOException {
        CloseableHttpClient sslClient = createSSLClient();
        HttpPost post = new HttpPost(url);
        post.setEntity(httpEntity);
        post.setConfig(requestConfig);
        HttpResponse response = sslClient.execute(post);
        return response;
    }

    /**
     * 忽略SSL证书校验的CloseableHttpClient.
     * @return
     */
    public static CloseableHttpClient createSSLClient(){
        // 在JSSE中,证书信任管理器类就是实现了接口X509TrustManager的类。我们可以自己实现该接口,让它信任我们指定的证书。
        // 创建SSLContext对象,并使用我们指定的信任管理器初始化,信任所有
        X509TrustManager x509mgr = new X509TrustManager() {
            //  该方法检查客户端的证书,若不信任该证书则抛出异常
            public void checkClientTrusted(X509Certificate[] xcs, String string) {
            }
            //   该方法检查服务端的证书,若不信任该证书则抛出异常
            public void checkServerTrusted(X509Certificate[] xcs, String string) {
            }
            //  返回受信任的X509证书数组。
            public X509Certificate[] getAcceptedIssuers() {
                return null;
            }
        };
        SSLContext sslContext = null;
        try {
            sslContext = SSLContext.getInstance("TLS");
            sslContext.init(null, new TrustManager[] { x509mgr }, null);
            SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslContext, new HostnameVerifier() {
                @Override
                public boolean verify(String hostname, SSLSession sslSession) {
                    // 对hostname不做验证信任所有,此处有安全隐患
                    return true;
                }
            });
            return HttpClients.custom().setSSLSocketFactory(sslsf).build();
        } catch (NoSuchAlgorithmException e) {
            log.error(e.getMessage(), e);
        } catch (KeyManagementException e) {
            log.error(e.getMessage(), e);
        }
        return HttpClients.createDefault();
    }
}
  • 2
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值