2017-04-21 54 views
0

在Android中,我的工作與REST的API使用HTTPS協議SSLPeerUnverifiedException使用HTTPS工作在Android的

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一段時間。

+0

我想'HttpClient'已棄用,但我建議你使用'HttpURLConnection'爲'http'連接和'HttpsURLConnection' 'https'連接 更多信息http://stackoverflow.com/questions/22095813/androidhttpclient-versus-httpurlconnection-for-api-level-9-and-above#answer-22096707 – Deb

+0

沒有'SSLPeerUnspicifiedException'。你的意思是'SSLPeerUnverifiedException'嗎? – Robert

+0

感謝您的回覆,但我也有同樣的問題與HttpsURLConnection類也 –

回答

0

下面是用於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(); 
      } 
     } 
    } 
+0

此外,你可以檢查這個問題以及http://stackoverflow.com/questions/9092857/sslpeerunverifiedexception-while-creating-an-ssl-connection-on-android?rq=1 – Deb

相關問題