最近新出了很多好东西都没时间去好好看看,现在得好好复习下了,记下笔记

记得以前用的框架是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                     @Override
22                     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                     @Override
34                     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

posted on 2016-02-29 09:54  翻滚的咸鱼  阅读(1174)  评论(0编辑  收藏  举报