Retrofit进阶篇之网络响应拦截

  • 如对Retrofit的使用还不太了解,请查阅我的上篇文章Retrofit的基本了解和简单使用

  • 简介:本篇主要介绍Retrofit接口注解的使用以及Retrofit配合Okhttp实现网络响应错误拦截和自定义错误拦截

部分依赖:
compile ‘com.jakewharton.rxbinding:rxbinding:0.4.0’
compile ‘com.squareup.okhttp3:okhttp:3.4.1’
compile ‘com.squareup.okhttp3:logging-interceptor:3.4.1’

1.创建回调接口:

interface GithubAPIInterface {
    @GET("users/{username}")
    Call<GithubUserDetail> requestUserDetails(@Path("username") String username);

    @GET("users")
    Call<List<GithubUser>> requestUsers(@Query("per_page") Integer perPage);
}

备注:
* @GET 指定请求方式,
* @Query 表示请求参数,将会以key=value的方式拼接在url后面
* 如requestUsers:完整地址https://api.github.com/users?per_page=1
* @PATH 拼接
* 如:requestUserDetails
* https://api.github.com/users/mojombo
*/

2.初始化Retrofit实例设置拦截器:

  HttpLoggingInterceptor httpLoggingInterceptor = new HttpLoggingInterceptor(new HttpLoggingInterceptor.Logger() {
            @Override
            public void log(String message) {
                Log.i("Rxjava", message);
            }
        });
        httpLoggingInterceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
        OkHttpClient okHttpClient = new OkHttpClient.Builder()
                .retryOnConnectionFailure(true)//设置重连
                .connectTimeout(15, TimeUnit.SECONDS)
                .addNetworkInterceptor(httpLoggingInterceptor)
                .build();

备注:
* HttpLoggingInterceptor可以设置无参,这里Logger()设置定向过滤Rxjava,默认是okhttp
* 设置拦截范围:BODY— 请求/响应行 + 头 + 体
* 拦截器分为两种:addInterceptor:设置应用拦截器,主要用于设置公共参数,头信息,日志拦截等addNetworkInterceptor:设置网络拦截器,主要用于重试或重写
*/

   Retrofit retrofit = new Retrofit.Builder()
                .baseUrl(ENDPOINT)
                .client(okHttpClient)
                .addConverterFactory(GsonConverterFactory.create())
                .build();
        mGithubAPI = retrofit.create(GithubAPIInterface.class);

备注:
* 1.基地址必须有(可以是全部,也可以是部分)
* 2.添加拦截器(非必须)
* 3.Converter是对于Call<T>中T的转换, Call<ResponseBody>———>Call<Poju>
* Call<T>中的Call也是可以被替换的,而返回值的类型就决定你后续的处理程序逻辑(非必须)
* 4.初始化Retrofit
* 5.用Retrofit创建出接口的代理对象,用代理对象来操作其方法,返回Call<Poju>
* 通过Call<Poju>来请求入队,execute/enqueue(同步/异步)
*
*/

3.请求回调获取数据

     call = mGithubAPI.requestUsers(PER_PAGE);
        call.enqueue(new Callback<List<GithubUser>>() {
            @Override
            public void onResponse(Call<List<GithubUser>> call, Response<List<GithubUser>> response) {
                final List<GithubUserDetail> githubUserDetails = new ArrayList<>();
                if (response.isSuccessful()) {
                    final List<GithubUser> githubUsers = response.body();
                    for (GithubUser user : githubUsers) {
                        mService.requestUserDetails(user.mLogin).enqueue(new Callback<GithubUserDetail>() {
                            @Override
                            public void onResponse(Call<GithubUserDetail> call, Response<GithubUserDetail> response) {
                                GithubUserDetail githubUserDetail = response.body();
                                githubUserDetails.add(githubUserDetail);
                                if (githubUserDetails.size() == 1) {
                                    EventBus.getDefault().post(githubUserDetails);
                                }
                            }

                            @Override
                            public void onFailure(Call<GithubUserDetail> call, Throwable t) {

                            }
                        });
                    }
                }

            }

            @Override
            public void onFailure(Call<List<GithubUser>> call, Throwable t) {
               // ErrorHandler.handle(t);//自定义错误拦截
            }
        });

4.根据服务端接口返回自定义错误拦截:

public class BodyResponse<T> {
    public String code;
    public String message;
    public T data;

    @Override
    public String toString() {
        return "BodyResponse{" +
                "code='" + code + '\'' +
                ", message='" + message + '\'' +
                ", data=" + data +
                '}';
    }
}
public class ErrorHandler {
    public static BodyResponse handle(Throwable throwable) {
        if (throwable instanceof HttpException) {
            HttpException error = (HttpException) throwable;
            try {
                return new Gson().fromJson(error.response().errorBody().string(),
                        BodyResponse.class);
            } catch (IOException e) {
                e.printStackTrace();
            }
        } else {
            Log.i("tag","throwable.printStackTrac--------------------");
            throwable.printStackTrace();
        }
        return null;
    }
}

代码托管地址

    原文作者:路过的人
    原文地址: https://www.jianshu.com/p/73e08ba0ff37
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