请阅读我在几个小时前提出的这个问题: How is it possible that POST API working in Postman but not the retrofit?
实际上,从 Retrofit 响应中,我从 ResponseBody 对象中获取了字符串格式的响应。
解释:我的状态码是200,成功,但是从响应正文来看,它只是字符串。如何从该字符串中获取所有数据?
登录成功后,我在 onResponse 中收到 String。我已经将用户凭据发送到此 APi,并且在 API 响应中,我收到了此字符串。
可能有一些与base64关系的编码解码。
最佳答案
public class LoginModel {
@SerializedName("body")
private Body body;
public Body getBody() {
return body;
}
public static class Body {
@SerializedName("userPwd")
private String userpwd;
@SerializedName("prodId")
private int prodid;
@SerializedName("emailId")
private String emailid;
@SerializedName("customerId")
private int customerid;
public String getUserpwd() {
return userpwd;
}
public int getProdid() {
return prodid;
}
public String getEmailid() {
return emailid;
}
public int getCustomerid() {
return customerid;
}
}
}
现在,如果您关注了 this answer你retrofit
界面是这样的
@Headers("Content-Type: application/json")
@POST("login/desktop/user")
Call<ResponseBody> getToken(@Body HashMap<String, HashMap<String, Object>> data);
修改为
@Headers("Content-Type: application/json")
@POST("login/desktop/user")
Call<LoginModel> getToken(@Body HashMap<String, HashMap<String, Object>> data); // change here
现在您可以在 onResponse()
中获取数据像这样
LoginModel loginData = response.body();
String pswd = loginData.getBody().getUserpwd();
PS = 如果您可以更改响应,我建议您更改 var body
从对诸如 data
之类的其他内容的回复.
SerializedName
用于POJO
类(class)并不重要,read more about them here
希望这会有所帮助!
关于java - 如何从登录API改造成功的字符串格式获取数据?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60338238/