Android okvolley framework, androidokvolley
I have recently made many new good things and have no time to take a good look. Now I have to review them and take notes.
I remember that the framework I used previously was android-async-http, volley, or something else. Then I went on to get okhttp, retrofit, and rxjava, and there were a lot of new things, I am not a programmer. I am just a porter on github. If so many people come to learn and post articles, I will learn it myself, because volley was used in the past, so I didn't use retrofit, because volley also supports okhttp. As for why okhttp is used, I won't say much about it. After all, it's not a great guy, it's just a little white, and the code is the best teacher, the next step is to use the framework body of okhttp and volley.
Interface request class
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 supports https and network request classes: 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. * verify the specified self-signed certificate. */Public class SelfSignSslOkHttpStack extends HurlStack {private OkHttpClient okHttpClient;/*** Create a OkHttpStack with default OkHttpClient. * Create a default okhttpclient okhttpstack. */Public SelfSignSslOkHttpStack () {this (new OkHttpClient ());} /*** Create a OkHttpStack with a custom OkHttpClient Create a Custom okhttpclient okhttpstack * @ param okHttpClient custom OkHttpClient, NonNull */public publish (OkHttpClient okHttpClient) {this. okHttpClient = okHttpClient;} @ Override protected HttpURLConnection createConnection (URL url) throws IOException {if ("http ". equals (url. getProtocol () {// if the request is an https request, all SSL is trusted. This is modified. Whether or not https is used, HttpURLConnection connection = new OkUrlFactory (okHttpClient) is trusted ). open (url); // SSLSocketFactory ssl = HTTPSTrustManager. allowAllSSL (); // connection. setSSLSocketFactory (ssl); return connection;} else {return new OkUrlFactory (okHttpClient ). open (url );}}}View Code
Request Management
Public class RequestManager {private static final String TAG = "RequestManager"; private static int SOCKET_TIMEOUT = 6x10*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 mRequest Queue; // private OkHttpClient okHttpClient; private BitmapLruCache mLruCache; private ImageLoader mImageLoader; private DiskBasedCache mDiskCache; private RequestManager (Context context) {int timeout = 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 I NputStream = 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 ();}/** to use Volley, you must first obtain a RequestQueue object **/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); // replace HttpURLConnection with OKHttp as the transport layer 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 request **/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 basereturn application. 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 request
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
Learning notes, for reference only, can also be optimized here, such as removing the network callback and switching to rxandroid