文档详情

Android架构系列-封装自己的okhttp.docx

发布:2017-06-26约5.13千字共10页下载文档
文本预览下载声明
Android架构系列-封装自己的okhttp1 网络库的选择和为什么放弃retrofit本来项目的网络库选择的搭配是最流行的retrofit+okhttp+gson.如下图版本库里还有记录。版本记录But!后来遇到了这样的问题:服务端提供的API无法遵循Restful的API格式,而且不同模块由于分服务开发的,也不能保证格式一致。导致 API接口层的实现十分牵强。最终api层的编写不能专注于业务,适得其反。(最起码现在的服务端还不适合与retrofit的使用)最后决定放弃使用retrofit,使用自己二次封装的okhttp。2 封装使用okhttp封装过程中参考了:hongyang的Android OkHttp完全解析 是时候来了解OkHttp了赵凯强的开源项目OkHttpPlus2.1 怎么使用先说封装好的okhttp+gson如何使用。(封装了POST请求,GET请求,上传文件,下载文件,取消请求和Gson转换等功能)2.1.1 POST请求MapString, String params = new HashMapString, String();params.put(name, tsy);MyOkHttp.get().post(this, /test_okhttp.php, params, new JsonResponseHandler() {@Overridepublic void onSuccess(int statusCode, JSONObject response) { LogUtils.v(TAG, statusCode + + response); }@Overridepublic void onFailure(int statusCode, String error_msg) { LogUtils.v(TAG, statusCode + + error_msg); }});2.1.2 GET请求MapString, String params = new HashMapString, String();params.put(name, tsy);MyOkHttp.get().get(this, /test_okhttp.php, params, new RawResponseHandler() {@Overridepublic void onSuccess(int statusCode, String response) { LogUtils.v(TAG, statusCode + + response); }@Overridepublic void onFailure(int statusCode, String error_msg) { LogUtils.v(TAG, statusCode + + error_msg); }});2.1.3 上传文件MapString, String params = new HashMapString, String();params.put(name, tsy);MapString, File files = new HashMapString, File();File file = new File(Environment.getExternalStorageDirectory() + /com.ci123.service.splashandroid/splash/1.png);files.put(avatar, file);MyOkHttp.get().upload(this, /test_post.php, params, files, new GsonResponseHandlerBB() {@Overridepublic void onFailure(int statusCode, String error_msg) { LogUtils.v(TAG, statusCode + + error_msg); }@Overridepublic void onSuccess(int statusCode, BB response) { LogUtils.v(TAG, statusCode + + response.ret); }@Overridepublic void onProgress(long currentBytes, long totalBytes) { LogUtils.v(TAG, currentBytes + / + totalBytes); }});2.1.4 下载文件MyOk
显示全部
相似文档