Java教程

https 连接

本文主要是介绍https 连接,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!
public static  Result httpsRequest(String requestUrl, String requestheader, String requestparams,Boolean retry) throws Exception{
//    logger.info("req---->:" + requestMethod + requestStr);
     Boolean ret = retry;
    HttpsURLConnection httpsConnection = null;
     Result result = new Result();
    try {
        // 创建SSLContext
        SSLContext sslContext = SSLContext.getInstance("SSL");
        TrustManager[] tm = { new TrustManager() };
        // 初始化
        sslContext.init(null, tm, new java.security.SecureRandom());
        // 获取SSLSocketFactory对象
        SSLSocketFactory ssf = sslContext.getSocketFactory();
        HostnameVerifier HostnameVerifier = new HostnameVerifier() {
            @Override
            public boolean verify(String var1, SSLSession var2) {
                    return true;
            }
        };
        JSONObject jsonparam = JSON.parseObject(requestparams);
        Iterator<Map.Entry<String, Object>> para = jsonparam.entrySet().iterator();
        StringBuffer urlparams = new StringBuffer(350);
        while(para.hasNext()){
            Map.Entry<String, Object> entry = para.next();
            urlparams.append(entry.getKey()+"="+entry.getValue()+"&");
        }
        URL url = new URL(requestUrl+"?"+urlparams);
        httpsConnection = (HttpsURLConnection) url.openConnection();
        httpsConnection.setDoOutput(false);
        httpsConnection.setDoInput(true);
        httpsConnection.setConnectTimeout(60000);
        httpsConnection.setReadTimeout(60000);
        httpsConnection.setRequestProperty("Content-Type", "application/json;charset=UTF-8");
        httpsConnection.setRequestProperty("Charset", "UTF-8");
        JSONObject jsonheader = JSON.parseObject(requestheader);
        Iterator<Map.Entry<String, Object>> headers = jsonheader.entrySet().iterator();
        while(headers.hasNext()){
            Map.Entry<String, Object> entry = headers.next();
            httpsConnection.setRequestProperty(entry.getKey(), entry.getValue().toString());
        }
        httpsConnection.setRequestProperty("User-Agent", "Client identifier");
        httpsConnection.setRequestMethod("GET");
        /*
         * httpsConnection.setUseCaches(false);
         * httpsConnection.setRequestMethod(requestMethod);
         */
        // 设置当前实例使用的SSLSoctetFactory
        httpsConnection.setSSLSocketFactory(ssf);
        httpsConnection.setHostnameVerifier(HostnameVerifier);
//        System.setProperty("https.protocols", "TLSv1,TLSv1.1,TLSv1.2");
        httpsConnection.connect();
        // 往服务器端写内容
        // 读取服务器端返回的内容
        InputStream inputStream = httpsConnection.getInputStream();
        try{
            inputStream = httpsConnection.getInputStream();
        }catch (IOException e){
            if(e.getMessage()!=null&&e.getMessage().contains("Server returned HTTP response code: 500 for URL")){
                log.error("response from remote server error code 500!"+e.getMessage());
                throw new Exception("错误码:500"+e.getMessage());
            }else if(e.getMessage()!=null&&e.getMessage().contains("Address already in use: connect")){
                log.error("response from remote server error:"+e.getMessage());
                throw new Exception("错误:address in use"+e.getMessage());
            }
        }
        if (httpsConnection.getResponseCode() != HttpURLConnection.HTTP_OK) {
//             logger.error("connect ezcs service failed: " + httpsConnection.getResponseCode());
             JSONObject responseJson = new JSONObject();
             responseJson.put("result","error:code-"+httpsConnection.getResponseCode());
            result.setCode(-1);
            result.setData("error:code-"+httpsConnection.getResponseCode());
            result.setMsg("失败");
            return result;
        }
        InputStreamReader inputReader = new InputStreamReader(inputStream,"utf-8");
        BufferedReader bufferReader = new BufferedReader(inputReader);
        StringBuffer sb = new StringBuffer();
        String inputLine = null;
        while ((inputLine = bufferReader.readLine()) != null) {
            sb.append(inputLine+"\n");
        }
        bufferReader.close();
        inputReader.close();
        inputStream.close();
//        String response = readResponse(inputStream);
//        Utils.convertStreamToString(inputStream, "utf-8");
//        log.debug("response from service: " + response);
        result.setCode(0);
        result.setData(sb);
        result.setMsg("成功");
        return result;
    }finally {
    if (httpsConnection != null) {
        httpsConnection.disconnect();
    }
}

private static String readResponse(InputStream inputStream) throws Exception {
    byte[] responseBytes = new byte[0];

    while(true) {
        byte[] readedBytes = new byte[1024];
        int readedCount = inputStream.read(readedBytes);
        if (readedCount <= 0) {
            StringBuilder readResponse = new StringBuilder();
            BufferedReader br = new BufferedReader(new InputStreamReader(new ByteArrayInputStream(responseBytes), StandardCharsets.UTF_8));
            Throwable var17 = null;

            try {
                for(String line = br.readLine(); line != null; line = br.readLine()) {
                    readResponse.append(line).append("\r\n");
                }
            } catch (Throwable var13) {
                var17 = var13;
                throw var13;
            } finally {
                if (br != null) {
                    if (var17 != null) {
                        try {
                            br.close();
                        } catch (Throwable var12) {
                            var17.addSuppressed(var12);
                        }
                    } else {
                        br.close();
                    }
                }

            }

            return readResponse.toString();
        }

        byte[] newBytes = new byte[responseBytes.length + readedCount];
        System.arraycopy(responseBytes, 0, newBytes, 0, responseBytes.length);
        System.arraycopy(readedBytes, 0, newBytes, responseBytes.length, readedCount);
        responseBytes = newBytes;
    }
}

static class TrustManager implements X509TrustManager {
    @Override
    public void checkClientTrusted(X509Certificate[] arg0, String arg1) throws CertificateException {

    }
    @Override
    public void checkServerTrusted(X509Certificate[] arg0, String arg1) throws CertificateException {

    }

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

}
这篇关于https 连接的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!