【Android】Retrofit知识汇总

整体知识

Carson带你学Android:网络请求库Retrofit使用教程(含实例讲解) - 简书

Retrofit一些基础知识_xuyin1204的博客-CSDN博客

简单步骤和demo

Retrofit2 实战(一、使用详解篇) - 掘金

进阶使用:

1、类型转换、rxjava、okhttp;

2、使用retrofit做为网络请求时,解决多个BaseURL切换的问题:添加okhttpclient拦截器,捕获添加的Headers,然后修改baseURL

Retrofit2详解_retrofit2 params-CSDN博客

超时-重试-缓存-拦截器

Android-Retrofit-超时-重试-缓存-拦截器 - 简书

重试两种方式:

如果不是全局用同一个重试机制,由于会每次都需要创建一个OkHttpInterceptor,会造成资源浪费,不建议使用。

Retrofit实现重试机制(自定义Interceptor或封装callback)_retrofit 重试-CSDN博客

做个完善

public class OkHttpRetryInterceptor implements Interceptor {

    private List<Long> retryIntervalList = new ArrayList<>();

    public OkHttpRetryInterceptor(List<Long> retryIntervalList) {
        if (retryIntervalList != null && !retryIntervalList.isEmpty()) {
            this.retryIntervalList = retryIntervalList;
            return;
        }
        //默认1.5秒重试一次
        retryIntervalList.add(1500L);
    }

    /**
     * 该方法提供了一个Chain类型的对象,Chain对象中可以获取到Request对象
     * ,而调用Chain对象的proceed方法(该方法接收一个Request对象)就可发起一次网络请求
     * ,该方法返回Response对象。
     *
     * @param chain
     * @return
     * @throws IOException
     */
    @Override
    public Response intercept(Chain chain) throws IOException {
        Request request = chain.request();
        Response response = doRequest(chain, request);
        if (response != null && response.isSuccessful()) {
            return response;
        }

        for (int i = 0; i < retryIntervalList.size(); i++) {
            Long retryInterval = retryIntervalList.get(i);
            if (retryInterval == null) {
                continue;
            }
            if (i == 0 || ((response == null) || !response.isSuccessful())) {
                try {
                    Thread.sleep(retryInterval);
                } catch (Exception e) {
                    e.printStackTrace();
                }
                response = doRequest(chain, request);
            }
        }

        return response;
    }

    private Response doRequest(Chain chain, Request request) {
        try {
            return chain.proceed(request);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

    public static class Builder {

        private List<Long> retryIntervalList = new ArrayList<>();

        public Builder buildRetryInterval(List<Long> retryIntervalList) {
            this.retryIntervalList = retryIntervalList;
            return this;
        }

        public OkHttpRetryInterceptor build() {
            return new OkHttpRetryInterceptor(retryIntervalList);
        }
    }

}

解决多个BaseURL切换其他方案

解决Retrofit多BaseUrl及运行时动态改变BaseUrl? - 简书

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容