請求第三方https接口

  1. 生成證書
    根據第三方提供的.cer證書,咱們能夠用JDK的keytool工具生成keystore密鑰庫文件

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

    b. 輸入密碼(本身給的密碼)
    tomcat

    c.回車提示是否信任此證書(y信任)
    socket

  2. 代碼請求https接口工具

    public static String httpsPost(String url, String json) {
    InputStream inputStream = null;
    String jsonString = "";
    try {
    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");post

    // 得到密匙庫
         KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType());
         ClassPathResource resource = new ClassPathResource("tomcat.keystore");
    
         // 獲取輸入流
         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 httppost = new HttpPost(url);
         StringEntity entity = new StringEntity(json, ContentType.APPLICATION_JSON);
         httppost.setEntity(entity);
    
         // 發起請求
         HttpResponse response = client.execute(httppost);
    
         // 獲取響應
         HttpEntity resEntity = response.getEntity();
         jsonString = EntityUtils.toString(resEntity, "utf-8");
     } catch (Exception e) {
         e.printStackTrace();
     } finally {
         try {
             inputStream.close();
         } catch (IOException e) {
             e.printStackTrace();
         }
     }
     return jsonString;

    }url

相關文章
相關標籤/搜索