最近新出了很多好东西都没时间去好好看看,现在得好好复习下了,记下笔记
记得以前用的框架是android-async-http,volley啊,或者其它的,然后后面接着又出了okhttp,retrofit,rxjava很多新东西,有句话说的好啊,我不是程序员,我只是github上面的搬运工,出了这么多东西肯定会有很多人学习然后发表文章的,自己就去学习了下,因为以前用的是volley,所以就没去用retrofit了,因为volley也支持okhttp了,至于为什么要用okhttp就不多说了,毕竟不是大牛,只供小白学习,代码就是最好的老师啊,接下来就是用的okhttp和volley结合使用的框架体了。
接口请求类
public class OkVolleyService { public interface ClientCallback {
void onSuccess(Object data); void onFailure(Exception e); void onError(Exception e);
} public static void Login(String userID, String password, Context context,
final ClientCallback callback) { String token = AuthFactory.encryptPassword(userID);
Map<String, String> params = new HashMap<>();
params.put("token", token);
params.put("userName", userID);
params.put("userPassword", password);
RequestManager.PostString("/doctor/login.do", context, params,
new Response.Listener<String>() {
@Override
public void onResponse(String response) {
UsersEntity entity = null;
try {
entity = UsersEntity.parse(response);
} catch (Exception e) {
e.printStackTrace();
callback.onError(e);
}
callback.onSuccess(entity);
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
callback.onFailure(error);
}
}); }; }
支持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());
} }
/**
* 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);
}
} }
请求管理类
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;
} }
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();
}
});
}
学习笔记,只供参考,此处还可以优化,比如把网络回调去掉,改用rxandroid