android okvolley架構搭建,androidokvolley
最近新出了很多好東西都沒時間去好好看看,現在得好好複習下了,記下筆記
記得以前用的架構是android-async-http,volley啊,或者其它的,然後後面接著又出了okhttp,retrofit,rxjava很多新東西,有句話說的好啊,我不是程式員,我只是github上面的搬運工,出了這麼多東西肯定會有很多人學習然後發表文章的,自己就去學習了下,因為以前用的是volley,所以就沒去用retrofit了,因為volley也支援okhttp了,至於為什麼要用okhttp就不多說了,畢竟不是大牛,只供小白學習,代碼就是最好的老師啊,接下來就是用的okhttp和volley結合使用的架構體了。
介面請求類
1 public class OkVolleyService { 2 3 public interface ClientCallback { 4 void onSuccess(Object data); 5 6 void onFailure(Exception e); 7 8 void onError(Exception e); 9 }10 11 public static void Login(String userID, String password, Context context,12 final ClientCallback callback) {13 14 String token = AuthFactory.encryptPassword(userID);15 Map<String, String> params = new HashMap<>();16 params.put("token", token);17 params.put("userName", userID);18 params.put("userPassword", password);19 RequestManager.PostString("/doctor/login.do", context, params,20 new Response.Listener<String>() {21 @Override22 public void onResponse(String response) {23 UsersEntity entity = null;24 try {25 entity = UsersEntity.parse(response);26 } catch (Exception e) {27 e.printStackTrace();28 callback.onError(e);29 }30 callback.onSuccess(entity);31 }32 }, new Response.ErrorListener() {33 @Override34 public void onErrorResponse(VolleyError error) {35 callback.onFailure(error);36 }37 });38 39 };40 41 }View Code支援https和網路請求類public class HTTPSTrustManager implements X509TrustManager{ private static TrustManager[] trustManagers; private static final X509Certificate[] _AcceptedIssuers = new X509Certificate[] {}; @Override public void checkClientTrusted( java.security.cert.X509Certificate[] x509Certificates, String s) throws java.security.cert.CertificateException { // To change body of implemented methods use File | Settings | File // Templates. } @Override public void checkServerTrusted( java.security.cert.X509Certificate[] x509Certificates, String s) throws java.security.cert.CertificateException { // To change body of implemented methods use File | Settings | File // Templates. } public boolean isClientTrusted(X509Certificate[] chain) { return true; } public boolean isServerTrusted(X509Certificate[] chain) { return true; } @Override public X509Certificate[] getAcceptedIssuers() { return _AcceptedIssuers; } public static void allowAllSSL() { HttpsURLConnection.setDefaultHostnameVerifier(new HostnameVerifier() { @Override public boolean verify(String arg0, SSLSession arg1) { // TODO Auto-generated method stub return true; } }); SSLContext context = null; if (trustManagers == null) { trustManagers = new TrustManager[] { new HTTPSTrustManager() }; } try { context = SSLContext.getInstance("TLS"); context.init(null, trustManagers, new SecureRandom()); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } catch (KeyManagementException e) { e.printStackTrace(); } HttpsURLConnection.setDefaultSSLSocketFactory(context .getSocketFactory()); }}View Code/** * A HttpStack implement witch can verify specified self-signed certification. * 驗證指定的自我簽署憑證。 */public class SelfSignSslOkHttpStack extends HurlStack { private OkHttpClient okHttpClient; /** * Create a OkHttpStack with default OkHttpClient. * 建立一個預設的okhttpclient okhttpstack。 */ public SelfSignSslOkHttpStack() { this(new OkHttpClient()); } /** * Create a OkHttpStack with a custom OkHttpClient 建立一個自訂的okhttpclient okhttpstack * @param okHttpClient Custom OkHttpClient, NonNull */ public SelfSignSslOkHttpStack(OkHttpClient okHttpClient) { this.okHttpClient = okHttpClient; } @Override protected HttpURLConnection createConnection(URL url) throws IOException { if ("http".equals(url.getProtocol())) {//如果請求是https請求那麼就信任所有SSL,此處作了修改,無論是不是https都信任 HttpURLConnection connection = new OkUrlFactory(okHttpClient).open(url);// SSLSocketFactory ssl = HTTPSTrustManager.allowAllSSL();// connection.setSSLSocketFactory(ssl); return connection; } else { return new OkUrlFactory(okHttpClient).open(url); } }}View Code
要求管理類
public class RequestManager { private static final String TAG = "RequestManager"; private static int SOCKET_TIMEOUT = 6 * 10 * 100; private static RequestManager instance; private Map<String, SSLSocketFactory> socketFactoryMap; public static RequestManager getInstance(Context context) { if (instance == null) { instance = new RequestManager(context); } return instance; } public RequestQueue mRequestQueue;// private OkHttpClient okHttpClient; private BitmapLruCache mLruCache; private ImageLoader mImageLoader; private DiskBasedCache mDiskCache; private RequestManager(Context context) { int MEM_CACHE_SIZE = 1024 * 1024 * ((ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE)).getMemoryClass() / 3;// okHttpClient = new OkHttpClient(); mLruCache = new BitmapLruCache(MEM_CACHE_SIZE); mRequestQueue = newRequestQueue(context.getApplicationContext()); mImageLoader = new ImageLoader(mRequestQueue, mLruCache); mDiskCache = (DiskBasedCache) mRequestQueue.getCache(); } private SSLSocketFactory createSSLSocketFactory(Context context, int res, String password) throws CertificateException, NoSuchAlgorithmException, IOException, KeyStoreException, KeyManagementException { InputStream inputStream = context.getResources().openRawResource(res); KeyStore keyStore = KeyStore.getInstance("BKS"); keyStore.load(inputStream, password.toCharArray()); TrustManagerFactory tmf = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm()); tmf.init(keyStore); SSLContext sslContext = SSLContext.getInstance("TLS"); sslContext.init(null, tmf.getTrustManagers(), new SecureRandom()); return sslContext.getSocketFactory(); } /**使用Volley首先需要擷取到一個RequestQueue對象**/ private RequestQueue newRequestQueue(Context context) { RequestQueue requestQueue; try {// String[] hosts = {CommonConfig.BASE_API};// int[] certRes = {R.raw.kyfw};// String[] certPass = {"asdfqaz"};// socketFactoryMap = new Hashtable<>(hosts.length);// for (int i = 0; i < certRes.length; i++) {// int res = certRes[i];// String password = certPass[i];// SSLSocketFactory sslSocketFactory = createSSLSocketFactory(context, res, password);// socketFactoryMap.put(hosts[i], sslSocketFactory);// } //用OKHttp替換HttpURLConnection作為傳輸層 HurlStack stack = new SelfSignSslOkHttpStack(); requestQueue = Volley.newRequestQueue(context, stack); requestQueue.start(); } catch (Exception e) { throw new RuntimeException(e); } return requestQueue; } public void addRequest(Request request, Object tag) { if (BuildConfig.DEBUG) { Log.i(TAG, "Add request:" + request.toString()); } if (tag != null) { request.setTag(tag); } mRequestQueue.add(request); } public void cancelAll(Object tag) { mRequestQueue.cancelAll(tag); } public File getCachedImageFile(String url) { return mDiskCache.getFileForKey(url); } public Bitmap getMemoryBitmap(String key) { return mLruCache.get(key); } public ImageLoader.ImageContainer loadImage(String requestUrl, ImageLoader.ImageListener imageListener) { return loadImage(requestUrl, imageListener, 0, 0); } public ImageLoader.ImageContainer loadImage(String requestUrl, ImageLoader.ImageListener imageListener, int maxWidth, int maxHeight) { return mImageLoader.get(requestUrl, imageListener, maxWidth, maxHeight); } /**post請求**/ public static void PostString(String url, Context context, final Map<String, String> pams, Response.Listener<String> listener, Response.ErrorListener errListener) { url = getAbsoluteUrl(url); HTTPSTrustManager.allowAllSSL(); StringRequest request = new StringRequest( Request.Method.POST, url, listener, errListener ) { @Override public Map<String, String> getHeaders() throws AuthFailureError { // TODO Auto-generated method stub return BaseApplication.getApplication() .getHeaderparams(); } @Override public RetryPolicy getRetryPolicy() { // TODO Auto-generated method stub RetryPolicy retryPolicy = new DefaultRetryPolicy( SOCKET_TIMEOUT, DefaultRetryPolicy.DEFAULT_MAX_RETRIES, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT); return retryPolicy; } @Override protected Map<String, String> getParams() throws AuthFailureError { return pams; } }; // mRequestQueue.cancelAll(); // volley.jar RequestManager.getInstance(context).addRequest(request, context); } private static String getAbsoluteUrl(String relativeUrl) { return CommonConfig.BASE_API + relativeUrl; }}View Code
ui請求
private void login(){ OkVolleyService.Login("xxxxxxxx", "123", context, new OkVolleyService.ClientCallback() { @Override public void onSuccess(Object data) { UsersEntity rEntity = (UsersEntity) data; if (rEntity.reqResult.equals("success")) { final UserEntity entity = rEntity.getData(); if (entity != null) startActivity(new Intent(context, MainActivity.class)); } } @Override public void onFailure(Exception e) { Toast.makeText(context, e.getMessage(), Toast.LENGTH_SHORT).show(); } @Override public void onError(Exception e) { Toast.makeText(context, e.getMessage(), Toast.LENGTH_SHORT).show(); } }); }View Code
學習筆記,只供參考,此處還可以最佳化,比如把網路回調去掉,改用rxandroid