Java实现https请求

/**
 * @author XuJD
 * @create 2019-01-21 17:21
 **/
public class HttpsUtil {
    private static Logger logger = LoggerFactory.getLogger(HttpsUtil.class);

    public static JSONObject httpsRequest(String requestUrl, String requestMethod, String outputStr) {
        logger.info("send https requestUrl:"+requestUrl);
        logger.info("send https requestMethod:"+requestMethod);
        logger.info("send https param:"+outputStr);
        JSONObject jsonObject = new JSONObject();
        StringBuffer buffer = new StringBuffer();
        InputStream inputStream = null;
        InputStreamReader inputStreamReader = null;
        BufferedReader bufferedReader = null;
        try {
            // 创建SSLContext对象,并使用我们指定的信任管理器初始化
            TrustManager[] tm = {new MyX509TrustManager()};
            SSLContext sslContext = SSLContext.getInstance("SSL", "SunJSSE");
            sslContext.init(null, tm, new java.security.SecureRandom());
            // 从上述SSLContext对象中得到SSLSocketFactory对象
            SSLSocketFactory ssf = sslContext.getSocketFactory();

            URL url = new URL(requestUrl);
            HttpsURLConnection httpUrlConn = (HttpsURLConnection) url.openConnection();
            httpUrlConn.setSSLSocketFactory(ssf);
            /*允许输出*/
            httpUrlConn.setDoOutput(true);
            /*允许输入*/
            httpUrlConn.setDoInput(true);
            /*不允许缓存*/
            httpUrlConn.setUseCaches(false);
            // 设置请求方式(GET/POST)
            httpUrlConn.setRequestMethod(requestMethod);
            /*如果是get请求,明文连接*/
            if (HttpMethod.GET.toString().equalsIgnoreCase(requestMethod)) {
                httpUrlConn.connect();
            }
            // 当有数据需要提交时
            if (!StringUtils.isEmpty(outputStr)) {
                OutputStream outputStream = httpUrlConn.getOutputStream();
                // 注意编码格式,防止中文乱码
                outputStream.write(outputStr.getBytes("UTF-8"));
                outputStream.close();
            }
            // 将请求返回的输入流转换成字json对象
            inputStream = httpUrlConn.getInputStream();
            inputStreamReader = new InputStreamReader(inputStream, "UTF-8");
            bufferedReader = new BufferedReader(inputStreamReader);
            String str = null;
            while ((str = bufferedReader.readLine()) != null) {
                buffer.append(str);
            }
            httpUrlConn.disconnect();
            jsonObject = (JSONObject) JSONObject.parse(buffer.toString());
            logger.info("response code:"+httpUrlConn.getResponseCode());
            logger.info("response jsonObject:"+jsonObject);
        } catch (ConnectException ce) {
            logger.info("Weixin server connection timed out.");
            throw new BusinessException("Weixin server connection timed out.");
        } catch (Exception e) {
            logger.info("https request error:" + e);
            throw new BusinessException("https request error:" + e);
        } finally {
            try {
                // 释放资源
                bufferedReader.close();
                inputStreamReader.close();
                inputStream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return jsonObject;
    }
}

自定义信任管理器

/**
 * @author XuJD
 * @create 2019-01-21 17:24
 **/
public class MyX509TrustManager implements X509TrustManager{
    @Override
    public void checkClientTrusted(X509Certificate[] x509Certificates, String s) throws CertificateException {

    }

    @Override
    public void checkServerTrusted(X509Certificate[] x509Certificates, String s) throws CertificateException {

    }

    @Override
    public X509Certificate[] getAcceptedIssuers() {
        return null;
    }
}

评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值