如何以编程方式添加自签名证书以从java代码发出HTTPS请求?
发布时间:2020-12-15 04:16:02 所属栏目:Java 来源:网络整理
导读:以下代码片段是从HTTP URL获取JSon响应: private static void getJson(String location) { try { try { createSSLSocket(); URL url = new URL( "https://abc.com/key/one"); HttpURLConnection conn = (HttpURLConnection) url .openConnection(); conn.se
以下代码片段是从HTTP URL获取JSon响应:
private static void getJson(String location) { try { try { createSSLSocket(); URL url = new URL( "https://abc.com/key/one"); HttpURLConnection conn = (HttpURLConnection) url .openConnection(); conn.setRequestMethod("GET"); conn.setRequestProperty("Accept","application/json"); if (conn.getResponseCode() != 200) { throw new RuntimeException("Failed : HTTP error code : " + conn.getResponseCode()); } BufferedReader br = new BufferedReader(new InputStreamReader( (conn.getInputStream()))); String output; System.out.println("Output from Server .... n"); while ((output = br.readLine()) != null) { System.out.println(output); } conn.disconnect(); } catch (MalformedURLException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } catch (Exception ex) { ex.printStackTrace(); } } 但它抛出了SSLHandshaking异常,因为我没有在代码中添加自签名认证异常.我在C#中完成了这个,但在java中没有.我应该执行哪些步骤?需要你的建议:) 提前致谢. 解决方法
您可以将HttpsURLConnection套接字工厂配置为接受所有证书而不进行任何验证:
private class TrustAll implements X509TrustManager { public void checkClientTrusted(X509Certificate[] x509Certificates,String s) throws CertificateException { } public void checkServerTrusted(X509Certificate[] x509Certificates,String s) throws CertificateException { } public X509Certificate[] getAcceptedIssuers() { return new X509Certificate[0]; } } SSLContext ctx = SSLContext.getInstance("TLS"); ctx.init(null,new TrustManager[] { new TrustAll() },null); HttpsURLConnection.setDefaultSSLSocketFactory(ctx.getSocketFactory()); UPDATE 您只需在应用程序启动时调用此代码一次.使用URL.openConnection()打开的所有HTTPS连接都将使用此套接字工厂.另一种解决方案是在createSSLSocket()方法体中添加此代码. (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |