Android分享Android开发

Retrofit + OkHttp3 + RxJava2

2017-04-28  本文已影响1252人  淡蓝丶天空

配置

满足以下需求

添加依赖

//retrofit2
compile 'com.squareup.retrofit2:retrofit:2.2.0'
//okhttp
compile 'com.squareup.okhttp3:okhttp:3.7.0'
//okhttp 网络请求log 拦截器
compile 'com.squareup.okhttp3:logging-interceptor:3.7.0'
//gson
compile 'com.google.code.gson:gson:2.8.0'
//gson 数据解析适配器
compile 'com.squareup.retrofit2:converter-gson:2.2.0'
//RxJava2
compile 'io.reactivex.rxjava2:rxjava:2.0.9'
compile 'io.reactivex.rxjava2:rxandroid:2.0.1'
//RxJava2 请求结果适配器
compile 'com.squareup.retrofit2:adapter-rxjava2:2.2.0'

基本使用流程

配置OkHttpClient

public class Client {
    private static OkHttpClient mOkHttpClient;
    private final static HttpLoggingInterceptor HTTP_LOGGING_INTERCEPTOR =
            new HttpLoggingInterceptor(message -> Log.d("Http:", message))
                    .setLevel(HttpLoggingInterceptor.Level.BODY);
    /**
    * 因为设置了读写超时,该client不适用于上传和下载
    */
    public static OkHttpClient get() {
        if (mOkHttpClient == null) {
            mOkHttpClient = new OkHttpClient.Builder()
                    //log 拦截器
                    .addInterceptor(HTTP_LOGGING_INTERCEPTOR)
                    .connectTimeout(10, TimeUnit.SECONDS)
                    .readTimeout(30, TimeUnit.SECONDS)
                    .writeTimeout(30,TimeUnit.SECONDS)
                    .build();
        }
        return mOkHttpClient;
    }
}

定义Retrofit

public class Retrofits {
    private static Retrofit mRetrofit;
    public static Retrofit get() {
        if(mRetrofit == null){
            mRetrofit = new Retrofit.Builder()
                    .baseUrl(BuildConfig.BASE_SERVER)
                    .client(Client.get())
                    .addConverterFactory(GsonConverterFactory.create())
                    .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
                    .build();
        }
        return mRetrofit;
    }
    public static <T> T get(Class<T> tClass){
        return get().create(tClass);
    }
}

定义Model

定义API接口

public interface Api {
    @GET("/test/getServerInfo")
    Observable<BaseResult<ServerInfo>> getServerInfo();
}

发起网络请求

Retrofits.get(Api.class)
  .getServerInfo()
  //指定在IO线程进行网络请求
  .subscribeOn(Schedulers.io())
  //指定订阅者在UI线程响应
  .observeOn(AndroidSchedulers.mainThread())
  //处理结果
  .subscribe(result -> {
    if (result.isSuccess()) {
      Toast.makeText(this,
                     result.getData().toString(),
                     Toast.LENGTH_SHORT)
        .show();
    }else {
      Toast.makeText(this,
                     String.format("失败:%s", result.getMessage()),
                     Toast.LENGTH_SHORT)
        .show();
    }
  });

Retrofit说明

注解说明

Body

注:此处所使用的序列化通过.addConverterFactory()进行配置,前文Demo使用的是Gson

示例:

//实体
class Repo {
  final String owner;
  final String name;
  ...
}

interface Api{
  ...
  @POST("/")
  Observable<BaseResult<Body>> sendNormal(@Body Repo repo);
  ...
}

Field

示例:


@POST("/")
Call<ResponseBody> sample(@Field("name") String name);

@POST("/list")
Call<ResponseBody> sample(@Field("name") String... names);

FieldMap

示例:

   @POST("/things")
   Call<ResponseBody> things(@FieldMap Map<String, String> fields);

Header

示例

 @GET("/")
 Call<ResponseBody> foo(@Header("Accept-Language") String lang);

HeaderMap

示例:

 @GET("/search")
 Call<ResponseBody> list(@HeaderMap Map<String, String> headers);

Headers

示例:

   @Headers("Cache-Control: max-age=640000")
   @GET("/")
   ...
  
   @Headers({
     "X-Foo: Bar",
     "X-Ping: Pong"
   })
   @GET("/")
   ...

Path

示例:

   @GET("/user/{name}")
   Call<ResponseBody> encoded(@Path("name") String name);
  
   @GET("/user/{name}")
   Call<ResponseBody> notEncoded(@Path(value="name", encoded=true) String name);

Query

示例

 @GET("/friends")
 Call<ResponseBody> friends(@Query("page") int page);

如果调用传入参数为1,则请求URL为/friends?page=1

 @GET("/friends")
 Call<ResponseBody> friends(@Query("group") String... groups);

如果调用传入参数为["1","2","3"],则请求URL为/friends?group=1&group=2&group=3

QueryMap

示例:

   @GET("/friends")
   Call<ResponseBody> friends(@QueryMap Map<String, String> filters);

RxJava配置

对于Rx的配置通过Retrofit.Builder.addCallAdapterFactory进行设置的。

Retrofit提供了RxJava2CallAdapterFactory类来进行构建。

需要注意的是RxJava2CallAdapterFactory中需要配置网络请求的执行方式。目前提供以下3种

上一篇下一篇

猜你喜欢

热点阅读