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/,如需轉載,請註明出處,否則將追究法律責任。
相關文章
- Gradle系列之構建指令碼基礎Gradle指令碼
- webgl值得重視的基礎構建Web
- Gradle For Android(2)--基礎的定製構建GradleAndroid
- Abp vNext 基礎篇丨領域構建
- HTTPS基礎原理和配置 - 1HTTP
- HTTPS基礎原理和配置-2HTTP
- HTTPS基礎原理和配置-3HTTP
- 基礎程式碼重構的若干建議(一)
- ASP.NET Core MVC專案基礎構建ASP.NETMVC
- 華夏航空全面採用AWS構建雲基礎架構架構
- 從智慧城市建設,看如何構建智慧安全基礎設施?
- 鵝廠如何構建大型基礎網路平臺
- 不得不學之「 Gradle」 ③ 構建指令碼基礎Gradle指令碼
- AI基礎軟體:如何自主構建大+小模型?AI模型
- IDEA + maven 零基礎構建 java agent 專案IdeaMavenJava
- 用Flutter構建漂亮的UI介面 - 基礎元件篇FlutterUI元件
- 微軟微服務構建框架Dapr基礎入門教程微軟微服務框架
- python網路爬蟲(9)構建基礎爬蟲思路Python爬蟲
- nlp基礎之-詞彙表構建的具體做法
- Netty系列文章之構建HTTP(HTTPS)應用程式NettyHTTP
- 從搞笑到高效,構建敏捷團隊的基礎原則敏捷
- Android 基礎知識課程助您輕鬆構建應用Android
- 愛分析調研 | 如何用超融合構建新一代IT基礎架構架構
- OrangeBusinessServices助力汽車製造商寶沃構建數字化基礎架構架構
- AWS副總裁Peter:解密基礎架構底層運維和構建之道解密架構運維
- Elasticsearch基礎結構Elasticsearch
- MySQL基礎架構MySql架構
- MySQL 基礎架構MySql架構
- websocketd | 基於 docker 構建WebDocker
- Java基礎14:離開IDE,使用java和javac構建專案JavaIDE
- 如何理解VMware內建於IT基礎架構的原生安全能力?架構
- Azure DevOps(二)利用Azure DevOps Pipeline 構建基礎設施資源dev
- 《大前端 基礎元件》系列 CSS基礎架構前端元件CSS架構
- 新華三:重構網路價值 構建數字經濟基礎設施
- moell/mojito - 基於 Laravel、Vue、ELement 構建的基礎後臺系統擴充套件LaravelVue套件
- K朋友問“基礎設施構建與系統整合的關係“
- 如何構建簡單、智慧又可靠的分支工廠 IT 基礎設施?
- Redis基礎——剖析基礎資料結構及其用法Redis資料結構