1. java.net.MalformedURLException: unknown protocol https
ANS: 使用的方法不是 HTTPS 的方式,將jce.jar與jsse.jar導入classpath,在使用https連線函式
2. 頁面停留過久
ANS: 就像打開IE一樣,會叫你點選接受憑證,這時用程式跑就自動停住了,居然不會timeout
<%@ page import="java.net.URL"%> <%@ page import="java.net.URLEncoder"%> <%@ page import="java.net.URLConnection"%> <%@ page import="javax.net.ssl.HttpsURLConnection"%> <%@ page import="javax.net.ssl.HostnameVerifier"%> <%@ page import="javax.net.ssl.HttpsURLConnection"%> <%@ page import="javax.net.ssl.SSLContext"%> <%@ page import="javax.net.ssl.SSLSession"%> <%@ page import="javax.net.ssl.TrustManager"%> <%@ page import="javax.net.ssl.X509TrustManager"%> <%@ page import="javax.security.cert.X509Certificate"%> <%@ page import="javax.security.cert.CertificateException"%> <%@ page import="java.security.SecureRandom"%> /*** * more code * skip */ /***********憑證擷取開始**************/ TrustManager[] trustAllCerts = new TrustManager[] { new X509TrustManager() { public java.security.cert.X509Certificate[] getAcceptedIssuers() { return null; } public void checkClientTrusted(java.security.cert.X509Certificate[] certs,String authType) { } public void checkServerTrusted(java.security.cert.X509Certificate[] certs,String authType) { } } }; HostnameVerifier dummyHostnameVerifier = new HostnameVerifier() { public boolean verify(String hostname, SSLSession session) { return true; } }; SSLContext sc = SSLContext.getInstance("SSL"); sc.init(null, trustAllCerts, new SecureRandom()); HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory()); HttpsURLConnection.setDefaultHostnameVerifier(dummyHostnameVerifier); /***********憑證擷取結束**************/ /***********擷取HTTPS頁面開始**************/ String httpsURL = "<https網址>" try{ url = new URL(httpsURL); Httpshurlconnection hurlc = (Httpshurlconnection) url.openConnection(); hurlc.setRequestMethod("POST"); InputStream inputStream = hurlc.getInputStream(); LineNumberReader reader = new LineNumberReader(new InputStreamReader(inputStream)); while (true) { tmp = reader.readLine(); if (tmp == null) break; out.print(tmp); } } catch (Exception e) { e.printStack(); } /***********憑證擷取結束**************/ /*** * more code * skip */
0 意見:
張貼留言