httpClient強制指定TLS 1.1プロトコルアクセスHTTPS

2244 ワード

 ~~
public static String httpsByTls(String url,Map params) throws Exception{
    //  X509TrustManager , , 
    X509TrustManager trustManager = new X509TrustManager() {
        @Override
        public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException {
        }

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

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

    };

    SSLContext sc = SSLContext.getInstance("TLSv1.1");
    sc.init(null, new TrustManager[] { trustManager }, null);

    SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sc);
    CloseableHttpClient httpclient = HttpClients.custom().setSSLSocketFactory(sslsf).build();
    HttpPost post = new HttpPost(url);
    post.addHeader("Content-Type","application/x-www-form-urlencoded; charset=UTF-8");
    post.getParams().setParameter(HttpMethodParams.HTTP_CONTENT_CHARSET,
            "UTF-8");
    List nameValuePairs = new ArrayList();
    Set set = params.keySet();
    for (Object str : set) {
        nameValuePairs.add(new BasicNameValuePair(str.toString(), params.get(str)));
    }
    post.setEntity(new UrlEncodedFormEntity(nameValuePairs, "UTF-8"));

    CloseableHttpResponse response = httpclient.execute(post);
    String returnStr="";
    try {
        HttpEntity entity = response.getEntity();
        returnStr= EntityUtils.toString(entity);
    } finally {
        response.close();
    }
    return returnStr;
}
public static void main(String[] args) throws Exception {
    String url = "https://192.168.2.176:8080/ytsafe/tourist/queryPunishByYT.shtml";
    Map params = new HashMap<>();
    params.put("year","2019");
    params.put("month","01");
    String returnStr=httpsByTls(url,params);
    System.out.println("returnStr :---"+ returnStr + ", =HttpsUtil.main()");
}