【问题标题】:Exception while fetching JSON response from HTTPS url in Android从 Android 中的 HTTPS url 获取 JSON 响应时出现异常
【发布时间】:2013-01-03 16:44:25
【问题描述】:

我从 HTTPS 得到 Json 响应并得到异常

javax.net.ssl.SSLException: Not trusted server certificate

以下是我的代码,无论我尝试使用 HttpGet 还是 HttpPost,我都会在该行得到异常

HttpResponse httpResponse = httpClient.execute(request);

这些是下面用于从 url 获取数据的代码。

DefaultHttpClient httpClient = new DefaultHttpClient();
        HttpPost request = new HttpPost(urlString);
        HttpResponse httpResponse = httpClient.execute(request);

希望得到这个问题的答案。谢谢。

【问题讨论】:

  • 参见this 使用 DefaultHttpClient 发出 https 请求
  • 不是 json 响应。没有堆栈跟踪。您的服务器使用了您的设备不信任的证书,这就是错误所说的。

标签: android json https


【解决方案1】:

该错误表示无法建立服务器证书的有效性。这可能有多种原因,例如受信任的根证书不可用。

您可以从浏览器连接到该页面吗?

【讨论】:

    【解决方案2】:

    我在为我的学校开发应用程序时遇到了类似的问题。诀窍是创建两个覆盖证书验证的类。一个扩展 HostnameVerifier 并在每次调用 verify() 时返回 true,例如 tthis。另一个class extends X509TrustManager 并覆盖getAcceptedIssuers(),如this

    然后您可以设置 HttpsURLConnection 使用此代码接受所有证书

     HttpsURLConnection.setDefaultHostnameVerifier(new AllVerifier());
     try
      {
       SSLContext sslContext = SSLContext.getInstance("TLS");
       sslContext.init(null, new TrustManager[] { new AllTrustManager() }, null);
       HttpsURLConnection.setDefaultSSLSocketFactory(sslContext.getSocketFactory());
         } catch (KeyManagementException e) {
           e.printStackTrace();
         } catch (NoSuchAlgorithmException e) {
           e.printStackTrace();
       }
    

    这应该可以解决问题。你可以在 run() 方法中看到我是如何在这里使用this 代码的。

    【讨论】:

      猜你喜欢
      • 2011-05-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多