Android Volley给出客户端错误代码400

时间:2018-11-13 14:30:16

标签: android api model-view-controller android-volley

我正在尝试发出POST请求以从Web API(由asp.net mvc编写)中获取令牌,并且它可以在Postman中工作(我获得了有效的JSON对象),但未使用Volley。使用以下代码:

  String url = "https://branj.ir/Token";

    Response.Listener<String> listener= new Response.Listener<String>() {
      @Override
      public void onResponse(String jsonResult) {

        Log.i(G.Tag, "volley result: " + jsonResult);
      }
    };
    Response.ErrorListener errorListener=   new Response.ErrorListener() {
      @Override
      public void onErrorResponse(VolleyError error) {

        error.printStackTrace();
        Log.d(G.Tag, "Error: " + error
          + "\nStatus Code " + error.networkResponse.statusCode
          + "\nCause " + error.getCause()
          + "\nmessage" + error.getMessage());
      }
    };

    StringRequest   request = new StringRequest  (
      Request.Method.POST,
      url,
      listener,
      errorListener

    )
 {
      @Override
      public Map<String, String> getHeaders() throws AuthFailureError {
        Map<String,String> params = new HashMap<String, String>();
        params.put("Content-Type","application/x-www-form-urlencoded");
        params.put("Accept", "application/json");
        return params;
      } }
 ;

logcat是:

 BasicNetwork.performRequest: Unexpected response code 400 for https://branj.ir/Token
11-13 16:55:59.608 21200-21200/ir.branj.app.wideidea.ir.branj D/Branj: Error: com.android.volley.ClientError
    Status Code 400
    Cause null
    messagenull

2 个答案:

答案 0 :(得分:1)

我按如下所示更改了应用程序代码,问题得到解决

 public static void Token(final String username, final String password) {

    String url = BASE_URL + "Token";

    Response.Listener<String> listener= new Response.Listener<String>() {
      @Override
      public void onResponse(String jsonResult) {

        Log.i(G.Tag, "volley result: " + jsonResult);
      }
    };
    Response.ErrorListener errorListener=   new Response.ErrorListener() {
      @Override
      public void onErrorResponse(VolleyError error) {
        error.printStackTrace();
        Log.d(G.Tag, "Error: " + error
          + "\nStatus Code " + error.networkResponse.statusCode
          + "\nCause " + error.getCause()
          + "\nnetworkResponse " + error.networkResponse.data.toString()
          + "\nmessage" + error.getMessage());
      }
    };

    StringRequest   request = new StringRequest  (
      Request.Method.POST,
      url,
      listener,
      errorListener
    )
    {
      @Override
      public Map<String, String> getParams() throws AuthFailureError {
        Map<String,String> params = new HashMap<>();
        params.put("username", username);
        params.put("password", password);
        params.put("grant_type", "password");
        return params;
      }
    } ;
    G.getInstance().addToRequestQueue(request);
  }

答案 1 :(得分:0)

{     “错误”:“ unsupported_grant_type” } 当我在邮递员上使用您的请求时,我收到错误消息,因为排球的身体不正确。