如何在android中使用volley从服务器获取json响应?

如何在android中使用volley从服务器获取json响应?,android,json,android-volley,Android,Json,Android Volley,我有一个登录活动,它接收电子邮件和密码,并以这种格式返回令牌 { "token":"your_token_here" } 我已经实现了post请求,它可以正常工作。在日志上我可以看到它。我的问题是如何将其作为json对象读取并保存到共享首选项中?如果登录不正确,我也会有其他响应,但它们不是状态码。 例如: { "non_field_errors":"credentials not provided" } 如何获得这些响应,以便在对话框中显示它们。使用volley的JsonObject

我有一个登录活动,它接收电子邮件和密码,并以这种格式返回令牌

{
"token":"your_token_here"    
}
我已经实现了post请求,它可以正常工作。在日志上我可以看到它。我的问题是如何将其作为json对象读取并保存到共享首选项中?如果登录不正确,我也会有其他响应,但它们不是状态码。 例如:

{
"non_field_errors":"credentials not provided"
}

如何获得这些响应,以便在对话框中显示它们。

使用volley的
JsonObjectRequest

RequestQueue.add(new JsonObjectRequest(
    Request.Method.POST,
    "your url",
    null, // the request body, which is a JsonObject
    new Response.Listener<JSONObject>() {
      @Override public void onResponse(JSONObject response) {
          // ok, do your job
      }
    },
    new Response.ErrorListener() {
      @Override public void onErrorResponse(VolleyError error) {
          // fail, you may need to get the error response body if the server return http status code >= 400 when request fail
      }
    }
));
RequestQueue.add(新的JSONObject请求(
Request.Method.POST,
“您的url”,
null,//请求主体,它是JsonObject
新的Response.Listener(){
@重写公共void onResponse(JSONObject响应){
//好的,做好你的工作
}
},
新的Response.ErrorListener(){
@覆盖公共无效onErrorResponse(截击错误){
//失败,如果请求失败时服务器返回http状态代码>=400,则可能需要获取错误响应正文
}
}
));
如果您正在使用POST

JSONObject obj = new JSONObject();
obj.put("key","value"); // Request parameters to be send with post request
RequestQueue.add(new JsonObjectRequest(
    Request.Method.POST,
    "url",
    obj , // the request body, which is a JsonObject otherwise null
    new Response.Listener<JSONObject>() {
      @Override public void onResponse(JSONObject response) {

String token = response.optString("token");
      }
    },
    new Response.ErrorListener() {
      @Override public void onErrorResponse(VolleyError error) {

// Handle error here
      }
    }
));
JSONObject obj=新的JSONObject();
对象放置(“键”、“值”);//与post请求一起发送的请求参数
添加(新的JsonObjectRequest(
Request.Method.POST,
“网址”,
obj,//请求主体,它是JsonObject,否则为null
新的Response.Listener(){
@重写公共void onResponse(JSONObject响应){
字符串标记=response.optString(“标记”);
}
},
新的Response.ErrorListener(){
@覆盖公共无效onErrorResponse(截击错误){
//在这里处理错误
}
}
));

这可能会有帮助,谢谢你,这正是我要找的。我已经在使用字符串请求进行发布。现在,当我在这里得到一个响应时,
public void onResponse(String response){}
我如何得到我要寻找的令牌?只需使用
JsonObject json=new JsonObject(response)
,但无论如何都应该使用JsonObjectRequest方法。