请求第三方https接口

  1. 生成证书
    根据第三方提供的.cer证书,我们可以用JDK的keytool工具生成证书

    a. keytool -import -v -file E:\cer\esb.*****-p.com.cn.cer -keystore F:tomcat.keystor

    b. 输入密码(自己给的密码)

    c.回车提示是否信任此证书(y信任)

  2. 代码请求https接口

    public static String httpsPost(String url, String json) throws Exception {
    DefaultHttpClient client = new DefaultHttpClient();
    CloseableHttpClient httpClient = HttpClients.createDefault();
    client.getParams().setParameter(ClientPNames.COOKIE_POLICY, CookiePolicy.BROWSER_COMPATIBILITY);
    client.getParams().setParameter(CoreProtocolPNames.USER_AGENT,
    " Mozilla/5.0 (Windows NT 6.2; rv:18.0) Gecko/20100101 Firefox/18.0");
    // 获得密匙库
    KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType());

             // tomcat.keystore的位置在resources文件夹下
     ClassPathResource resource = new ClassPathResource("tomcat.keystore");
     InputStream inputStream = resource.getInputStream();
    
     // 密匙库的密码
     trustStore.load(inputStream, "123456".toCharArray());
    
     // 注册密匙库
     SSLSocketFactory socketFactory = new SSLSocketFactory(trustStore);
    
     // 不校验域名
     socketFactory.setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
     Scheme sch = new Scheme("https", 443, socketFactory);
     client.getConnectionManager().getSchemeRegistry().register(sch);
     HttpPost httppost1 = new HttpPost(url);
     StringEntity entity = new StringEntity(json, ContentType.APPLICATION_JSON);
     httppost1.setEntity(entity);
     HttpResponse response1 = client.execute(httppost1);
     HttpEntity resEntity1 = response1.getEntity();
     String jsonString = EntityUtils.toString(resEntity1, "utf-8");
     return jsonString;

    }

猜你喜欢

转载自www.cnblogs.com/fanshu/p/10189351.html