日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問(wèn) 生活随笔!

生活随笔

當(dāng)前位置: 首頁(yè) > 编程资源 > 编程问答 >内容正文

编程问答

android 访问https服务器

發(fā)布時(shí)間:2024/4/15 编程问答 29 豆豆
生活随笔 收集整理的這篇文章主要介紹了 android 访问https服务器 小編覺(jué)得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.

??? 之前,我講了如何讓tomcat支持https訪問(wèn),當(dāng)時(shí)瀏覽器通過(guò)https:localhost:8443即可訪問(wèn)tomcat。可是android此時(shí)如何訪問(wèn)已經(jīng)搭建好的tomcat的https了?我在網(wǎng)上找了很多資料,發(fā)現(xiàn)還是有問(wèn)題,后來(lái)自己改了一些,終于是做出來(lái)了。

1.搭建tomcat的https服務(wù)器。

這個(gè),我之前的博客已經(jīng)講過(guò),所有不在細(xì)講了。


2.將搭建tomcat服務(wù)器時(shí)生成的server.cer證書(shū)放在android的assets目錄下,應(yīng)為客戶(hù)端用https訪問(wèn)時(shí)需要檢測(cè)服務(wù)器的證書(shū)是否符合要求。


3.編寫(xiě)一個(gè)類(lèi)繼承X509TrustManager,X509TrustManager是證書(shū)信任管理器類(lèi),我們可以自己實(shí)現(xiàn)該接口,讓它信任我們指定的證書(shū)。

自己實(shí)現(xiàn)了信任管理器類(lèi),如何使用呢?類(lèi)HttpsURLConnection似乎并沒(méi)有提供方法設(shè)置信任管理器。其實(shí),HttpsURLConnection通過(guò)SSLSocket來(lái)建立與HTTPS的安全連接,SSLSocket對(duì)象是由SSLSocketFactory生成的。HttpsURLConnection提供了方法setSSLSocketFactory(SSLSocketFactory)設(shè)置它使用的SSLSocketFactory對(duì)象。SSLSocketFactory通過(guò)SSLContext對(duì)象來(lái)獲得,在初始化SSLContext對(duì)象時(shí),可指定信任管理器對(duì)象。

