Retrofit 2 - 获取错误对象JSON(同一请求的POJO很少)

时间:2015-10-15 14:59:01

标签: java android json retrofit

我有像

这样的简单请求
  /*LOGIN*/
        @FormUrlEncoded
        @POST("v1/user/login") //your login function in your api
        Call<LoginResponce> login(@Field("identity") String identity,
               @Field("password") String password);

如果http代码200

,则返回LoginResponceobject
{"token":"itwbwKay7iUIOgT-GqnYeS_IXdjJi","user_id":17}

或错误Json,如果出现问题则描述确切的错误

{"status":4,"description":"user provided token expired"}

如何在响应中处理错误状态?

我尝试了这个,但它没有在原始文本中看到JSON(不能正常工作)。并不是一个好的解决方案。

mCallLoginResponse.enqueue(new Callback<LoginResponce>() {
                @Override
                public void onResponse(Response<LoginResponce> response, Retrofit retrofit) {
                    if (response.isSuccess()) {

                        registerWithToken(response.body().getToken());
                    } else { //some error in responce

                        Gson gson = new GsonBuilder().create();
                        ApiError mApiError = gson.fromJson(response.raw().body().toString(), 
ApiError.class); //Exception here - no JSON in String
                            //todo error handling
                        }
                    }

1 个答案:

答案 0 :(得分:3)

要在遇到错误代码时访问响应正文,请使用errorBody()代替body()。另外,string上有一个ResponseBody方法,您应该使用toString代替Gson gson = new GsonBuilder().create(); try { ApiError mApiError = gson.fromJson(response.errorBody().string(),ApiError.class); } catch (IOException e) { // handle failure to read error }

while ($row = mysqli_fetch_array($result) && strlen($row['url_key']) > 4)
{
....
}
相关问题