【发布时间】:2012-08-29 03:12:08
【问题描述】:
当我想打开一个 HTTPS 连接时,我得到了 SSL 异常。如何设置 HttpURLConnection 对这个异常不敏感?
我的代码是:
private String getData() {
String response = null;
String connection = "https://www.kamalan.com/";
try {
URL url = new URL(connection);
Log.i(TAG, "Try to open: " + connection);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
int responseCode = conn.getResponseCode();
Log.i(TAG, "Response code is: " + responseCode);
if (responseCode == HttpURLConnection.HTTP_OK) {
BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
if (in != null) {
StringBuilder strBuilder = new StringBuilder();
int ch = 0;
while ((ch = in.read()) != -1)
strBuilder.append((char) ch);
// get returned message and show it
response = strBuilder.toString();
Log.i("JSON returned by server:", response);
}
in.close();
} else {
Log.e(TAG, "Couldn't open connection in getResepiItems()");
}
} catch (SSLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return response;
}
【问题讨论】:
-
@Morrison Chang 这是日志猫
Caused by: java.security.cert.CertificateException: java.security.cert.CertPathValidatorException: Trust anchor for certification path not found.中的错误 -
你看到这个 SO 帖子了吗:stackoverflow.com/questions/6825226/… ?
-
感谢 Morrison 和 Raja,我将方法从打开连接更改为加载到 webView 并在那里获取数据。不过感谢您的建议。如果我回到上述方法,那么我将对其进行测试。
-
@Hesam 不要。这是不安全的。解决证书部署问题,不要只是绕过它。证书检查是 SSL 安全性的关键部分。
-
@Hesam 你错了。您无法使用 HTTP keep-alive 解决证书问题。
标签: java android ssl httpurlconnection