Retrofit 使用技巧

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/cuizehui123/article/details/79980949

Retrofit 使用技巧

  1. 创建工厂类
    public class RetrofitFactory {
        private static String baseUrl = "BaseURL/";

        private static Retrofit GsonRetrofit = new Retrofit.Builder()
                .baseUrl(baseUrl)

                //TOdo 添加转换器配置
                .addConverterFactory(GsonConverterFactory.create(GsonFactory.getgson()))
                .build();


        //解析返回的字符串
        public static LogInService getStringService() {
            LogInService service = GsonRetrofit.create(LogInService.class);
            return service;
        }


    }
     //retrofit底层用的okHttp,所以设置超时还需要okHttp
     //然后设置5秒超时
     //其中DEFAULT_TIMEOUT是我这边定义的一个常量
     //TimeUnit为java.util.concurrent包下的时间单位
     //TimeUnit.SECONDS这里为秒的单位
     OkHttpClient client = new OkHttpClient.Builder()
        .connectTimeout(DEFAULT_TIMEOUT, TimeUnit.SECONDS)
          .writeTimeout(DEFAULT_TIMEOUT, TimeUnit.SECONDS)
           .readTimeout(DEFAULT_TIMEOUT, TimeUnit.SECONDS)
                            .build();

      //构建Retrofit对象
      //然后将刚才设置好的okHttp对象,通过retrofit.client()方法 设置到retrofit中去
        retrofit = new Retrofit.Builder().baseUrl(baseUrl)
        .addConverterFactory(GsonConverterFactory.create()).client(client).build();    
  1. 通过泛型和注解方式配置参数


    public interface LogInService {
        @GET("/auth/login")
        Call<LogInRequestBean> login(@Query("mail") String mail,
                                     @Query("secret") String secret,
                                     @Query("device") String device);

        @GET("/auth/check")
        Call<CheckBean> check(@Query("mail") String mail);

        @GET("/auth/register")
        Call<LogInRequestBean> register(@Query("mail") String mail,
                                        @Query("secret") String secret,
                                        @Query("code") String code,
                                        @Query("device") String device);

        @GET("/auth/refresh")
        Call<LogInRequestBean> refresh(@Query("mail") String mail,
                                       @Query("refresh_token") String refresh_token,
                                       @Query("device") String device);

    }
  1. 生成转换后的bean 使用gsonformat(必要值可定义枚举)
    4.创建requestManager统一处理网络请求
    public class RequestManager {

    /**
     * 重置密码
     *
     * @param email
     * @param password
     * @param deviceID
     */
    public static void register(String email, String password, String code, String deviceID) {
        Call<LogInRequestBean> call = RetrofitFactory.getStringService().register(email, password, code, deviceID);
        if (call != null) {
            call.enqueue(new Callback<LogInRequestBean>() {
                @Override
                public void onResponse(Call<LogInRequestBean> call, Response<LogInRequestBean> response) {
                    if (response.code() == 200) {
                        //TODO 记录当前用户类型
                        //todo 记录"accessToken": "string", "expiresIn": 0,"refreshToken": "string",
                        LogInRequestBean logInRequestBean = response.body();
                        //todo 登陆成功
                        EventBus.getDefault().post(new CTLoginEvent(CTEvent.TYPE_LOGIN, true, CTLoginEvent.REASON_NONE));

                    }
                    //todo 登陆失败
                    else {
                        EventBus.getDefault().post(new CTLoginEvent(CTEvent.TYPE_LOGIN, false, CTLoginEvent.REASON_INVALID_PARAM));

                    }


                }

                @Override
                public void onFailure(Call<LogInRequestBean> call, Throwable t) {
                    //todo 网络失败
                }
            });
        }
    }
}

表单提交:

@FormUrlEncoded
    @POST("/oauth/refresh")
    Call<LogInRequestBean> refreshToken(@Header("Authorization") String authorization,
                                        @Field("username") String username,
                                        @Field("refresh_token") String refreshToken,
                                        @Field("grant_type") String grantType);
  1. 处理逻辑此处应特别注意,不应该在manager中拆开response,只需将response传递给请求方即可。
  2. 和EventBus结合即可将对象在回传事件时传递给请求调起方

baseurl更改为动态:

public class RetrofitFactory {
    private static Gson gson = new GsonBuilder()
            .setDateFormat("yyyy-MM-dd hh:mm:ss")
            .create();
    private static String baseUrl;

    public static boolean setBaseUrl(String url) {
        HttpUrl httpUrl = HttpUrl.parse(url);
        if (httpUrl == null) {
            return false;
        }
        baseUrl = url;
        return true;
    }

    //解析返回的字符串
    public static Authentication getAuthenticationService() {
        Retrofit GsonRetrofit = new Retrofit.Builder()
                .baseUrl(baseUrl)
                .addConverterFactory(GsonConverterFactory.create(gson))
                .build();
        Authentication authenticationService = GsonRetrofit.create(Authentication.class);
        return authenticationService;
    }
}

判定一次请求正在进行中则不发起第二次请求:

public static void login(String username, String password, String terminalSwVersion) {
        if (sIsLogin) {
            return;
        }
        sIsLogin = true;
        Call<LoginRequestBean> call = RetrofitFactory.getAuthenticationService().login(xxxxxxx, username, Utils.getMD5(password).toString(), "1a", "2b", "3c", "4d", "sdk-" + terminalSwVersion);
        call.enqueue(new Callback<LoginRequestBean>() {
            @Override
            public void onResponse(Call<LoginRequestBean> call, Response<LoginRequestBean> response) {
                switch (response.code()) {
                    case 401:
                        EventBus.getDefault().post(new LoginEvent(false, 401, response.body()));
                        break;
                    case 200:
                        EventBus.getDefault().post(new LoginEvent(true, 200, response.body()));
                        break;
                    case 400:
                        EventBus.getDefault().post(new LoginEvent(false, 400, null));
                        break;
                    default:
                        EventBus.getDefault().post(new LoginEvent(false, response.code(), null));
                        break;
                }
                sIsLogin = false;
            }

            @Override
            public void onFailure(Call<LoginRequestBean> call, Throwable t) {
                t.printStackTrace();
                sIsLogin = false;
                EventBus.getDefault().post(new LoginEvent(false, LoginEvent.NETWORK_TIME_OUT, null));
            }
        });
    }
阅读更多

没有更多推荐了,返回首页