public class TrustAllCertsManager implements X509TrustManager {@Override public void checkClientTrusted(X509Certificate[] chain, String authType)throws CertificateException {// Do nothing -> accept any certificates }@Override public void checkServerTrusted(X509Certificate[] chain, String authType)throws CertificateException {// Do nothing -> accept any certificates }@Override public X509Certificate[] getAcceptedIssuers() {return new X509Certificate[0]; } }


4.編寫(xiě)一個(gè)類(lèi)實(shí)現(xiàn)HostnameVerifier接口,此類(lèi)是用于主機(jī)名驗(yàn)證的基接口。

在握手期間,如果 URL 的主機(jī)名和服務(wù)器的標(biāo)識(shí)主機(jī)名不匹配,則驗(yàn)證機(jī)制可以回調(diào)此接口的實(shí)現(xiàn)程序來(lái)確定是否應(yīng)該允許此連接。

策略可以是基于證書(shū)的或依賴(lài)于其他驗(yàn)證方案。

當(dāng)驗(yàn)證 URL 主機(jī)名使用的默認(rèn)規(guī)則失敗時(shí)使用這些回調(diào)。

public class VerifyEverythingHostnameVerifier implements HostnameVerifier {@Override public boolean verify(String hostname, SSLSession session) {return true; } }

此時(shí),我設(shè)置對(duì)所有主機(jī)都可以訪問(wèn)。

5.實(shí)例化服務(wù)器的證書(shū)。

private TrustManager[] createTrustManager() {BufferedInputStream cerInputStream = null; try {// 獲取客戶(hù)端存放的服務(wù)器公鑰證書(shū) cerInputStream = new BufferedInputStream(getAssets().open("server.cer")); // 根據(jù)公鑰證書(shū)生成Certificate對(duì)象 CertificateFactory cf = CertificateFactory.getInstance("X.509"); Certificate ca = cf.generateCertificate(cerInputStream); Log.e("TAG", "ca=" + ((X509Certificate) ca).getSubjectDN()); // 生成包含當(dāng)前CA證書(shū)的keystore KeyStore keyStore = KeyStore.getInstance(KeyStore.getDefaultType()); keyStore.load(null, null); keyStore.setCertificateEntry("ca", ca); // 使用包含指定CA證書(shū)的keystore生成TrustManager[]數(shù)組 String tmfAlgorithm = TrustManagerFactory.getDefaultAlgorithm(); TrustManagerFactory tmf = TrustManagerFactory.getInstance(tmfAlgorithm); tmf.init(keyStore); return tmf.getTrustManagers(); } catch (CertificateException e) {e.printStackTrace(); } catch (IOException e) {e.printStackTrace(); } catch (KeyStoreException e) {e.printStackTrace(); } catch (NoSuchAlgorithmException e) {e.printStackTrace(); } finally {if (cerInputStream != null) {try {cerInputStream.close(); } catch (IOException e) {e.printStackTrace(); }}}return null; }


上面的代碼比較固定,其中server.cer是配置tomcat時(shí)的服務(wù)器證書(shū)。具體我也不是很清楚,可以去百度找一下。


6.具體實(shí)現(xiàn)https請(qǐng)求。

private void httpsRequest(){String name="健康科技"; String pass="123456"; TrustManager[] trustManager = createTrustManager(); // TrustManager[] trustManager = new TrustManager[]{new TrustAllCertsManager()}; SSLContext sslContext = null; if (trustManager == null) {Log.e("TAG", "tmf create failed!"); return; }try {sslContext = SSLContext.getInstance("SSL"); sslContext.init(null, trustManager, new java.security.SecureRandom()); } catch (NoSuchAlgorithmException e) {// do nothing }catch (KeyManagementException e) {// do nothing }HttpsURLConnection.setDefaultSSLSocketFactory(sslContext.getSocketFactory()); HttpsURLConnection httpsURLConnection = null; BufferedReader reader = null; URL url = null; try {url = new URL("https://192.168.1.190:8443/MyWeb/HttpServlet"); httpsURLConnection = (HttpsURLConnection) url.openConnection(); httpsURLConnection.setHostnameVerifier(new VerifyEverythingHostnameVerifier()); httpsURLConnection.setConnectTimeout(5000); httpsURLConnection.setDoInput(true); httpsURLConnection.setUseCaches(false); //將用戶(hù)名和密碼放入HashMap Map<String,String> params=new HashMap<String,String>(); params.put("userName", name); params.put("passWord", pass); StringBuffer stringBuffer = new StringBuffer(); //存儲(chǔ)封裝好的請(qǐng)求體信息 try {for(Map.Entry<String, String> entry : params.entrySet()) {stringBuffer.append(entry.getKey()).append("=").append(URLEncoder.encode(entry.getValue(), "UTF-8")).append("&"); }stringBuffer.deleteCharAt(stringBuffer.length() - 1); //刪除最后的一個(gè)"&" } catch (Exception e) {e.printStackTrace(); }byte[] data=stringBuffer.toString().getBytes(); httpsURLConnection.setRequestMethod("POST"); //設(shè)置請(qǐng)求為POST httpsURLConnection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); httpsURLConnection.setRequestProperty("Content-Length", String.valueOf(data.length)); httpsURLConnection.connect(); OutputStream outputStream = httpsURLConnection.getOutputStream(); outputStream.write(data); reader = new BufferedReader(new InputStreamReader(httpsURLConnection.getInputStream())); StringBuilder sBuilder = new StringBuilder(); String line; while ((line = reader.readLine()) != null) {sBuilder.append(line); }Log.e("TAG", "Wiki content=" + sBuilder.toString()); final String s=sBuilder.toString(); runOnUiThread(new Runnable() {@Override public void run() {mTextView.setText(s.toString()); }}); } catch (MalformedURLException e) {e.printStackTrace(); } catch (IOException e) {e.printStackTrace(); }}


到這來(lái),客戶(hù)端就可以做https請(qǐng)求了,不過(guò)服務(wù)器的tomcat需要自己寫(xiě)一個(gè)簡(jiǎn)單的HttpServlet,這個(gè)很簡(jiǎn)單,自己完全可以百度。


總結(jié)

以上是生活随笔為你收集整理的android 访问https服务器的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。

如果覺(jué)得生活随笔網(wǎng)站內(nèi)容還不錯(cuò),歡迎將生活随笔推薦給好友。