Volley 百财帮封装
Activity
public class MainActivity extends Activity implements OnClickListener {private Context ctx;private TextView tv;@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);ctx = this;setContentView(R.layout.activity_main);findViewById(R.id.button1).setOnClickListener(this);findViewById(R.id.button2).setOnClickListener(this);findViewById(R.id.button3).setOnClickListener(this);findViewById(R.id.button4).setOnClickListener(this);tv = (TextView) findViewById(R.id.tv);}@Overridepublic void onClick(View v) {tv.setText("");switch (v.getId()) {case R.id.button1:requestLogin();break;case R.id.button2:requestUserDetailInfo();break;case R.id.button3:requestUserWallet();break;case R.id.button4:requestUserBankCard();break;default:break;}}/*** 登录*/private void requestLogin() {JSONObject obj = new JSONObject();try {obj.put("Mobile", "13412341234");obj.put("Password", "12341234");} catch (JSONException e) {e.printStackTrace();}BcbJsonRequest jsonRequest = new BcbJsonRequest(Urls.UserDoLogin, obj, null, new BcbRequest.BcbCallBack<JSONObject>() {@Overridepublic void onResponse(JSONObject response) {Log.i("bqt", "登录后返回的数据:" + response.toString());if (HttpCallBackUtils.getRequestStatus(response, ctx)) {JSONObject data = HttpCallBackUtils.getResultObject(response);if (data != null) {App.instance.setAccessToken(data.optString("Access_Token"));tv.setText(JsonFormatTool.formatJson(data.toString()));}}}@Overridepublic void onErrorResponse(Exception error) {}});App.instance.getRequestQueue().add(jsonRequest);}/*** 用户信息*/private void requestUserDetailInfo() {BcbJsonRequest jsonRequest = new BcbJsonRequest(Urls.UserMessage, null, App.instance.getAccessToken(), new BcbRequest.BcbCallBack<JSONObject>() {@Overridepublic void onResponse(JSONObject response) {Log.i("bqt", "用户信息:" + response.toString());if (HttpCallBackUtils.getRequestStatus(response, ctx)) {JSONObject data = HttpCallBackUtils.getResultObject(response);if (data != null) {tv.setText(JsonFormatTool.formatJson(data.toString()));}}}@Overridepublic void onErrorResponse(Exception error) {}});App.instance.getRequestQueue().add(jsonRequest);}/*** 用户钱包*/private void requestUserWallet() {BcbJsonRequest jsonRequest = new BcbJsonRequest(Urls.UserWallet, null, App.instance.getAccessToken(), new BcbRequest.BcbCallBack<JSONObject>() {@Overridepublic void onResponse(JSONObject response) {Log.i("bqt", "用户钱包:" + response.toString());if (HttpCallBackUtils.getRequestStatus(response, ctx)) {JSONObject data = HttpCallBackUtils.getResultObject(response);if (data != null) {tv.setText(JsonFormatTool.formatJson(data.toString()));}}}@Overridepublic void onErrorResponse(Exception error) {}});App.instance.getRequestQueue().add(jsonRequest);}/*** 用户银行卡*/private void requestUserBankCard() {BcbJsonRequest jsonRequest = new BcbJsonRequest(Urls.UrlUserBand, null, App.instance.getAccessToken(), new BcbRequest.BcbCallBack<JSONObject>() {@Overridepublic void onResponse(JSONObject response) {Log.i("bqt", "用户银行卡:" + response.toString());if (HttpCallBackUtils.getRequestStatus(response, ctx)) {JSONObject data = HttpCallBackUtils.getResultObject(response);if (data != null) {tv.setText(JsonFormatTool.formatJson(data.toString()));}}}@Overridepublic void onErrorResponse(Exception error) {}});App.instance.getRequestQueue().add(jsonRequest);}}
全局Application
public class App extends Application {public static App instance;private RequestQueue requestQueue;private String accessToken;@Overridepublic void onCreate() {super.onCreate();instance = this;}public RequestQueue getRequestQueue() {if (null == requestQueue) requestQueue = Volley.newRequestQueue(this);return requestQueue;}public String getAccessToken() {return accessToken;}public void setAccessToken(String accessToken) {this.accessToken = accessToken;}}
加密解密工具
public class DESUtil {/*** 从加密了的token中获取key*/public static String decodeKey(String encodeToken) {try {byte[] baseDecodeResult = Base64.decode(encodeToken, Base64.DEFAULT);byte[] keybyte = MyConstants.KEY.getBytes();byte[] decodeByte_ECB = ees3DecodeECB(keybyte, baseDecodeResult);String decodeString_ECB = new String(decodeByte_ECB, "UTF-8");// 从已加密的token中解析key// 先解密token为铭文,再解析字符串 {usertoken}|{secutiryKey}if (null != decodeString_ECB && decodeString_ECB.contains("|")) return decodeString_ECB.substring(decodeString_ECB.indexOf("|") + 1);return null;} catch (Exception e) {e.printStackTrace();return null;}}/*** 加密数据*/@SuppressLint("TrulyRandom")public static byte[] des3EncodeECB(byte[] key, byte[] data) throws Exception {DESedeKeySpec spec = new DESedeKeySpec(key);SecretKeyFactory keyfactory = SecretKeyFactory.getInstance("desede");Key deskey = keyfactory.generateSecret(spec);Cipher cipher = Cipher.getInstance("desede" + "/ECB/PKCS7Padding");cipher.init(Cipher.ENCRYPT_MODE, deskey);byte[] bOut = cipher.doFinal(data);return bOut;}/*** 解密数据*/public static byte[] ees3DecodeECB(byte[] key, byte[] data) throws Exception {DESedeKeySpec spec = new DESedeKeySpec(key);SecretKeyFactory keyfactory = SecretKeyFactory.getInstance("desede");Key deskey = keyfactory.generateSecret(spec);Cipher cipher = Cipher.getInstance("desede" + "/ECB/PKCS7Padding");cipher.init(Cipher.DECRYPT_MODE, deskey);byte[] bOut = cipher.doFinal(data);return bOut;}}
请求Request
public abstract class BcbRequest<T> extends Request<T> {protected static final String PROTOCOL_CHARSET = "utf-8";protected static final String CONTENT_TYPE = "application/json; charset=utf-8";//自定义监听器private BcbCallBack<T> mBcbCallBack;private BcbIndexCallBack<T> mBcbIndexCallBack;//Post请求的实体,如果为 null,则为GET请求,否则为POST请求private String mRequestBody;//已加密的token,没有为nullprivate String mEncodeToken;private String key;//位置参数,默认为 -1,表示不使用位置参数回调private int index = -1;//是否添加设备信息private boolean isAddDevInfo = true;//************************************************ 重写请求头,请求头是不用加密的 ******************************************@Overridepublic Map<String, String> getHeaders() throws AuthFailureError {Map<String, String> headers = new HashMap<String, String>();try {if (mEncodeToken != null) headers.put("access-token", mEncodeToken);String pkName = App.instance.getPackageName();//包名String version = App.instance.getPackageManager().getPackageInfo(pkName, 0).versionName;//清单文件中设置的版本号headers.put("version", version);headers.put("platform", "2");Log.i("bqt", "【请求头】" + headers.toString());} catch (PackageManager.NameNotFoundException e) {e.printStackTrace();}return headers;}//************************************************ 重写请求体,请求体中的数据都是加密的 ******************************************/*** 重写请求实体* @return 如果存在请求的参数,则需要返回加了密的请求实体*/@Overridepublic byte[] getBody() {try {// 检测传入的密文token是否为空,没有token参数,数据解密的key为默认的if (null == mEncodeToken) {Log.i("bqt", "【加密前的请求体】" + mRequestBody);key = MyConstants.KEY;} else key = DESUtil.decodeKey(mEncodeToken);// 如果传入参数不为空,则需要加密传入的数据if (null != mRequestBody) {byte[] data = mRequestBody.getBytes(PROTOCOL_CHARSET);byte[] encodeByte_ECB = DESUtil.des3EncodeECB(key.getBytes(), data);String body = Base64.encodeToString(encodeByte_ECB, Base64.DEFAULT);Log.i("bqt", "【加密后的请求体】" + body.toString());return body.getBytes();}} catch (Exception e) {VolleyLog.wtf("Unsupported DES3Encoding while trying to get the bytes of %s using %s", mRequestBody, PROTOCOL_CHARSET);}//返回为空return null;}//************************************************ 构造函数 ******************************************/*** 构造函数* @param url 请求地址* @param requestBody 请求实体* @param encodeToken 已加密的token,没有就传null* @param bcbCallBack 请求结果回调*/public BcbRequest(String url, String requestBody, String encodeToken, BcbCallBack<T> bcbCallBack) {this(requestBody == null ? Method.GET : Method.POST, url, requestBody, encodeToken, bcbCallBack);}/*** 构造函数* @param method 请求方式* @param url 请求地址* @param requestBody 请求实体* @param encodeToken 已加密的token,没有就传null* @param bcbCallBack 请求结果回调*/public BcbRequest(int method, String url, String requestBody, String encodeToken, final BcbCallBack bcbCallBack) {//将出错信息用接口保存起来super(method, url, new ErrorListener() {@Overridepublic void onErrorResponse(VolleyError error) {bcbCallBack.onErrorResponse(error);}});Log.i("url", "url = " + url + " requestBody = " + requestBody);mBcbCallBack = bcbCallBack;if (TextUtils.isEmpty(requestBody)) mRequestBody = null;else mRequestBody = requestBody;mEncodeToken = encodeToken;}/*** 构造函数* @param method 请求方式* @param url 请求接口* @param requestBody 请求实体* @param encodeToken 已加密的token,没有就传null* @param isAddDevInfo 是否添加设备信息* @param bcbCallBack 请求结果回调*/public BcbRequest(int method, String url, String requestBody, String encodeToken, boolean isAddDevInfo, final BcbCallBack bcbCallBack) {//将出错信息用接口保存起来super(method, url, new ErrorListener() {@Overridepublic void onErrorResponse(VolleyError error) {bcbCallBack.onErrorResponse(error);Log.d("url", "error = " + error.toString());}});Log.d("url", "url = " + url + " requestBody = " + requestBody);mBcbCallBack = bcbCallBack;if (TextUtils.isEmpty(requestBody)) mRequestBody = null;else mRequestBody = requestBody;mEncodeToken = encodeToken;this.isAddDevInfo = isAddDevInfo;}/*** 构造函数* @param method 请求方式* @param url 请求接口* @param requestBody 请求实体,没有就传null* @param encodeToken 已加密的token, 没有就传null* @param index 位置参数,主要用于记录列表某个位置请求* @param bcbCallBack 回调*/public BcbRequest(int method, String url, String requestBody, String encodeToken, int index, final BcbIndexCallBack bcbCallBack) {//将出错信息用接口保存起来super(method, url, new ErrorListener() {@Overridepublic void onErrorResponse(VolleyError error) {bcbCallBack.onErrorResponse(error);}});Log.i("bqt", "【url 】 " + url + " 【requestBody 】 " + requestBody);this.index = index;mBcbIndexCallBack = bcbCallBack;if (TextUtils.isEmpty(requestBody)) mRequestBody = null;else mRequestBody = requestBody;mEncodeToken = encodeToken;}//********************************************* 复写的函数 *********************************************@Overrideprotected void deliverResponse(T response) {//如果不存在位置参数,则使用默认回调,否则使用位置回调if (index == -1) mBcbCallBack.onResponse(response);else mBcbIndexCallBack.onResponse(response, index);}/*** 子类必须实现该功能,对返回的回调响应数据 response.data 进行解码转成相应类型的数据*/@Overrideabstract protected Response<T> parseNetworkResponse(NetworkResponse response);/*** @deprecated Use {@link #getBodyContentType()}.*/@Overridepublic String getPostBodyContentType() {return getBodyContentType();}/*** @deprecated Use {@link #getBody()}.*/@Overridepublic byte[] getPostBody() {return getBody();}@Overridepublic String getBodyContentType() {return CONTENT_TYPE;}//************************************************ 回调 ******************************************public interface BcbCallBack<T> {void onResponse(T response);void onErrorResponse(Exception error);}public interface BcbIndexCallBack<T> {void onResponse(T response, int index);void onErrorResponse(Exception error);}}
请求封装Request
public class BcbJsonRequest extends BcbRequest<JSONObject> {private String mEncodeToken;/*** 服务器回调*/@Overrideprotected Response<JSONObject> parseNetworkResponse(NetworkResponse response) {try {//返回不成功,则提示是否成功if (response.statusCode != 200) {Log.i("bqt", "返回出错,状态码为:" + response.statusCode + " 请求链接:" + getUrl());return Response.error(new ParseError());}//获取解密的key,没有token参数,数据解密的key为默认的String key;if (null == mEncodeToken) key = MyConstants.KEY;else key = DESUtil.decodeKey(mEncodeToken);Log.i("bqt", "【加密的Token】" + mEncodeToken);Log.i("bqt", "【解密的Token】" + key);//解密数据String result = new String(response.data);byte[] baseDecodeResult = Base64.decode(result, Base64.DEFAULT);byte[] keybyte = key.getBytes();byte[] decodeByte_ECB = DESUtil.ees3DecodeECB(keybyte, baseDecodeResult);String decodeJsonString = new String(decodeByte_ECB, PROTOCOL_CHARSET);Log.i("bqt", "【加密的JSON串】" + result);Log.i("bqt", "【解密的JSON串】" + decodeJsonString);//返回解密后的对象return Response.success(new JSONObject(decodeJsonString), HttpHeaderParser.parseCacheHeaders(response));} catch (UnsupportedEncodingException e) {return Response.error(new ParseError(e));} catch (JSONException je) {return Response.error(new ParseError(je));} catch (Exception ex) {return Response.error(new ParseError(ex));}}//********************************************* 构造函数 *********************************************/*** 构造函数,默认为POST请求* @param url 请求接口* @param jsonObject JSONObject对象* @param encodeToken Token* @param callBack 请求回调*/public BcbJsonRequest(String url, JSONObject jsonObject, String encodeToken, BcbCallBack<JSONObject> callBack) {this(Method.POST, url, jsonObject, encodeToken, callBack);}/*** 构造函数,默认为POST请求* @param url 请求接口* @param jsonObject JSONObject对象* @param encodeToken Token* @param index 位置参数* @param callBack 请求回调*/public BcbJsonRequest(String url, JSONObject jsonObject, String encodeToken, int index, BcbIndexCallBack<JSONObject> callBack) {this(Method.POST, url, jsonObject, encodeToken, index, callBack);}/*** 构造函数* @param url 请求接口* @param jsonObject JSONObject对象* @param encodeToken Token* @param isAddDevInfo 是否添加设备信息* @param callBack 请求回调*/public BcbJsonRequest(String url, JSONObject jsonObject, String encodeToken, boolean isAddDevInfo, BcbCallBack<JSONObject> callBack) {super(Method.POST, url, jsonObject == null ? "" : jsonObject.toString(), encodeToken, isAddDevInfo, callBack);mEncodeToken = encodeToken;}/*** 构造函数* @param method 请求方式,GET ? POST 还是其他* @param url 请求接口* @param jsonObject JSONObject对象* @param encodeToken Token* @param callBack 请求回调*/public BcbJsonRequest(int method, String url, JSONObject jsonObject, String encodeToken, BcbCallBack<JSONObject> callBack) {super(method, url, jsonObject == null ? "" : jsonObject.toString(), encodeToken, callBack);mEncodeToken = encodeToken;}/*** 构造函数* @param method 请求方式,GET ? POST 还是其他* @param url 请求接口* @param jsonObject JSONObject对象* @param encodeToken Token* @param index 位置参数* @param callBack 请求回调*/public BcbJsonRequest(int method, String url, JSONObject jsonObject, String encodeToken, int index, BcbIndexCallBack<JSONObject> callBack) {super(method, url, jsonObject == null ? "" : jsonObject.toString(), encodeToken, index, callBack);mEncodeToken = encodeToken;}}
Volley 百财帮封装的更多相关文章
- volley二次封装
产品中使用Volley框架已有多时,本身已有良好封装的Volley确实给程序开发带来了很多便利与快捷.但随着产品功能的不断增加,服务器接口的不断复杂化,直接使用Volley原生的JSONObjectR ...
- 继续封装个 Volley 组件
本篇文章已授权微信公众号 dasu_Android(大苏)独家发布 前面已经封装了很多常用.基础的组件了:base-module, 包括了: crash 处理 常用工具类 apk 升级处理 log 组 ...
- volley全然解析
一.volley是什么? 1.简单介绍 Volley是Goole在2013年Google I/O大会上推出了一个新的网络通信框架,它是开源的.从名字由来和配图中无数急促的火箭能够看出 Volley ...
- Android网络框架源码分析一---Volley
转载自 http://www.jianshu.com/p/9e17727f31a1?utm_campaign=maleskine&utm_content=note&utm_medium ...
- Volley框架的使用
所谓Volley,它是2013年Google I/O上发布的一款网络框架,基于Android平台,能使网络通信更快,更简单,更健全. 它的优点:(1)默认Android2.3及以上基于HttpURLC ...
- 【开源项目13】Volley框架 以及 设置request超时时间
Volley提供了优美的框架,使android程序网络访问更容易.更快. Volley抽象实现了底层的HTTP Client库,我们不需关注HTTP Client细节,专注于写出更加漂亮.干净的RES ...
- Volley源码学习笔记
标签(空格分隔): Volley 创建RequestQueue 使用Volley的时候,我们首先需要创建一个RequestQueue对象,用于添加各种请求,创建的方法是Volley.newReques ...
- Volley解析之表单提交篇
要实现表单的提交,就要知道表单提交的数据格式是怎么样,这里我从某知名网站抓了一条数据,先来分析别人提交表单的数据格式. 数据包: Connection: keep-alive Content-Len ...
- Xutils, OKhttp, Volley, Retrofit对比
Xutils这个框架非常全面,可以进行网络请求,可以进行图片加载处理,可以数据储存,还可以对view进行注解,使用这个框架非常方便,但是缺点也是非常明显的,使用这个项目,会导致项目对这个框架依赖非常的 ...
随机推荐
- 用core dump来调试程序段错误
有的程序可以通过编译, 但在运行时会出现Segment fault(段错误). 这通常都是指针错误引起的.但这不像编译错误一样会提示到文件->行, 而是没有任何信息, 使得我们的调试变得困难起来 ...
- jQuery获取select、checkbox、radio的方法总结
在进行网页的前后台交互的时候,经常需要获取单选框(radio).复选框(checkbox)以及下拉列表(select/dropdownlist)选中的值. 总结了一下,方便以后复习查看: 1.获取选中 ...
- grails框架中读取txt文件内容将内容转换为json格式,出现异常Exception in thread "main" org.json.JSONException: A JSONObject text must begin with '{' at character 1 of [...]
Exception in thread "main" org.json.JSONException: A JSONObject text must begin with '{' a ...
- [PHP学习日志]简单Session的使用
首先,给出一些Session的解释:目前最实用的网络协议即HTTP超文本传输协议,它是“无状态”的,所谓“无状态”是指它在用户与服务器交互时没有存储需要交互的“状态”.而Session 是在网络应用中 ...
- Llinux-apache安装
第四章 构建LAMP网站服务平台 实验报告 1.安装apache服务器软件及相关组件 查看系统中是否安装apache服务相关的软件包: [root@www /]# rpm -qa | grep ht ...
- JS 操作Dom节点之CURD
许多优秀的Javascript库,已经封装好了丰富的Dom操作函数,这可以加快项目开发效率.但是对于非常注重网页性能的项目来说,使用Dom的原生操作方法还是必要的. 1. 查找节点 document. ...
- python中的几种遍历列表的方法比较
python的内容非常丰富,给我们带来的便利很多,很多事情的表达方法有很大的多样性,比如我经常需要遍历一个列表,取它的下标和值,这个时候就有很多方法需要取舍一下才行. for循环遍历 l = [1,2 ...
- js中typeof的用法
一. 经常会在js里用到数组,比如 多个名字相同的input, 若是动态生成的, 提交时就需要判断其是否是数组. if(document.mylist.length != "undefine ...
- Solr4.8.0源码分析(10)之Lucene的索引文件(3)
Solr4.8.0源码分析(10)之Lucene的索引文件(3) 1. .si文件 .si文件存储了段的元数据,主要涉及SegmentInfoFormat.java和Segmentinfo.java这 ...
- mvc vs iis默认页面
有时候,再iis里面设置了web的默认页面index.html 希望跳转到这个页面index.html默认页面 而 mvc则跳转到路由里面的设置页面 怎么忽略这个呢. 设置路由可能是个好办法,能实现 ...