反序列化时改进抛出异常的时间

时间:2018-03-18 06:39:32

标签: android retrofit2 android-architecture-components

我正在努力学习改造。我需要通过改造来处理反序列化错误。当任何关键数据类型不匹配时,改装抛出超时异常。

//改造初始化

  Retrofit retrofit= new Retrofit.Builder()
            .baseUrl(ConstantUtils.BASE_URL)
            .client(getOkHttpClient())
            .addConverterFactory(GsonConverterFactory.create(getGson()))
            .addCallAdapterFactory(new LiveDataCallAdapterFactory())
            .build()
            .create(CustomRetrofit.class);

 private Gson getGson() {
        return new GsonBuilder()
                .setExclusionStrategies(new GsonFieldExclusionStrategy())
                .setLenient()
                .create();
    }
private OkHttpClient getOkHttpClient() {
    HttpLoggingInterceptor interceptor = new HttpLoggingInterceptor(message -> Timber.i(message));
    interceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
    return new OkHttpClient.Builder().addInterceptor(interceptor).build();
}

添加CallAdapter

    public class LiveDataCallAdapter<R> implements CallAdapter<R, LiveData<ApiResponse<R>>> {
    private final Type responseType;

    LiveDataCallAdapter(Type responseType) {
        this.responseType = responseType;
    }

    @Override
    public Type responseType() {
        return responseType;
    }

    @Override
    public LiveData<ApiResponse<R>> adapt(@NonNull Call<R> call) {
        return new LiveData<ApiResponse<R>>() {
            AtomicBoolean started = new AtomicBoolean(false);

            @Override
            protected void onActive() {
                super.onActive();
                Timber.d("Live Data Call Adapter Called");
                if (started.compareAndSet(false, true)) {
                    call.enqueue(new Callback<R>() {
                        @Override
                        public void onResponse(@NonNull Call<R> call, @NonNull Response<R> response) {
                            postValue(new ApiResponse<>(response));
                        }

                        @Override
                        public void onFailure(@NonNull Call<R> call, @NonNull Throwable throwable) {
                            postValue(new ApiResponse<R>(throwable));
                        }
                    });
                }
            }
        };
    }
}

Json String

`{
  "sessionID": "201803181521354596165495",
  "name": "Umesh  Saraswat",
  "firstName": "Umesh - MRN:251729",
  "isCorporate": "",
  "access_token": "99f52c9aaba84283fa4b3581f17f3d10",
  "session_timeout": 86400,
  "lastlogin": "16-Mar-2018 11:17 AM",
  "eWellnessPackage": "[]",
  "eWellnessPackageStatus": 0,
  "customerReferralCode": "US305691",
  "cart_order_data": null
}`

模型类

 public class LoginAndRegistrationResponse {
    @SerializedName("sessionID")
    private String sessionId;
    private String name;
    private String firstName;
    @SerializedName("access_token")
    private String accessToken;
    @SerializedName("lastlogin")
    private String lastLoginDateAndTime;
    private Integer eWellnessPackageStatus;
    private String customerReferralCode;
    private String status;
    private Integer id;
    @SerializedName("msg")
    private String message;;
}

当我使用上面的模型时。但是当我将“访问令牌”更改为Integer然后改进抛出Timeout异常时。现在我很困惑,由于低互联网连接或反序列化Json,超时出现异常。

1 个答案:

答案 0 :(得分:-1)

我不太确定为什么要给TimeoutException。也许尝试使用以下方法增加超时:

@Provides
fun provideHttpClient(): OkHttpClient {
    val builder = OkHttpClient.Builder()

    builder.connectTimeout(60, TimeUnit.SECONDS)
    builder.readTimeout(60, TimeUnit.SECONDS)
    builder.writeTimeout(60, TimeUnit.SECONDS)

    return builder.build()
}

但正如Santanu所指出的那样,JSON结构将access_token作为String返回,而accessTokenint则不会直接