背景
在Time Cat项目开发过程中,我们尝试过很多网络请求库。基本点的就是原生的http请求框架,好比
HttpClient以及HttpUrlConnection等,略懂android开发的估计无人不知android-async-http或者volley啥的,再往上走,有okhttp等。但是最后我们选择了一个新的http请求框架,Retrofit。Retrofit简介
retrofit是Square公司出品的,为android和java提供一个类型安全的Http网络请求库,这里是官网地址。Retrofit的优点- 使用注解来描述http请求
- URL参数的替换和query参数的支持
- 对象转化为请求体(如:JSON,protocol buffers等)
- 多重请求体和文件上传 以上都是官网描述
TimeCat中的实例
定义接口
// NoteService.java public interface NoteService { @Headers({"Content-Type: application/json", "Accept: application/json"}) @POST("/notes/") Observable<Note> createNote(@Body Note note); }
辅助使用Retrofit
// RetrofitHelper.java public class RetrofitHelper { private static final String BASE_URL = "http://192.168.88.105:8000/"; private static OkHttpClient mOkHttpClient; static { initOkHttpClient(); } /** * 初始化OKHttpClient * 设置缓存 * 设置超时时间 * 设置打印日志 * 设置UA拦截器 */ private static void initOkHttpClient() { HttpLoggingInterceptor interceptor = new HttpLoggingInterceptor(new Log()); interceptor.setLevel(HttpLoggingInterceptor.Level.BODY); if (mOkHttpClient == null) { synchronized (RetrofitHelper.class) { if (mOkHttpClient == null) { //设置Http缓存 Cache cache = new Cache(new File(TimeCatApp.getInstance().getCacheDir(), "HttpCache"), 1024 * 1024 * 100); mOkHttpClient = new OkHttpClient.Builder().cache(cache).addInterceptor(interceptor).retryOnConnectionFailure(true).connectTimeout(30, TimeUnit.SECONDS).writeTimeout(20, TimeUnit.SECONDS).readTimeout(20, TimeUnit.SECONDS).build(); } } } } public static NoteService getNoteService() { Retrofit retrofit = new Retrofit.Builder() .baseUrl(BASE_URL) .client(mOkHttpClient) .addCallAdapterFactory(RxJavaCallAdapterFactory.create()) .addConverterFactory(GsonConverterFactory.create()) .build(); return retrofit.create(NoteService.class); } }
结合RxJava发起网络请求只需要
RetrofitHelper.getNoteService().createNote(note) //获取Observable对象 .compose(this.bindToLifecycle()) // 绑定到生命周期 .subscribeOn(Schedulers.newThread()) //请求在新的线程中执行 .observeOn(Schedulers.io()) //请求完成后在io线程中执行 .doOnNext(new Action1<Note>() { @Override public void call(Note note) { DB.notes().saveAndFireEvent(ModelUtil.toDBNote(note)); // 进行数据读写,甚至可以进行文件读写 Log.e(TAG, "保存任务信息到本地" + note.toString()); } }) .observeOn(AndroidSchedulers.mainThread())//最后在主线程中执行 .subscribe(new Subscriber<Note>() { @Override public void onCompleted() { } @Override public void onError(Throwable e) { //请求失败 ToastUtil.show("添加[ 任务 ]失败"); Log.e(TAG, e.toString()); } @Override public void onNext(Note note) { //请求成功 ToastUtil.show("成功添加[ 任务 ]:" + dialog_add_task_et_content.getText().toString()); finish(); Log.e(TAG, "请求成功" + note.toString()); } });
使用的套路
权限
<uses-permission android:name="android.permission.INTERNET" />
这个没什么好说的,没有网络权限什么都做不了
导包
compile 'com.squareup.retrofit2:retrofit:2.1.0' compile 'com.squareup.retrofit2:converter-gson:2.1.0' compile 'com.squareup.retrofit2:adapter-rxjava:2.1.0' compile 'com.squareup.okhttp3:logging-interceptor:3.4.1' compile 'io.reactivex:rxandroid:1.2.1'
这里几个库的含义是:我们使用
retrofit2.0去进行网络请求操作,同时我们使用gson去进行数据解析,并且结合rxjava去进行相应的代码编写基本配置
new Retrofit.Builder() .baseUrl(BASE_URL) .client(mOkHttpClient) .addCallAdapterFactory(RxJavaCallAdapterFactory.create()) .addConverterFactory(GsonConverterFactory.create()) .build();
这段就是使用
RxJava,利用gson做解析(这边解析器可以设置注入Jackson之类的,甚至可以自定义),http引擎框架是okhttpAPI说明
Retrofit需要通过注解请求方法以及请求参数来表明应该如何去进行一个Http请求,目前内置了5种注解方式GET、POST、PUT、DELETE以及HEAD。同时资源的相对URL要在注解中明确的指出。比如请求方法@POST("/notes/")
@POST("/notes/")的意思是,用POST方法,向BASE_URL + 'notes/' 即http://192.168.88.105:8000/notes/发起请求。注意两个斜杆,左边的/代表在BASE_URL的基础上,右边的/表示notes的实际接口,去掉其中一个都会导致不同的结果。更多api的写法请看下一篇
参考
https://www.jianshu.com/p/6b3daeda1eed
