NoHttp1.1.0发布,支持与RxJava
完美结合、支持一句话切换底层OkHttp
、URLConnection
,支持缓存数据到DB或者SD卡,支持Cookie的自动维护,完美支持Restful风格的接口,比Retrofit更简单易用。 java
NoHttp 源码地址:github.com/yanzhenjie/… android
NoHttp详细使用文档:doc.nohttp.netgit
欢迎加入QQ交流群:547839514github
比Retrofit使用更简单、更易用。数据库
compile 'com.yolanda.nohttp:nohttp:1.1.0'复制代码
compile 'com.yanzhenjie.nohttp:okhttp:1.1.0'复制代码
若是使用OkHttp作为网络层
下载NoHttp-OkHttp Jar包,而且请自行下载okhttp、okio的jar包。express
建议没用Android的同窗尽早切换到AndroidStudio来开发Android应用。apache
NoHttp初始化须要一个Context,最好在Application
的onCreate()
中初始化,记得在manifest.xml
中注册Application
。json
直接初始化后,一切采用默认设置。api
NoHttp.initialize(this);复制代码
超时配置,默认10s缓存
NoHttp.initialize(this, new NoHttp.Config()
// 设置全局链接超时时间,单位毫秒
.setConnectTimeout(30 * 1000)
// 设置全局服务器响应超时时间,单位毫秒
.setReadTimeout(30 * 1000)
);复制代码
配置缓存,默认保存在数据库
NoHttp.initialize(this, new NoHttp.Config()
...
// 保存到数据库
.setCacheStore(
new DBCacheStore(this).setEnable(true) // 若是不使用缓存,设置false禁用。
)
// 或者保存到SD卡
.setCacheStore(
new DiskCacheStore(this)
)
);复制代码
配置Cookie保存的位置,默认保存在数据库
NoHttp.initialize(this, new NoHttp.Config()
...
// 默认保存数据库DBCookieStore,开发者能够本身实现。
.setCookieStore(
new DBCookieStore(this).setEnable(false) // 若是不维护cookie,设置false禁用。
)
);复制代码
配置网络层
NoHttp.initialize(this, new NoHttp.Config()
...
// 使用HttpURLConnection
.setNetworkExecutor(new URLConnectionNetworkExecutor())
// 使用OkHttp
.setNetworkExecutor(new OkHttpNetworkExecutor())
);复制代码
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />复制代码
Logger.setDebug(true);// 开启NoHttp的调试模式, 配置后可看到请求过程、日志和错误信息。
Logger.setTag("NoHttpSample");// 设置NoHttp打印Log的tag。复制代码
开启NoHttp的调试模式后可看到请求过程、日志和错误信息,基本不用抓包。能够看到请求头、请求数据、响应头、Cookie等,并且打印出的Log很是整齐。
因此说,若是你使用过程当中遇到什么问题了,开启调试模式,一切妖魔鬼怪都会现形的。
能够与RxJava、RxAndroid、RxBus、EventBus等第三方异步任务框架完美结合使用,这里在demo中给出了和RxJava一块儿使用的代码。
NoHttp能够和RxJava完美结合,这里列出如何使用,具体的封装请参考Demo的RxNoHttp。
Request<UserInfo> request = new JavaBeanRequest<>(url, UserInfo.class);
RxNoHttp.request(this, request, new SimpleSubscriber<Response<UserInfo>>() {
@Override
public void onNext(Response<YanZhenjie> entityResponse) {
// 直接拿到实体对象
UserInfo userInfo = entiryResponse.get();
}
});复制代码
RequestQueue requestQueue = NoHttp.newRequestQueue();
// 若是要指定并发值,传入数字便可:NoHttp.newRequestQueue(3);
// 发起请求
requestQueue.add(what, request, responseListener);复制代码
responseLisetener
响应时回调给开发者,因此开发者能够用一个responseLisetener
接受多个请求的响应,用what来区分结果。而不用像有的框架同样,每个请求都要new一个callback。 Request<String> request = NoHttp.createStringRequest(url, RequestMethod.GET);
requestQueue.add(0, request, listener);复制代码
// JsonObject
Request<JSONObject> objRequest = NoHttp.createJsonObjectRequest(url, RequestMethod.POST);
requestQueue.add(0, objRequest, listener);
// JsonArray
Request<JSONArray> arrayRequest = NoHttp.createJsonArrayRequest(url, RequestMethod.PUT);
requestQueue.add(0, arrayRequest, listener);复制代码
Request<Bitmap> request = NoHttp.createImageRequest(url, RequestMethod.DELETE);
requestQueue.add(0, request, listener);复制代码
// FastJson
Request<JSONObject> request = new FastJsonRequest(url, RequestMethod.POST);
requestQueue.add(0, request, listener);复制代码
// 内部使用Gson、FastJson解析成JavaBean
Request<UserInfo> request = new JavaBeanRequest(url, RequestMethod.GET);
requestQueue.add(0, request, listener);复制代码
Request<JSONObject> request = new JavaBeanRequest(url, RequestMethod.POST);
.add("name", "yoldada") // String类型
.add("age", 18) // int类型
.add("sex", '0') // char类型
.add("time", 16346468473154) // long类型
// 添加Bitmap
.add("head", new BitmapBinary(bitmap))
// 添加File
.add("head", new FileBinary(file))
// 添加ByteArray
.add("head", new ByteArrayBinary(byte[]))
// 添加InputStream
.add("head", new InputStreamBinary(inputStream));复制代码
文件上传实现了http表单的标准协议,知足了广大开发者的需求,有如下几种形式:
单个文件
Request<String> request = ...
request.add("file", new FileBinary(file));复制代码
上传多个文件、多个Key多个文件形式
这里能够添加各类形式的文件,File、Bitmap、InputStream、ByteArray。
Request<String> request = ...
request.add("file1", new FileBinary(File));
request.add("file2", new FileBinary(File));
request.add("file3", new InputStreamBinary(InputStream));
request.add("file4", new ByteArrayBinary(byte[]));
request.add("file5", new BitmapBinary(Bitmap));复制代码
上传多个文件、一个Key多个文件形式
Request<String> request = ...
List<Binary> fileList = new ArrayList<>(4);
fileList.add(new FileBinary(File));
fileList.add(new InputStreamBinary(InputStream));
fileList.add(new ByteArrayBinary(byte[]));
fileList.add(new BitmapStreamBinary(Bitmap));
request.add("file_list", fileList);复制代码
提交Body分为提交Json、提交String、提交Xml、提交流等,具体用法以下:
// 提交普通String
request.setDefineRequestBody(String, ContentType);
// 提交json字符串
request.setDefineRequestBodyForJson(JsonString)
// 提交jsonObject对象,其实仍是json字符串
request.setDefineRequestBodyForJson(JSONObject)
// 提交xml字符串
request.setDefineRequestBodyForXML(XmlString)
// 提交字体Body,好比File(这跟表单上传不同的),能够转为InputStream来提交
request.setDefineRequestBody(InputStream, ContentType)复制代码
在当前线程发起请求,在线程这么使用。
Request<String> request = NoHttp.createStringRequest(url, RequestMethod.DELETE);
Response<String> response = NoHttp.startRequestSync(request);
if (response.isSucceed()) {
// 请求成功
} else {
// 请求失败
}复制代码
NoHttp的缓存很是强大,支持缓存到数据库、换到SD卡等,而且不论缓存在数据库或者SD,NoHttp都把数据进行了加密,须要在初始化的时候配置缓存的位置。
须要注意的是,在6.0以上的手机中若是要缓存在SD卡,须要在请求以前,须要请求运行时权限,若是你不懂运行时权限,能够看这个项目:AndPermission。
NoHttp.initialize(this, new NoHttp.Config()
...
// 保存到数据库
.setCacheStore(
new DBCacheStore(this).setEnable(true) // 若是不使用缓存,设置false禁用。
)
// 或者保存到SD卡
.setCacheStore(
new DiskCacheStore(this)
)
);复制代码
一、Default模式,实现http 304重定向缓存
NoHttp自己是实现了RFC2616,因此这里不用设置或者设置为DEFAULT。
Request<JSONObject> request = NoHttp.createJsonObjectRequest(url);
request.setCacheMode(CacheMode.DEFAULT);复制代码
二、 当请求服务器失败的时候,读取缓存
请求服务器成功则返回服务器数据,若是请求服务器失败,读取缓存数据返回。
Request<JSONObject> request = NoHttp.createJsonObjectRequest(url);
request.setCacheMode(CacheMode.REQUEST_NETWORK_FAILED_READ_CACHE);复制代码
三、若是发现有缓存直接成功,没有缓存才请求服务器
咱们知道ImageLoader的核心除了内存优化外,剩下一个就是发现把内地有图片则直接使用,没有则请求服务器,因此NoHttp这一点很是使用作一个ImageLoader。
Request<Bitmap> request = NoHttp.createImageRequest(imageUrl);
request.setCacheMode(CacheMode.IF_NONE_CACHE_REQUEST_NETWORK);复制代码
四、仅仅请求网络
这里不会读取缓存,也不支持Http304。
Request<Bitmap> request = NoHttp.createImageRequest(imageUrl);
request.setCacheMode(CacheMode.ONLY_REQUEST_NETWORK);
...复制代码
五、仅仅读取缓存
仅仅读取缓存,不会请求网络和其它操做。
Request<Bitmap> request = NoHttp.createImageRequest(imageUrl);
request.setCacheMode(CacheMode.ONLY_READ_CACHE);复制代码
由于下载文件代码比较多,这里贴关键部分,具体的请参考demo。
文件下载也是队列,队列和开头所说的请求的队列是同样的。
发起下载请求
//下载文件
downloadRequest = NoHttp.createDownloadRequest...
// what 区分下载
// downloadRequest 下载请求对象
// downloadListener 下载监听
downloadQueue.add(0, downloadRequest, downloadListener);复制代码
暂停或者中止下载
downloadRequest.cancel();复制代码
监听下载过程
private DownloadListener downloadListener = new DownloadListener() {
@Override
public void onStart(int what, boolean resume, long preLenght, Headers header, long count) {
// 下载开始
}
@Override
public void onProgress(int what, int progress, long downCount) {
// 更新下载进度
}
@Override
public void onFinish(int what, String filePath) {
// 下载完成
}
@Override
public void onDownloadError(int what, StatusCode code, CharSequence message) {
// 下载发生错误
}
@Override
public void onCancel(int what) {
// 下载被取消或者暂停
}
};复制代码
NoHttp支持取消某个请求、取消指定多个请求、取消全部请求。
取消单个请求
直接调用请求对象的cancel方法。
request.cancel();复制代码
从队列中取消指定的请求
在请求以前给请求set一个sign,取消的时候调用队列的cancelBySign就能够取消掉全部指定这个sign的请求。
request1.setCancelSign(sign);
request2.setCancelSign(sign);
// 取消队列中多个用sign标志的请求
queue.cancelBySign(sign);复制代码
取消队列中全部请求
queue.cancelAll();复制代码
队列中止后再添加请求到队列后,请求不会被执行。
RequestQueue queue = NoHttp.newRequestQueue();
...
queue.stop();复制代码
FastJsonRequest
public class FastJsonRequest extends RestRequestor<JSONObject> {
public FastJsonRequest(String url) {
this(url, RequestMethod.GET);
}
public FastJsonRequest(String url, RequestMethod requestMethod) {
super(url, requestMethod);
}
@Override
public JSONObject parseResponse(Headers header, byte[] body) throws Throwable {
String result = StringRequest.parseResponseString(headers, body);
return JSON.parseObject(result);
}
}复制代码
JavaBeanRequest,利用FastJson、Gson等把数据直接转为JavaBean
public class JavaBeanRequest<T> extends RestRequest<T> {
private Class<T> clazz;
public JavaBeanRequest(String url, Class<T> clazz) {
this(url, RequestMethod.GET, clazz);
}
public JavaBeanRequest(String url, RequestMethod requestMethod, Class<T> clazz) {
super(url, requestMethod);
this.clazz = clazz;
}
@Override
public T parseResponse(Headers header, byte[] body) throws Throwable {
String response = StringRequest.parseResponseString(header, body);
// 这里若是数据格式错误,或者解析失败,会在失败的回调方法中返回 ParseError 异常。
return JSON.parseObject(response, clazz);
}
}复制代码
使用自定义请求
// 使用FastJson自定义请求
Request<JSONObject> request = new FastJsonRequest(url, requestMethod);
queue.add(what, mRequest, listener);
// 直击请求JavaBean
Request<UserInfo> request = new JavaBeanRequest(url, UserInfo.class);
queue.add(what, request, listener);复制代码
NoHttp设计到兼容高版本系统的api采用反射调用,因此全部类均可以被混淆
若是你非要keep的话,以下配置便可
-dontwarn com.yolanda.nohttp.**
-keep class com.yolanda.nohttp.**{*;}复制代码
NoHttp 源码地址:github.com/yanzhenjie/…
Copyright 2016 Yan Zhenjie
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.复制代码