美文网首页
Retrofit 源码解析-1、基本使用.md

Retrofit 源码解析-1、基本使用.md

作者: 飞奔的口罩 | 来源:发表于2020-09-27 19:59 被阅读0次

一、基本使用

1、创建Retrofit类

 Retrofit retrofit = new Retrofit.Builder()
                .baseUrl(BaseHttpUrl.BASE_URL)
                //使用网络请求内核,默认就是okhttp。可以设置okhttp相关内容
                .client(new OkHttpClient())
                //转换器,作用就是讲response的数据进行解码
                .addConverterFactory(GsonConverterFactory.create())
                //添加异步适配器,默认使用ExecutorCallbackCall()。
                // 默认适配器实际上就是通过调用okhttp的call.enqueue()方法发起请求,并异步处理回调。
                // 也可以使用rxjava进行处理。后续文章中我们在说rxjava的使用。
                //.addCallAdapterFactory(RxJavaCallAdapterFactory.create())
                .build();

2、自定义OkHttpClient()

    // 1、创建http日志 拦截器
    HttpLoggingInterceptor httpLoggingInterceptor = new HttpLoggingInterceptor(new HttpLoggingInterceptor.Logger() {
        @Override
        public void log(String message) {
            Logger.e("okhttp",message);
        }
    });
    httpLoggingInterceptor.setLevel(HttpLoggingInterceptor.Level.BODY);

    // 2、指定缓存路径,缓存大小100Mb
    Cache cache = new Cache(new File(StoragePathConfig.getAppCacheDir(), "HttpCache"),
            1024 * 1024 * 100);
    // 3、创建OkHttpClient
    mOkHttpClient = new OkHttpClient.Builder()
            //添加缓存
            .cache(cache)
            //添加自定义Intercept,可以统一设置Request的通用Header头
            .addInterceptor(new SignInterceptor())//添加签名
            //添加http日志拦截器
            .addInterceptor(httpLoggingInterceptor)
            //默认重试连接1次,如果需要多次重试。需要自定义intercept
            .retryOnConnectionFailure(true)
            //重试intercept ,最大重试10次
            .addInterceptor(new RetryInterceptor(10))
            //设置超时时间
            .connectTimeout(30, TimeUnit.SECONDS)
            .writeTimeout(30, TimeUnit.SECONDS)
            .readTimeout(30, TimeUnit.SECONDS)
            .build();
            
            
            

     /**
     * 自定义的,重试N次的拦截器
     * 通过:addInterceptor 设置
     */
    public static class RetryInterceptor implements Interceptor {
        public int maxRetry;//最大重试次数
        private int retryNum = 0;//假如设置为3次重试的话,则最大可能请求4次(默认1次+3次重试)
        public RetryInterceptor(int maxRetry) {
            this.maxRetry = maxRetry;
        }
        @Override
        public Response intercept(@NonNull Chain chain) throws IOException {
            Request  request  = chain.request();
            Response response = chain.proceed(request);
            Log.i("Retry","num:"+retryNum);
            while (!response.isSuccessful() && retryNum < maxRetry) {
                retryNum++;
                Log.i("Retry","num:"+retryNum);
                response = chain.proceed(request);
            }
            return response;
        }
    }
    

3、创建请求接口interface


    public interface RetrofitApiImpl{
        @Headers({
                "Cache-Control: max-age=640000",
                "User-Agent: Retrofit-Sample-App"
        })
        @POST("audit/home/get-home")
        Call<TestVo>  getHome(@Body HashMap<String,String> map);

        //表单形式上传
        @FormUrlEncoded
        @POST("loanmall/activity/get-list")
        Call<TestVo>  getHome1(@Field("first_name") String first,@Field("second_name") String second);

        //上传文件类型
        @Multipart
        @PUT("common/image/post-upload")
        Call<TestVo>  updatePhoto(@Part("file\"; filename=hahaha\"") RequestBody photo,@Part("dir") String dir,@Part("rule") String rule);

        @POST("common/image/post-upload")
        Call<TestVo>  updatePhoto1(@Body MultipartBody multipartBody);

    }

4、发起请求

4.1 发起普通post

    //创建请求类
    RetrofitApiImpl retrofitApi = retrofit.create(RetrofitApiImpl.class);
    //调用接口
    Call<TestVo> call = retrofitApi.getHome(new HashMap<String, String>());
    //发起请求
    call.enqueue(new Callback<TestVo>() {
        @Override
        public void onResponse(Call<TestVo> call, Response<TestVo> response) {
            
        }

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

        }
    });

4.2 发起file类型文件

    RetrofitApiImpl retrofitApi = retrofit.create(RetrofitApiImpl.class);
    //创建multpart类型
    MultipartBody.Builder builder = new MultipartBody.Builder();
    RequestBody requestBody = RequestBody.create(MediaType.parse("image/png"), file);
    builder.addFormDataPart("file", file.getName(), requestBody);
    builder.addFormDataPart("dir", "user");
    int width = AbDisplayUtil.dip2px(70);
    builder.addFormDataPart("rule", width+"x"+width+"_c");
    builder.setType(MultipartBody.FORM);
    MultipartBody multipartBody = builder.build();
    //发起请求
    Call<TestVo> call = retrofitApi.updatePhoto1(multipartBody);
    call.enqueue(new Callback<TestVo>() {
        @Override
        public void onResponse(Call<TestVo> call, Response<TestVo> response) {
            
        }

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

        }
    });

相关文章

网友评论

      本文标题:Retrofit 源码解析-1、基本使用.md

      本文链接:https://www.haomeiwen.com/subject/dtwluktx.html