https構建(基礎)
先寫最基礎的,你才能學框架聯網等,
public class HttpUtils { public interface HttpListener { void onSuccess(String content); void onFail(Exception ex); } private static Handler mUIHandler = new Handler(Looper.getMainLooper()); public static void doGet(final Context context, final String urlStr, final HttpListener listener) { new Thread() { @Override public void run() { InputStream is = null; try { URL url = new URL(urlStr); HttpsURLConnection conn = (HttpsURLConnection) url.openConnection(); SSLContext sslContext = SSLContext.getInstance("TLS");//協議 X509Certificate serverCert = getCert(context); TrustManager[] trustManagers = {new MyX509TrustManager(serverCert)}; sslContext.init(null, trustManagers, new SecureRandom());//三種,第二個是陣列我們要信任那些證照 conn.setSSLSocketFactory(sslContext.getSocketFactory()); //對域名的效驗 conn.setHostnameVerifier(new HostnameVerifier() { @Override public boolean verify(String hostname, SSLSession session) { HostnameVerifier defaultHostnameVerifier = HttpsURLConnection.getDefaultHostnameVerifier(); return defaultHostnameVerifier.verify("kyfw.12306.cn", session); } }); //以上是htpps需要的 conn.setDoInput(true); conn.setDoOutput(true); conn.setRequestMethod("GET"); conn.setReadTimeout(5000); conn.setConnectTimeout(5000); conn.connect(); is = conn.getInputStream(); InputStreamReader isr = new InputStreamReader(is);//char對應是Reader如果用byte用Stream就行 char[] buf = new char[2048]; int len = -1; final StringBuilder content = new StringBuilder(); while ((len = isr.read(buf)) != -1) { content.append(new String(buf, 0, len)); } mUIHandler.post(new Runnable() { @Override public void run() { listener.onSuccess(content.toString()); } }); } catch (Exception e) { e.printStackTrace(); listener.onFail(e); } finally { try { if (is != null) { is.close(); } } catch (IOException e) { // ignore } } } }.start(); } /** * 獲取證照判斷證照 * @param context * @return */ private static X509Certificate getCert(Context context) { try { InputStream is = context.getAssets().open("srca.cer"); CertificateFactory certificateFactory = CertificateFactory.getInstance("X.509");//建立證照 return (X509Certificate) certificateFactory.generateCertificate(is); } catch (IOException e) { e.printStackTrace(); } catch (CertificateException e) { e.printStackTrace(); } return null; } }
/** * 檢查證照 */ public class MyX509TrustManager implements X509TrustManager { private X509Certificate mServerCert;//證照 public MyX509TrustManager(X509Certificate certificate) { mServerCert = certificate; } @Override public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException { } @Override public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException { //判斷證照合法性 for (X509Certificate certificate : chain) { // 證照是否過期以及合法性的校驗 certificate.checkValidity(); try { certificate.verify(mServerCert.getPublicKey());//傳入公鑰 } catch (Exception e) { throw new CertificateException(e); } } } @Override public X509Certificate[] getAcceptedIssuers() { return new X509Certificate[0]; } }
有這個你就可以了,下面第二方法
public class HttpUtils2 { public interface HttpListener { void onSuccess(String content); void onFail(Exception ex); } private static Handler mUIHandler = new Handler(Looper.getMainLooper()); public static void doGet(final Context context, final String urlStr, final HttpListener listener) { new Thread() { @Override public void run() { InputStream is = null; try { URL url = new URL(urlStr); HttpsURLConnection conn = (HttpsURLConnection) url.openConnection(); X509Certificate serverCert = getCert(context); // String keyStoreType = KeyStore.getDefaultType(); KeyStore keyStore = KeyStore.getInstance(keyStoreType); keyStore.load(null); keyStore.setCertificateEntry("srca",serverCert); TrustManagerFactory trustManagerFactory = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm()); trustManagerFactory.init(keyStore); // SSLContext sslContext = SSLContext.getInstance("TLS"); TrustManager[] trustManagers = trustManagerFactory.getTrustManagers(); sslContext.init(null, trustManagers, new SecureRandom()); conn.setSSLSocketFactory(sslContext.getSocketFactory()); conn.setHostnameVerifier(new HostnameVerifier() { @Override public boolean verify(String hostname, SSLSession session) { HostnameVerifier defaultHostnameVerifier = HttpsURLConnection.getDefaultHostnameVerifier(); return defaultHostnameVerifier.verify("kyfw.12306.cn", session); } }); conn.setDoInput(true); conn.setDoOutput(true); conn.setRequestMethod("GET"); conn.setReadTimeout(5000); conn.setConnectTimeout(5000); conn.connect(); is = conn.getInputStream(); InputStreamReader isr = new InputStreamReader(is); char[] buf = new char[2048]; int len = -1; final StringBuilder content = new StringBuilder(); while ((len = isr.read(buf)) != -1) { content.append(new String(buf, 0, len)); } mUIHandler.post(new Runnable() { @Override public void run() { listener.onSuccess(content.toString()); } }); } catch (Exception e) { e.printStackTrace(); listener.onFail(e); } finally { try { if (is != null) { is.close(); } } catch (IOException e) { // ignore } } } }.start(); } private static X509Certificate getCert(Context context) { try { InputStream is = context.getAssets().open("srca.cer"); CertificateFactory certificateFactory = CertificateFactory.getInstance("X.509"); return (X509Certificate) certificateFactory.generateCertificate(is); } catch (IOException e) { e.printStackTrace(); } catch (CertificateException e) { e.printStackTrace(); } return null; } }
這就是最基礎的東西了
來自 “ ITPUB部落格 ” ,連結:http://blog.itpub.net/1747/viewspace-2813061/,如需轉載,請註明出處,否則將追究法律責任。
相關文章
- webgl值得重視的基礎構建Web
- Vue2.0構建——基礎總結Vue
- Gradle系列之構建指令碼基礎Gradle指令碼
- C++基礎建構函式(constructor)C++函式Struct
- 華夏航空全面採用AWS構建雲基礎架構架構
- 智慧城市基礎設施建設的PPP模式如何構建模式
- 基礎程式碼重構的若干建議(一)
- 鵝廠如何構建大型基礎網路平臺
- Oracle基礎結構之手工建庫相關Oracle
- Spring Cloud構建分散式微服務雲架構基礎SpringCloud分散式微服務架構
- HTTPS基礎原理和配置-3HTTP
- HTTPS基礎原理和配置 - 1HTTP
- HTTPS基礎原理和配置-2HTTP
- 構建基於LDAP的地址薄之一 基礎篇(轉)LDA
- 從智慧城市建設,看如何構建智慧安全基礎設施?
- 用Flutter構建漂亮的UI介面 - 基礎元件篇FlutterUI元件
- Abp vNext 基礎篇丨領域構建
- Gradle For Android(2)--基礎的定製構建GradleAndroid
- 微軟微服務構建框架Dapr基礎入門教程微軟微服務框架
- AI基礎軟體:如何自主構建大+小模型?AI模型
- wepback基礎配置(構建一個vue-cli)--2Vue
- wepback基礎配置(構建一個vue-cli)--1Vue
- 如何構建一個分散式爬蟲:基礎篇分散式爬蟲
- nlp基礎之-詞彙表構建的具體做法
- Spring Cloud構建微服務架構—服務消費基礎SpringCloud微服務架構
- IDEA + maven 零基礎構建 java agent 專案IdeaMavenJava
- 不得不學之「 Gradle」 ③ 構建指令碼基礎Gradle指令碼
- OrangeBusinessServices助力汽車製造商寶沃構建數字化基礎架構架構
- 從搞笑到高效,構建敏捷團隊的基礎原則敏捷
- python網路爬蟲(9)構建基礎爬蟲思路Python爬蟲
- Python基礎原理:FP-growth演算法的構建Python演算法
- 構建一個高可用 WebSphere Business Events 事件基礎設施Web事件
- 愛分析調研 | 如何用超融合構建新一代IT基礎架構架構
- AWS副總裁Peter:解密基礎架構底層運維和構建之道解密架構運維
- Elasticsearch基礎結構Elasticsearch
- MySQL基礎架構MySql架構
- Oracle基礎構架Oracle
- MySQL 基礎架構MySql架構