溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務條款》

android httpClient 支持HTTPS的訪問方式是怎樣的

發布時間:2021-11-12 17:52:35 來源:億速云 閱讀:114 作者:柒染 欄目:移動開發

這篇文章將為大家詳細講解有關android httpClient 支持HTTPS的訪問方式是怎樣的,文章內容質量較高,因此小編分享給大家做個參考,希望大家閱讀完這篇文章后對相關知識有一定的了解。

項目中Android https請求地址遇到了這個異常(無終端認證):
javax.net.ssl.SSLPeerUnverifiedException: No peer certificate

是SSL協議中沒有終端認證。

沒有遇到過的問題,于是無奈的去找度娘。。。。。。。

看了不少大神的博客后得到的解決方案如下:

/**   * Post請求連接Https服務   * @param serverURL  請求地址   * @param jsonStr    請求報文   * @return   * @throws Exception   */  public static synchronized String doHttpsPost(String serverURL, String jsonStr)throws Exception {      // 參數      HttpParams httpParameters = new BasicHttpParams();      // 設置連接超時      HttpConnectionParams.setConnectionTimeout(httpParameters, 3000);      // 設置socket超時      HttpConnectionParams.setSoTimeout(httpParameters, 3000);      // 獲取HttpClient對象 (認證)      HttpClient hc = initHttpClient(httpParameters);      HttpPost post = new HttpPost(serverURL);      // 發送數據類型      post.addHeader("Content-Type", "application/json;charset=utf-8");      // 接受數據類型      post.addHeader("Accept", "application/json");      // 請求報文      StringEntity entity = new StringEntity(jsonStr, "UTF-8");      post.setEntity(entity);      post.setParams(httpParameters);      HttpResponse response = null;      try {          response = hc.execute(post);      } catch (UnknownHostException e) {          throw new Exception("Unable to access " + e.getLocalizedMessage());      } catch (SocketException e) {          e.printStackTrace();      }      int sCode = response.getStatusLine().getStatusCode();      if (sCode == HttpStatus.SC_OK) {          return EntityUtils.toString(response.getEntity());      } else          throw new Exception("StatusCode is " + sCode);  }   private static HttpClient client = null;  /**   * 初始化HttpClient對象   * @param params   * @return   */  public static synchronized HttpClient initHttpClient(HttpParams params) {      if(client == null){          try {              KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType());              trustStore.load(null, null);                             SSLSocketFactory sf = new SSLSocketFactoryImp(trustStore);              //允許所有主機的驗證              sf.setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);                             HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);              HttpProtocolParams.setContentCharset(params, HTTP.UTF_8);              // 設置http和https支持              SchemeRegistry registry = new SchemeRegistry();              registry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80));              registry.register(new Scheme("https", sf, 443));                             ClientConnectionManager ccm = new ThreadSafeClientConnManager(params, registry);                             return new DefaultHttpClient(ccm, params);          } catch (Exception e) {              e.printStackTrace();              return new DefaultHttpClient(params);          }      }      return client;  }  public static class SSLSocketFactoryImp extends SSLSocketFactory {      final SSLContext sslContext = SSLContext.getInstance("TLS");       public SSLSocketFactoryImp(KeyStore truststore)              throws NoSuchAlgorithmException, KeyManagementException,              KeyStoreException, UnrecoverableKeyException {          super(truststore);           TrustManager tm = new X509TrustManager() {              public java.security.cert.X509Certificate[] getAcceptedIssuers() {                  return null;              }               @Override              public void checkClientTrusted(                      java.security.cert.X509Certificate[] chain,                      String authType)                      throws java.security.cert.CertificateException {              }               @Override              public void checkServerTrusted(                      java.security.cert.X509Certificate[] chain,                      String authType)                      throws java.security.cert.CertificateException {              }          };          sslContext.init(null, new TrustManager[] { tm }, null);      }       @Override      public Socket createSocket(Socket socket, String host, int port,              boolean autoClose) throws IOException, UnknownHostException {          return sslContext.getSocketFactory().createSocket(socket, host,                  port, autoClose);      }       @Override      public Socket createSocket() throws IOException {          return sslContext.getSocketFactory().createSocket();      }  }

run下,小手發抖的點到測試按鈕,深吸口氣,咦?沒反應。。。馬蛋的,工作線程忘記start(),唉,再次run下,終于的有點反應了,神奇的竟然沒有報之前的  javax.net.ssl.SSLPeerUnverifiedException: No peer certificate 的異常了。服務端的數據正常返回了。

分析問題:
HTTPS:超文本安全傳輸協議,和HTTP相比,多了一個SSL/TSL的認證過程,端口為443。

1.peer終端發送一個request,https服務端把支持的加密算法等以證書的形式返回一個身份信息(包含ca頒發機構和加密公鑰等)。

2.獲取證書之后,驗證證書合法性。

3.隨機產生一個密鑰,并以證書當中的公鑰加密。

4.request https服務端,把用公鑰加密過的密鑰傳送給https服務端。

5.https服務端用自己的密鑰解密,獲取隨機值。

6.之后雙方傳送數據都用此密鑰加密后通信。

HTTPS流程清楚后,問題也就明顯了,驗證證書時,無法驗證。

上面提供的解決方案就是添加默認信任全部證書。以此來通過接下來的通信。

但是,這樣問題是解決了。但是覺得還是不帶靠譜(信任全部證書有點危險)。繼續噼噼啪啪的網上搜索一番。又找到了一種解決方案,其過程大致這樣的:

1.瀏覽器訪問https地址,保存提示的證書到本地,放到android項目中的assets目錄。

2.導入證書,代碼如下。

3.把證書添加為信任。

public static String requestHTTPSPage(Context context, String mUrl) {         InputStream ins = null;         String result = "";         try {             ins = context.getAssets().open("my.key"); // 下載的證書放到項目中的assets目錄中             CertificateFactory cerFactory = CertificateFactory.getInstance("X.509");             Certificate cer = cerFactory.generateCertificate(ins);             KeyStore keyStore = KeyStore.getInstance("PKCS12", "BC");             keyStore.load(null, null);             keyStore.setCertificateEntry("trust", cer);               SSLSocketFactory socketFactory = new SSLSocketFactory(keyStore);             Scheme sch = new Scheme("https", socketFactory, 443);             HttpClient mHttpClient = new DefaultHttpClient();             mHttpClient.getConnectionManager().getSchemeRegistry().register(sch);               BufferedReader reader = null;             try {                 HttpGet request = new HttpGet();                 request.setURI(new URI(mUrl));                 HttpResponse response = mHttpClient.execute(request);                 if (response.getStatusLine().getStatusCode() != 200) {                     request.abort();                     return result;                 }                   reader = new BufferedReader(new InputStreamReader(response                         .getEntity().getContent()));                 StringBuffer buffer = new StringBuffer();                 String line = null;                 while ((line = reader.readLine()) != null) {                     buffer.append(line);                 }                 result = buffer.toString();             } catch (Exception e) {                 e.printStackTrace();             } finally {                 if (reader != null) {                     reader.close();                 }             }         } catch (Exception e) {             e.printStackTrace();         } finally {             try {                 if (ins != null)                     ins.close();             } catch (IOException e) {                 e.printStackTrace();             }         }         return result;

關于android httpClient 支持HTTPS的訪問方式是怎樣的就分享到這里了,希望以上內容可以對大家有一定的幫助,可以學到更多知識。如果覺得文章不錯,可以把它分享出去讓更多的人看到。

向AI問一下細節

免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。

AI

亚洲午夜精品一区二区_中文无码日韩欧免_久久香蕉精品视频_欧美主播一区二区三区美女