【问题标题】:SSLPeerUnverifiedException while working with HTTPS in android在 android 中使用 HTTPS 时出现 SSLPeerUnverifiedException
【发布时间】:2017-09-18 08:29:40
【问题描述】:

在 android 中,我正在使用带有 HTTPS 协议的 RESTful API

HttpResponse response = null;
                try {
                    HttpClient client = new DefaultHttpClient();
                    HttpGet request = new HttpGet();
                    request.setURI(new URI(UrlConnectionConstants.SCI_TA_AGENT_URL));
                    response = client.execute(request);
                } catch (URISyntaxException e) {
                    e.printStackTrace();
                } catch (ClientProtocolException e) {

                    e.printStackTrace();
                } catch (IOException e) {

                    e.printStackTrace();
                }
               return response;

导致 SSLPeerUnverifiedException。

【问题讨论】:

  • 我认为HttpClient 已被弃用,我建议您将HttpURLConnection 用于http 连接和HttpsURLConnection 用于https 连接更多信息stackoverflow.com/questions/22095813/…
  • 没有SSLPeerUnspicifiedException。你的意思是SSLPeerUnverifiedException
  • 感谢您的回复,但我对 HttpsURLConnection 类也有同样的问题
  • SSLPeerUnverifiedException
  • 证书是服务器上的自签名证书吗?

标签: java android rest https


【解决方案1】:

这是用于 HTTPS 连接的自签名证书的示例代码

    BufferedReader in = null;
    HttpsURLConnection client=null;
    try {

        URL url = new URL(appendedUrl);
        client= (HttpsURLConnection) url.openConnection();
        client.setRequestMethod("GET");
        client.setRequestProperty("Auth-Token", token);
        client.setConnectTimeout(120000);
        client.setReadTimeout(120000);
        if(appendedUrl.contains("https")) {
            client.setSSLSocketFactory(certificatePinning(context).getSocketFactory());//for certificate pinning
            client.setHostnameVerifier(new HostnameVerifier() {
                @Override
                public boolean verify(String hostname, SSLSession session) {
                    if (hostname.equals("YOUR-HOST-ADDRESS"))
                        return true;
                    else
                        return false;
                }
            });
        }
        try{
            in = new BufferedReader(new InputStreamReader(client.getInputStream()));
        }catch(Exception ex)
        {
            ex.printStackTrace();
        }
        StringBuffer sb = new StringBuffer("");
        String line = "";
        String NL = System.getProperty("line.separator");
        while ((line = in.readLine()) != null) {
            sb.append(line + NL);
        }
        in.close();

        String result = sb.toString();
        return new JSONObject(result);
    }
    finally {
        if (in != null) {
            try {
                in.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

【讨论】:

猜你喜欢
  • 2020-05-29
  • 1970-01-01
  • 1970-01-01
  • 2017-09-12
  • 1970-01-01
  • 2013-06-01
  • 2016-04-24
  • 2014-07-18
  • 2018-08-26
相关资源
最近更新 更多