经过上面的学习,咱们不难发现单纯使用okHttp来做为网络库仍是多多少少有那么一点点不太方便,并且还需本身来管理接口,对于接口的使用的是哪一种请求方式也不能一目了然,出于这个目的接下来学习一下Retrofit+Okhttp的搭配使用。html
okHttp相关文章地址:java
Retrofit和okHttp师出同门,也是Square的开源库,它是一个类型安全的网络请求库,Retrofit简化了网络请求流程,基于OkHtttp作了封装,解耦的更完全:比方说经过注解来配置请求参数,经过工厂来生成CallAdapter,Converter,你可使用不一样的请求适配器(CallAdapter), 比方说RxJava,Java8, Guava。你可使用不一样的反序列化工具(Converter),比方说json, protobuff, xml, moshi等等。react
compile 'com.squareup.retrofit2:retrofit:2.1.0'
retrofit = new Retrofit.Builder() .baseUrl(BASE_URL) .addConverterFactory(FastJsonConverterFactory.create()) .client(mOkHttpClient) .build();
OkHttpClient.Builder builder = new OkHttpClient().newBuilder() .connectTimeout(10, TimeUnit.SECONDS)//设置超时时间 .readTimeout(10, TimeUnit.SECONDS)//设置读取超时时间 .writeTimeout(10, TimeUnit.SECONDS);//设置写入超时时间 int cacheSize = 10 * 1024 * 1024; // 10 MiB Cache cache = new Cache(App.getContext().getCacheDir(), cacheSize); builder.cache(cache); builder.addInterceptor(interceptor); mOkHttpClient = builder.build();
关于okHttp的拦截器、Cache-Control等这里就再也不作解说了android
对于okHttpClient的初始化咱们都已经很熟悉了,对ConverterFactory初次接触多少有点陌生,其实这个就是用来统一解析ResponseBody返回数据的。git
常见的ConverterFactorygithub
com.squareup.retrofit2:converter-gson
com.squareup.retrofit2:converter-jackson
com.squareup.retrofit2:converter-moshi
com.squareup.retrofit2:converter-protobuf
com.squareup.retrofit2:converter-wire
com.squareup.retrofit2:converter-simplexml
com.squareup.retrofit2:converter-scalars
因为项目中使用的是FastJson,因此只能本身自定义ConverterFactory,不过国内已经有大神对此做了封装(http://www.tuicool.com/articles/j6rmyi7)。json
1.get请求 不带任何参数api
public interface IApi { @GET("users")//不带参数get请求 Call<List<User>> getUsers(); }
2.get请求 动态路径 @Path使用缓存
public interface IApi { @GET("users/{groupId}")//动态路径get请求 Call<List<User>> getUsers(@Path("userId") String userId); }
3.get请求 拼接参数 @Query使用安全
public interface IApi { @GET("users/{groupId}") Call<List<User>> getUsers(@Path("userId") String userId, @Query("age")int age); }
3.get请求 拼接参数 @QueryMap使用
public interface IApi { @GET("users/{groupId}") Call<List<User>> getUsers(@Path("userId") String userId, @QueryMap HashMap<String, String> paramsMap); }
1.post请求 @body使用
public interface IApi { @POST("add")//直接把对象经过ConverterFactory转化成对应的参数 Call<List<User>> addUser(@Body User user); }
2.post请求 @FormUrlEncoded,@Field使用
public interface IApi { @POST("login") @FormUrlEncoded//读参数进行urlEncoded Call<User> login(@Field("userId") String username, @Field("password") String password); }
3.post请求 @FormUrlEncoded,@FieldMap使用
public interface IApi { @POST("login") @FormUrlEncoded//读参数进行urlEncoded Call<User> login(@FieldMap HashMap<String, String> paramsMap); }
4.post请求 @Multipart,@Part使用
public interface IApi { @Multipart @POST("login") Call<User> login(@Part("userId") String userId, @Part("password") String password); }
public interface IApi { @Headers("Cache-Control: max-age=640000") @GET("users")//不带参数get请求 Call<List<User>> getUsers(); }
1.返回IApi
/** * 初始化Api */ private void initIApi() { iApi = retrofit.create(IApi.class); } /** * 返回Api */ public static IApi api() { return api.iApi; }
2.发送请求
Call<String> call = Api.api().login(userId,password); call.enqueue(new Callback<String>() { @Override public void onResponse(Call<String> call, Response<String> response) { Log.e("", "response---->" + response.body()); } @Override public void onFailure(Call<String> call, Throwable t) { Log.e("", "response----失败"); } });
上面介绍了Retrofit 与OkHttp的结合,下面介绍一下Retrofit与RxJava的结合,RxJava做为当前的开源库的网红之一,Retrofit理所固然也提供了对其的支持,RxJava的强大之处强大的异步处理能力,Retrofit与RxJava的结合势必提升开发效率以及运行性能。
compile 'com.squareup.retrofit2:adapter-rxjava:2.0.1' // Retrofit的rx解析库
compile 'io.reactivex:rxandroid:1.2.0'
compile 'io.reactivex:rxjava:1.1.5'
/** * 初始化Retrofit */ private void initRetrofit() { retrofit = new Retrofit.Builder() .baseUrl(BASE_URL) .addConverterFactory(FastJsonConverterFactory.create()) .addCallAdapterFactory(RxJavaCallAdapterFactory.create()) .client(mOkHttpClient) .build(); }
public interface IApi { @POST("system/login") Observable<String> systemLogin(@Body String userId, @Body String password);
}
Api.api().systemLogin(userId,password) .subscribeOn(Schedulers.io()) .observeOn(AndroidSchedulers.mainThread()) .subscribe(new Subscriber<String>() { @Override public void onCompleted() { } @Override public void onError(Throwable e) { } @Override public void onNext(String result) { } });
这里简单介绍了Retrofit与Okhttp、RxJava的结合使用。