Http请求类,基于JDK自带的HttpURLConnectionUtil请求类

/**
 * Http请求类,基于JDK自带的HttpURLConnectionUtil请求类
 */
public class HttpsURLConnectionUtil {
    private static Logger logger = LoggerFactory.getLogger(HttpsURLConnectionUtil.class);

    static {
        try {
            trustAllHttpsCertificates();
            HttpsURLConnection.setDefaultHostnameVerifier(new HostnameVerifier() {
                public boolean verify(String urlHostName, SSLSession session) {
                    return true;
                }
            });
        } catch (Exception e) {
        }
    }

    private static void trustAllHttpsCertificates() throws NoSuchAlgorithmException, KeyManagementException {
        TrustManager[] trustAllCerts = new TrustManager[1];
        trustAllCerts[0] = new TrustAllManager();
        /** JDK1.7是TLS1.0,而JDK1.8是TLSv1.2,要调用ICC框架版本是JDK8,因此这里设置为TLSv1.2 **/
        SSLContext sc = SSLContext.getInstance("TLSv1.2");
        sc.init(null, trustAllCerts, null);
        HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
    }

    private static class TrustAllManager implements X509TrustManager {

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

        public void checkServerTrusted(X509Certificate[] certs, String authType) throws CertificateException {
        }

        public void checkClientTrusted(X509Certificate[] certs, String authType) throws CertificateException {
        }
    }


    /**
     * @param httpUrl 请求对象
     * @return String json字符串格式的响应数据
     **/
    public static String doGet(String httpUrl, Map<String, String> headers) {
        logger.info("HttpsURLConnectionUtil,doGet,URL:{}, headers:{}", httpUrl, headers);
        StringBuilder response = new StringBuilder();
        BufferedReader bufferedReader = null;

        try {
            //创建连接
            URL url = new URL(httpUrl);
            HttpsURLConnection connection = (HttpsURLConnection) url.openConnection();
            //忽略ssl验证
            //disableSslVerification(connection);
            //设置请求方式
            connection.setRequestMethod("GET");
            connection.setRequestProperty("accept", "*/*");
            connection.setRequestProperty("connection", "Keep-Alive");
            connection.setRequestProperty("content-type", "application/x-www-form-urlencoded;charset=UTF-8");
            //设置自定义请求头信息
            setCustomHeader(connection, headers);

            //设置请求超时时间:10秒
            connection.setConnectTimeout(10 * 1000);
            //设置读取超时时间:10秒
            connection.setReadTimeout(10 * 1000);
            //开始连接
            connection.connect();
            if (connection.getResponseCode() == 404) {
                JSONObject result = new JSONObject();
                result.put("code", "404");
                result.put("errMsg", "子系统未安装或接口与版本不匹配");
                return result.toJSONString();
            }
            //获取响应数据
            String readLine = null;
            bufferedReader = new BufferedReader(new InputStreamReader(connection.getInputStream(), "utf-8"));
            while ((readLine = bufferedReader.readLine()) != null) {
                response.append(readLine);
            }
            bufferedReader.close();
        } catch (MalformedURLException e) {
            logger.error("HttpsURLConnectionUtil,doGet,request error:{}", e.getMessage());
            e.printStackTrace();
        } catch (IOException e) {
            logger.error("HttpsURLConnectionUtil,doGet,request error:{}", e.getMessage());
            e.printStackTrace();
        }
        return response.toString();
    }

    /**
     * @param httpUrl 请求地址
     * @param jsonStr json字符串格式的请求数据
     * @return String json字符串格式的响应数据
     **/
    public static String doPost(String httpUrl, String jsonStr, Map<String, String> headers) {
        logger.info("HttpsURLConnectionUtil,doPost,URL:" + httpUrl);
        StringBuilder response = new StringBuilder();
        BufferedReader bufferedReader = null;

        try {
            //创建连接
            URL url = new URL(httpUrl);
            HttpsURLConnection connection = (HttpsURLConnection) url.openConnection();
            //忽略ssl验证
            //disableSslVerification(connection);

            //设置请求方式
            connection.setRequestMethod("POST");
            connection.setRequestProperty("accept", "application/json");
            connection.setRequestProperty("connection", "Keep-Alive");
            connection.setRequestProperty("content-type", "application/json;charset=UTF-8");
            //设置自定义请求头信息
            setCustomHeader(connection, headers);

            connection.setDoOutput(true);
            connection.setDoInput(true);
            //设置请求超时时间:10秒
            connection.setConnectTimeout(10 * 1000);
            //设置读取超时时间:10秒
            connection.setReadTimeout(10 * 1000);
            //设置请求参数
            if (jsonStr != null && !"".equalsIgnoreCase(jsonStr)) {
                OutputStream outputStream = connection.getOutputStream();
                byte[] input = jsonStr.getBytes("utf-8");
                outputStream.write(input, 0, input.length);
                outputStream.flush();
                outputStream.close();
            }
            connection.connect();
            if (connection.getResponseCode() == 404) {
                JSONObject result = new JSONObject();
                result.put("code", "404");
                result.put("errMsg", "子系统未安装或接口与版本不匹配");
                return result.toJSONString();
            }
            //获取响应数据
            String readLine = null;
            bufferedReader = new BufferedReader(new InputStreamReader(connection.getInputStream(), "utf-8"));
            while ((readLine = bufferedReader.readLine()) != null) {
                response.append(readLine);
            }
            bufferedReader.close();
        } catch (MalformedURLException e) {
            logger.error("HttpsURLConnectionUtil,doPost,request error:{}", e.getMessage());
            e.printStackTrace();
        } catch (IOException e) {
            logger.error("HttpsURLConnectionUtil,doPost,request error:{}", e.getMessage());
            e.printStackTrace();
        }

        return response.toString();
    }

