Dmi*_*din 5 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);
Run Code Online (Sandbox Code Playgroud)
如果http代码200,则返回LoginResponceobject
{"token":"itwbwKay7iUIOgT-GqnYeS_IXdjJi","user_id":17}
Run Code Online (Sandbox Code Playgroud)
或错误Json,如果出现问题则描述确切的错误
{"status":4,"description":"user provided token expired"}
Run Code Online (Sandbox Code Playgroud)
如何处理响应中的错误状态?
我试过这个,但它没有在原始文本中看到JSON(doens't工作).而且似乎不是很好的解决方案.
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
}
}
Run Code Online (Sandbox Code Playgroud)
To get access to the response body when you have an error code, use errorBody() instead of body(). Also, there is a string method on ResponseBody that you should use instead of toString.
Gson gson = new GsonBuilder().create();
try {
ApiError mApiError = gson.fromJson(response.errorBody().string(),ApiError.class);
} catch (IOException e) {
// handle failure to read error
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1646 次 |
| 最近记录: |