Retrofit2+RxJava 简单封装

前言

学习Retrofit2+RxJava时间不长,大概知道怎么用。根据需求简单的封装一下。

1.接口

public interface GankIO{
    @GET("App/10/{index}")
    Call getApp(@Path("index") String index);
}

@POST 请求方式

("819-1") URL地址

@QueryMap Map cityId 请求参数
ResponseBody 返回数据

2.网络请求类#

public class HttpManager {

    public final static int CONNECT_TIMEOUT =5;
    public final static int READ_TIMEOUT=5;
    public final static int WRITE_TIMEOUT=5;
    //服务器地址
    private static final String BASE_URL = "";
    private static Retrofit retrofit;

    private static Retrofit getRetrofit() {
        if (retrofit == null) {
            //网络缓存路径文件
            // File httpCacheDirectory = new File(BaseApplication.getInstance().getExternalCacheDir(), "responses");
            //通过拦截器设置缓存,暂未实现
            //CacheInterceptor cacheInterceptor = new CacheInterceptor();

            OkHttpClient client = new OkHttpClient.Builder()
                .connectTimeout(CONNECT_TIMEOUT, TimeUnit.SECONDS)
                .readTimeout(READ_TIMEOUT, TimeUnit.SECONDS)
                .writeTimeout(WRITE_TIMEOUT, TimeUnit.SECONDS)
                .addInterceptor(new MyInterceptors())
                .build();

            retrofit = new Retrofit.Builder()
                .client(client)
                .baseUrl(BASE_URL)
                .addConverterFactory(GsonConverterFactory.create())
                .addCallAdapterFactory(RxJavaCallAdapterFactory.create())
                .build();
        }
        return retrofit;
    }
}

3.拦截器 MyInterceptors#

public class MyInterceptors implements Interceptor {
    private static final String TAG = "MyInterceptors";
    @Override
    public Response intercept(Chain chain) throws IOException {

        //封装headers
        Request request = chain.request().newBuilder()
                .addHeader("model","24037") //手机型号
                .build();
        Headers headers = request.headers();
        //打印
        System.out.println("phoneModel is : " + headers.get("phoneModel"));
        String requestUrl = request.url().toString(); //获取请求url地址
        String methodStr = request.method(); //获取请求方式
        RequestBody body = request.body(); //获取请求body
        String bodyStr = (body==null?"":body.toString());
        //打印Request数据
        Log.d(TAG, "intercept: Request Url is :" + requestUrl + "\nMethod is : " + methodStr + "\nRequest Body is :" + bodyStr + "\n");

        Response response = chain.proceed(request);

        if (response != null) {
            //byte[] str = Base64.decode(response.body().string(), Base64.DEFAULT);
//            s1 = Base64Decoder.decode(response.body().string());
            //s1 = new String(str);
        } else {
            System.out.println("Respong is null");
        }
        Log.d(TAG, "intercept: response  "+response.body().toString());
        return response;
    }
}

4.调用

Api.getRetrofit().create(GankIO.class).getApp(index).enqueue(new Callback() {
        @Override
        public void onResponse(Call call, Response response) {
          //请求成功处理
        }

        @Override
        public void onFailure(Call call, Throwable t) {
           //请求失败处理
        }
    });

你可能感兴趣的:(Retrofit2+RxJava 简单封装)