    /**
     * @param httpUrl 请求地址
     * @param jsonStr json字符串格式的请求数据
     * @return String json字符串格式的响应数据
     **/
    public static String doPut(String httpUrl, String jsonStr, Map<String, String> headers) {
        logger.info("HttpsURLConnectionUtil,doPut,URL:" + httpUrl);
        StringBuilder response = new StringBuilder();
        BufferedReader bufferedReader = null;

        try {
            //创建连接
            URL url = new URL(httpUrl);
            HttpsURLConnection connection = (HttpsURLConnection) url.openConnection();
            //忽略ssl验证
            //disableSslVerification(connection);

            //设置请求方式
            connection.setRequestMethod("PUT");
            connection.setRequestProperty("accept", "application/json");
            connection.setRequestProperty("connection", "Keep-Alive");
            connection.setRequestProperty("content-type", "application/json;charset=UTF-8");
            //设置自定义请求头信息
            setCustomHeader(connection, headers);

            connection.setDoOutput(true);
            connection.setDoInput(true);
            //设置请求超时时间:10秒
            connection.setConnectTimeout(10 * 1000);
            //设置读取超时时间:10秒
            connection.setReadTimeout(10 * 1000);
            //设置请求参数
            if (jsonStr != null && !"".equalsIgnoreCase(jsonStr)) {
                OutputStream outputStream = connection.getOutputStream();
                byte[] input = jsonStr.getBytes("utf-8");
                outputStream.write(input, 0, input.length);
                outputStream.flush();
                outputStream.close();
            }
            connection.connect();
            if (connection.getResponseCode() == 404) {
                JSONObject result = new JSONObject();
                result.put("code", "404");
                result.put("errMsg", "子系统未安装或接口与版本不匹配");
                return result.toJSONString();
            }
            //获取响应数据
            String readLine = null;
            bufferedReader = new BufferedReader(new InputStreamReader(connection.getInputStream(), "utf-8"));
            while ((readLine = bufferedReader.readLine()) != null) {
                response.append(readLine);
            }
            bufferedReader.close();
        } catch (MalformedURLException e) {
            logger.error("HttpsURLConnectionUtil,doPut,request error:{}", e.getMessage());
            e.printStackTrace();
        } catch (IOException e) {
            logger.error("HttpsURLConnectionUtil,doPut,request error:{}", e.getMessage());
            e.printStackTrace();
        }

        return response.toString();
    }

    /**
     * @param httpUrl 请求地址
     * @param jsonStr json字符串格式的请求数据
     * @return String json字符串格式的响应数据
     **/
    public static String doDelete(String httpUrl, String jsonStr, Map<String, String> headers) {
        logger.info("HttpsURLConnectionUtil,doDelete,URL:" + httpUrl);
        StringBuilder response = new StringBuilder();
        BufferedReader bufferedReader = null;

        try {
            //创建连接
            URL url = new URL(httpUrl);
            HttpsURLConnection connection = (HttpsURLConnection) url.openConnection();
            //忽略ssl验证
            //disableSslVerification(connection);

            //设置请求方式
            connection.setRequestMethod("DELETE");
            connection.setRequestProperty("accept", "application/json");
            connection.setRequestProperty("connection", "Keep-Alive");
            connection.setRequestProperty("content-type", "application/json;charset=UTF-8");
            //设置自定义请求头信息
            setCustomHeader(connection, headers);

            connection.setDoOutput(true);
            connection.setDoInput(true);
            //设置请求超时时间:10秒
            connection.setConnectTimeout(10 * 1000);
            //设置读取超时时间:10秒
            connection.setReadTimeout(10 * 1000);
            //设置请求参数
            if (jsonStr != null && !"".equalsIgnoreCase(jsonStr)) {
                OutputStream outputStream = connection.getOutputStream();
                byte[] input = jsonStr.getBytes("utf-8");
                outputStream.write(input, 0, input.length);
                outputStream.flush();
                outputStream.close();
            }
            connection.connect();
            if (connection.getResponseCode() == 404) {
                JSONObject result = new JSONObject();
                result.put("code", "404");
                result.put("errMsg", "子系统未安装或接口与版本不匹配");
                return result.toJSONString();
            }
            //获取响应数据
            String readLine = null;
            bufferedReader = new BufferedReader(new InputStreamReader(connection.getInputStream(), "utf-8"));
            while ((readLine = bufferedReader.readLine()) != null) {
                response.append(readLine);
            }
            bufferedReader.close();
        } catch (MalformedURLException e) {
            logger.error("HttpsURLConnectionUtil,doDelete,request error:{}", e.getMessage());
            e.printStackTrace();
        } catch (IOException e) {
            logger.error("HttpsURLConnectionUtil,doDelete,request error:{}", e.getMessage());
            e.printStackTrace();
        }

        return response.toString();
    }

    /**
     * 设置自定义请求头信息
     **/
    public static void setCustomHeader(HttpURLConnection connection, Map<String, String> headers) {
        if (!CollectionUtils.isEmpty(headers)) {
            Set set = headers.entrySet();
            Iterator iterator = set.iterator();
            while (iterator.hasNext()) {
                Map.Entry<String, String> entry = (Map.Entry<String, String>) iterator.next();
                String key = entry.getKey();
                String value = entry.getValue();
                connection.setRequestProperty(key, value);
            }
        }
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

一名技术极客

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值