java - 如何处理改造的响应(这里我的响应没有显示数据,它只显示调用的代码和状态)
问题描述
我正在使用改造从我的 android 应用程序中进行 api 调用。但响应显示状态代码 200 和 ok 消息。但是调用的数据是由 httpClient 返回的。那么如何处理我的呼叫的响应数据。这里的响应将是
请求有效载荷
/okhttp.OkHttpClient: {"data":{"email":"foobar@gmail.com","password":"PASSWoRD121"}}
回复:
okhttp.OkHttpClient: {"数据":"我的令牌"}
这是我打印出来的回复,不会给出上述数据。如何将令牌设置为我的下一个电话?
响应 ==== 响应{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 中包含一个 keydata
和一个 string my tokken
。
data
在类改造响应中,它是来自 keydata
和 type的相等变量String
,为什么是 String?因为值我的令牌是那个 json 中的一个字符串。因此,您可以稍后从data
getter setter 中检索该值。像getData();
因此,对于 {"data":"my tokken"}
,您的LoginResponse
类仅包含一个data
具有 typeString
和 setter getter 的字段。
当你有回应时{"data": {"user": "xxxx", "email": "foobar@gmail.com", "lastname": "yyyyy", "gender": 1, "deviceType": 1}"}
。您可以分析该键data
包含一个json对象;一个 json 等于一个类。
所以,你需要一个类来获得它的价值。让我们说它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
}
我以简单的方式解释了我的想法,希望您能理解。
推荐阅读
- javascript - 尝试对数据进行分页时出现无限循环
- node.js - 仅当键不为空时才包含续集
- kubernetes - 未为 ml-pipeline pod 指定配置 DBConfig.ExtraParams
- javascript - 将事件侦听器添加到页面 Chrome 扩展上的按钮
- amazon-web-services - 尝试更改 Spark 数据框中多列中的多个值时,ASW Spark 作业超时
- javascript - React.js 状态在 console.log 之间发生巨大变化,而没有任何改变(在它已经正确更新之后)
- php - Oauth2 返回的图像 url 中断 imagecreatefrompng
- javascript - 如何使用柏树将多个元素的值存储在数组列表中的一个根元素下
- python - 如何使用 ruamel.yaml 包编辑 yaml 文件,而不更改文件的缩进?
- r - 突出显示两点之间的一段线(传单/R)