Okhttp網路請求最佳實踐(一)
阿新 • • 發佈:2018-12-16
首先是實現網路的配置:
- 先獲取網路許可權;
- 再宣告兩個變數,有關網路操作許可權的;
- 宣告一個url地址。
public class constants { private static final int WRITE_READ_EXTERNASL_CODE=999; private static final String[] WRITE_READ_EXTERNAL_PERMISSION ={Manifest.permission.READ_EXTERNAL_STORAGE,Manifest.permission.WRITE_EXTERNAL_STORAGE}; } public class Urlconstants { public static final String USER_LOGIN="http://www.kuaidi100.com/query";//快遞查詢URL }
其次是modle層,這裡就只用一個空的user層。
public class user {
}
然後進入到Okhttp的框架:
- 首先是新建一個異常類OkhttpExcetion,伺服器返回錯誤的訊息以及錯誤編號。
public class OkhttpsException extends Exception{ private static final long sertalVersion=1L; /** * 返回伺服器的資料 */ private int ecode; /** * 伺服器返回錯誤訊息 */ private Object emsg; public OkhttpsException(int ecode,Object emsg) { this.ecode=ecode; this.emsg=emsg; } public int getEcode()//返回伺服器返回的資訊 { return ecode; } public Object getEmsg() { return emsg; } }
import java.io.IOException; import java.io.InputStream; import java.security.KeyManagementException; import java.security.KeyStore; import java.security.KeyStoreException; import java.security.NoSuchAlgorithmException; import java.security.UnrecoverableKeyException; import java.security.cert.CertificateException; import java.security.cert.CertificateFactory; import java.security.cert.X509Certificate; import javax.net.ssl.HostnameVerifier; import javax.net.ssl.KeyManager; import javax.net.ssl.KeyManagerFactory; import javax.net.ssl.SSLContext; import javax.net.ssl.SSLSession; import javax.net.ssl.SSLSocketFactory; import javax.net.ssl.TrustManager; import javax.net.ssl.TrustManagerFactory; import javax.net.ssl.X509TrustManager; /** * 網路請求 */ public class HttpsUtils { /** *SSL安全協議 */ public static class SSLParams { public SSLSocketFactory sslSocketFactory; public X509TrustManager trustManager; } /** * 獲取證書 * @param certificate,證書 * @param bksFile,bks檔案格式的檔案 * @param password * @return */ public static SSLParams getSslSocketFactory(InputStream[] certificate,InputStream bksFile,String password) { SSLParams sslParams =new SSLParams(); try { TrustManager[] trustManagers = prepareTrustManager(certificate); KeyManager[] keyManagers = prepareKeyManager(bksFile,password); SSLContext sslContext=SSLContext.getInstance("SSL"); X509TrustManager trustManager=null; if(trustManagers!=null) { trustManager = new MyTrustManager(chooseTrustManager(trustManagers)); }else { trustManager=new UnsafeTrustManager(); } /** 初始化sslContext, */ sslContext.init(keyManagers,new TrustManager[]{trustManager},null); sslParams.sslSocketFactory=sslContext.getSocketFactory(); sslParams.trustManager=trustManager; return sslParams; }catch(NoSuchAlgorithmException e) { throw new AssertionError(e); }catch(KeyManagementException e) { throw new AssertionError(e); }catch(KeyStoreException e) { throw new AssertionError(e); } } /** * 準備階段 * @param bksFile * @param password * @return */ private static KeyManager[] prepareKeyManager(InputStream bksFile, String password) { try { if(bksFile==null||password==null)return null;//輸入流為空或者密碼為空 KeyStore clientKeyStore=KeyStore.getInstance("BKS");//為keyStore提供一個bks檔案格式的檔案 /** The system will return the most preferred implementation of the specified keystore type available in the environment. Before a keystore can be accessed, it must be loaded. */ clientKeyStore.load(bksFile,password.toCharArray()); KeyManagerFactory keyManagerFactory=KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm()); keyManagerFactory.init(clientKeyStore,password.toCharArray()); return keyManagerFactory.getKeyManagers(); } catch (CertificateException e) { e.printStackTrace(); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); }catch (Exception e) { e.printStackTrace(); } return null; } /** * 訪問自簽名的網站 * @param certificates 一個證書是一個實體的數字簽名,還包含這個實體的公共鑰匙值. * @return * InputStream就對應於我們證書的輸入流。 * 程式碼內部,我們: 構造CertificateFactory物件,通過它的generateCertificate(is)方法得到Certificate。 然後講得到的Certificate放入到keyStore中。 接下來利用keyStore去初始化我們的TrustManagerFactory 由trustManagerFactory.getTrustManagers獲得TrustManager[]初始化我們的SSLContext 最後,設定我們mOkHttpClient.setSslSocketFactory即可。 本文來自 鴻洋_ 的CSDN 部落格 ,全文地址請點選:https://blog.csdn.net/lmj623565791/article/details/48129405?utm_source=copy*/ /** * 信任管理器 * @param certificates * @return */ private static TrustManager[] prepareTrustManager(InputStream... certificates) { if(certificates==null||certificates.length<=0) return null; try { CertificateFactory certificateFactory=CertificateFactory.getInstance("X.509"); /** * Typical ways to request a KeyStore object include relying on the default type and providing a specific keystore type. *The system will return a keystore implementation for the default type. */ KeyStore keyStore=KeyStore.getInstance(KeyStore.getDefaultType()); keyStore.load(null); int index=0; for(InputStream certificate :certificates) { String certificateAlias=Integer.toString(index++); /** * alias - the alias name * cert - the certificate *Assigns the given trusted certificate to the given alias. */ keyStore.setCertificateEntry(certificateAlias,certificateFactory.generateCertificate(certificate)); try { if(certificate!=null) { certificate.close(); } }catch ( Exception e) { } } TrustManagerFactory trustManagerFactory=TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm()); trustManagerFactory.init(keyStore);// 接下來利用keyStore去初始化我們的TrustManagerFactory TrustManager[] trustManagers=trustManagerFactory.getTrustManagers();//由trustManagerFactory.getTrustManagers獲得TrustManager[] return trustManagers; } catch (CertificateException e) { e.printStackTrace(); } catch (KeyStoreException e) { e.printStackTrace(); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return null; } private static X509TrustManager chooseTrustManager(TrustManager[] trustManagers) { for(TrustManager trustManager : trustManagers) { if(trustManager instanceof X509TrustManager) { return (X509TrustManager) trustManager; } } return null; } private static class MyTrustManager implements X509TrustManager{ private X509TrustManager defaultTrustManager; private X509TrustManager localTrustManager; public MyTrustManager(X509TrustManager localTrustManager)throws NoSuchAlgorithmException,KeyStoreException { TrustManagerFactory var4 =TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm()); var4.init((KeyStore) null); defaultTrustManager =chooseTrustManager(var4.getTrustManagers()); this.localTrustManager=localTrustManager; } @Override public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException { } @Override public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException { try { defaultTrustManager.checkServerTrusted(chain,authType); }catch(CertificateException ce) { localTrustManager.checkServerTrusted(chain, authType); } } @Override//Return an array of certificate authority certificates which are trusted for authenticating peers. public X509Certificate[] getAcceptedIssuers() { return new X509Certificate[0]; } } private static class UnsafeHostnameManager implements HostnameVerifier { @Override public boolean verify(String hostname, SSLSession session) { return true; } } public static class UnsafeTrustManager implements X509TrustManager { @Override public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException { } @Override public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException { } @Override public X509Certificate[] getAcceptedIssuers() { return new java.security.cert.X509Certificate[]{}; } } }