[英]Get token from Server Response in JSON
我通过Retrofit的帮助向服务器发送了发布请求,但是我希望在服务器发送回响应时从令牌中获取一个值。 这是我发送帖子请求和onSuccess的方式,我想接收令牌。 我的问题是我不知道如何从服务器响应中检索令牌。 请在这里帮助。
public void loginUser(String userName, String userPassword, Boolean userRememberMe) {
mAPIService.loginUser(userName, userPassword, userRememberMe).enqueue(new Callback<Login>() {
@Override
public void onResponse(Response<Login> response, Retrofit retrofit) {
if(response.isSuccess()) {
//save token here
Intent intent = new Intent(LoginActivity.this, ProfileActivity.class);
startActivity(intent);
}
}
@Override
public void onFailure(Throwable throwable) {
Log.e(TAG, "Unable to Login");
}
});
}
这是我从服务器得到的响应
{
"total": 0,
"data": {
"id": "348680c7-d46b-4adc-9be0-89a1d1a38566",
"username": "0242770336",
"name": "name",
"phoneNumber": "063546345",
"email": "number@gmail.com",
"dateOfBirth": null,
"image": null,
"gender": "",
"idTypeId": null,
"idType": null,
"idNumber": null,
"idExpiryDate": null,
"idVerified": false,
"cityId": null,
"city": null,
"residentialAddress": null,
"latitude": 0,
"longitude": 0,
"createdAt": "2017-08-14T17:45:16.24Z",
"role": {
"id": 2,
"name": "User",
"privileges": [
""
]
},
"token": "jNK_DGszYOMEpPOFoRGjuyJ5KX9kaJQKCl3cujlHoXklCS8Ij6b-QBmhv0jVwVC54KcNXkzyM62xpswqcjo9Ajf-n-rWzSaIoiYNglaXhtPspziZ0PcTKzTMAvw8si3A7BlcD98M-IjIxYjxieVYAPWVtcvomWi"
},
"message": "Login Successfull",
"success": true
}
这是我的登录模型
public class Login {
@SerializedName("userName")
@Expose
private String userName;
@SerializedName("password")
@Expose
private String password;
@SerializedName("rememberMe")
@Expose
private Boolean rememberMe;
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public Boolean getRememberMe() {
return rememberMe;
}
public void setRememberMe(Boolean rememberMe) {
this.rememberMe = rememberMe;
}
}
有两种方法。
方法1:使用JsonObject
mAPIService.loginUser(userName, userPassword, userRememberMe).enqueue(new Callback<JsonObject>() {
@Override
public void onResponse(Response<JsonObject> response, Retrofit retrofit) {
if(response.isSuccess()) {
try {
String token=response.body().get("data").get("token");
} catch (JSONException e) {
e.printStackTrace();
}
Intent intent = new Intent(LoginActivity.this,ProfileActivity.class);
startActivity(intent);
}
}
}
方法2:您可以使用http://pojo.sodhanalibrary.com/将您的回复转换为POJO。 现在将其添加到您的项目中,让我们将其命名为ResponseData.class并通过执行以下更改使用getter方法获取令牌
mAPIService.loginUser(userName, userPassword, userRememberMe).enqueue(new Callback<ResponseData>() {
@Override
public void onResponse(Response<ResponseData> response, Retrofit retrofit) {
if(response.isSuccess()) {
//save token here
String token =response.getData().getToken();
Intent intent = new Intent(LoginActivity.this, ProfileActivity.class);
startActivity(intent);
}
}
@Override
public void onFailure(Throwable throwable) {
Log.e(TAG, "Unable to Login");
}
});
将响应字符串转换为JSONObject
,然后再次获取数据的JSONObject
,在数据中您可以找到令牌对象。
JSONObject object = new JSONObject(response);
JSONObject dataObject = object.getJSONObject("data");
String token = dataObject.getString("token");
Log.i("TAG","token is "+token);
尝试这个。
使用optBoolean()
方法和optString()
方法
try {
JSONObject jsonObject = new JSONObject(response);
boolean success = jsonObject.optBoolean("success");
if (success) {
JSONObject data = jsonObject.getJSONObject("data");
String token = data.optString("token");
} else {
Log.e("message", "failure");
}
} catch (JSONException e) {
e.printStackTrace();
}
您可以使用Gson
将json
转换为Java POJO类。 但是,如果您只想获取令牌字段,则可以这样使用它:
public void onResponse(Response<Login> response, Retrofit retrofit) {
if(response.isSuccess()) {
try {
JSONObject ob = new JSONObject(response.body());
String token = ob.getJSONObject("data").getString("token");
} catch (JSONException e) {
e.printStackTrace();
}
Intent intent = new Intent(LoginActivity.this, ProfileActivity.class);
startActivity(intent);
}
}
为此,您需要首先了解该响应是Json格式的,因此需要首先从从服务器获取的响应中创建Json对象。 为了更好地理解https://www.androidhive.info/2012/01/android-json-parsing-tutorial/ http://www.json.org/以及获得该响应的代码。
try{
JSONObject jsonObject = new JSONObject(response);
String token = jsonObject.getJSONObject("data").getString("token");
}
catch(JSONException e){
e.printstacktrace();
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.