模拟https类型的get,post请求时,碰到证书不信任,无法正常获取返回内容的异常

解决方案,借助X509TrustManager,再创建httpClient的时候设置信任所有证书,
自己封装的创建closeableHttpClient

public static CloseableHttpClient createHttpsClient() throws Exception {

        //证书信任管理者
        X509TrustManager x509mgr = new X509TrustManager() {
            @Override
            public void checkClientTrusted(X509Certificate[] xcs, String string) {
            }

            @Override
            public void checkServerTrusted(X509Certificate[] xcs, String string) {
            }

            @Override
            public X509Certificate[] getAcceptedIssuers() {
                return null;
            }
        };
        //获取一个SSLContext实例
        SSLContext sslContext = SSLContext.getInstance("TLS");
        //初始化SSLContext实例
        sslContext.init(null, new TrustManager[]{x509mgr}, new java.security.SecureRandom());
        //构建一个SSLConnectionSocket工厂,设置为信任所有证书
        SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslContext,
                SSLConnectionSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
        //返回CloseableHttpClient对象
        return HttpClients.custom().setSSLSocketFactory(sslsf).build();
    }

用法示例

/**
     * 发送Post请求
     * @param url url
     * @param params json,发送的内容
     * @param headers headers,发送头
     * @return true or false
     */
    public static JSONObject post(String url, String params, String headers){
        CloseableHttpClient closeableHttpClient = null;
        JSONObject result = new JSONObject();
        //建立一个连接
        try {
            closeableHttpClient = createHttpsClient();

            //创建一个HttpPost
            HttpPost httpPost = new HttpPost(url);
            //设置发送的内容
            httpPost.setEntity(new StringEntity(params));
            //设置头信息
            JSONObject jsonObject = JSONObject.parseObject(headers);
            Set keys = jsonObject.keySet();
            for (String key : keys){
                httpPost.setHeader(key,jsonObject.getString(key));
            }
            //发送
            HttpResponse httpResponse = closeableHttpClient.execute(httpPost);
            int returnCode = httpResponse.getStatusLine().getStatusCode();
            if (returnCode == HttpStatus.SC_OK) {
                InputStream is = httpResponse.getEntity().getContent();
                BufferedReader in = new BufferedReader(new InputStreamReader(is));
                StringBuffer buffer = new StringBuffer();
                String line = "";
                while ((line = in.readLine()) != null) {
                    buffer.append(line);
                }
                result.put("code","200");
                result.put("result",JSONObject.parseObject(buffer.toString()));
                return result;
            } else {
                result.put("code","404");
                result.put("result","no result");
                return result;
            }
        } catch (Exception e) {
            e.printStackTrace();
            result.put("code","404");
            result.put("result","no result");
            return result;
        }
    }

你可能感兴趣的:(零碎笔记,java,https请求)