[英]How can I handle the response from the retrofit (Here my response not showing the data, it only shows the code and status of the call)
我正在使用改造從我的 android 應用程序進行 api 調用。 但是響應顯示狀態代碼 200 和 ok 消息。 但是調用的數據是由 httpClient 返回的。 那么我該如何處理我的呼叫的響應數據。 這里的響應將是
請求有效載荷
/okhttp.OkHttpClient: {"data":{"email":"foobar@gmail.com","password":"PASSWoRD121"}}
回復:
okhttp.OkHttpClient: {"data":"我的令牌"}
這是我打印的回復不會給出上述數據。 如何將令牌設置為下一次調用?
響應====響應{protocol=http/1.1, code=200, message=OK, url="http://tyhgfhfty/hfhgfh/"}
ApiService.java
@POST(ApiConstant.Login)
Call<User> LoginRequest(@Body JsonObject user);
登錄活動:
ApiService userLoginService = retrofit.create(ApiService.class);
final JsonObject jo = new JsonObject();
jo.addProperty(ApiParameter.EMAIL, email);
jo.addProperty(ApiParameter.PASSWORD, password);
final JsonObject jobj = new JsonObject();
jobj.add(ApiParameter.DATA, jo);
userLoginService.userLogin(jobj).enqueue(new Callback<LoginRequest>(){
@Override
public void onResponse(Call<LoginRequest> call, Response<LoginRequest>response) {
System.out.println(("response ===" + response));
登錄請求.java
public class LoginRequest {
private String email;
private String password;
public void setEmail(String email) {
this.email = email;
}
public void setPassword(String password) {
this.password = password;
}
public String getEmail() {
return email;
}
public String getPassword() {
return password;
}
}
當你有一個 json 響應時,你可以分析或假設json 等於一個 class ,因為 Gson 轉換。
在那個 json 中包含一個關鍵data
和一個字符串my tokken
。
在類改造響應中,它是相等的名為data
變量,它來自類型為String
關鍵data
,為什么是 String ? 因為值我的令牌是該 json 中的一個字符串。 因此,您可以稍后從data
getter setter 中檢索該值。 像getData();
因此,對於{"data":"my tokken"}
,您的LoginResponse
類僅包含一個字段,該字段是類型為String
data
和 setter getter。
當你有回應{"data": {"user": "xxxx", "email": "foobar@gmail.com", "lastname": "yyyyy", "gender": 1, "deviceType": 1}"}
. 你可以分析包含一個 json 對象的關鍵data
;一個 json 等於一個 class 。
所以,你需要一個類來獲取它的價值。 假設它是User
類。
public class User {
private String user; // because the value of user in json is String
private String email;
private String lastname;
private Int gender; // because the value of gender in json is Int
private Int deviceType;
// the setter getter here
}
最后,處理改造調用的類響應。 假設UserResponse
應該是這樣的
public class UserResponse {
private User data;
// the variable is named data because it should be the same to the json key and the type of the variable is class `User`. Remember about the bolded text
// (variable named same is not a must, if different, you can use `SerializedName` annotation, you can read about it later)
// the setter getter here
}
我用簡單的方式解釋了我的想法,希望你能理解。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.