当我尝试使用 Volley StringRequest 或 JsonObjectRequest 通过 REST API 获取数据时。我总是收到 400 错误。它与邮递员一起工作正常。 Http请求方法为POST,Content-Type为application/x-www-form-urlencoded。我还检查了我的参数拼写,它对我来说看起来很好。我尝试过 StringRequest 和 JsonObjectRequest,结果是 E/Volley: [10283] BasicNetwork.performRequest: 意外的响应代码 400。下面是我的代码。我已附上屏幕截图。
Here is the new screenshot
StringRequest stringRequest = new StringRequest(Request.Method.POST, AppConfig.URL_LOGIN, new Response.Listener<String>() {
@Override
public void onResponse(String response) {
Log.d(TAG, response.toString());
viewHelper.hideDialog();
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
Log.d(TAG, error.toString());
viewHelper.hideDialog();
}
}){
@Override
protected Map<String, String> getParams() {
// Posting parameters to login url
Map<String, String> params = new HashMap<String, String>();
params.put("grant_type", "password");
params.put("username", email);
params.put("password", password);
return params;
}
@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");
return params;
}
@Override
public String getBodyContentType(){
return "application/x-www-form-urlencoded";
}
};
stringRequest.setRetryPolicy(new DefaultRetryPolicy(5000, DefaultRetryPolicy.DEFAULT_MAX_RETRIES, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
// Adding request to request queue
AppController.getInstance().addToRequestQueue(stringRequest, "Authenticating User");
我也尝试过齐射 JSONObjectRequest
Map<String, String> params = new HashMap<String, String>();
params.put("grant_type", "password");
params.put("username", email);
params.put("password", password);
JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.POST, AppConfig.URL_LOGIN, new JSONObject(params), new Response.Listener<JSONObject>() {
@Override
public void onResponse(JSONObject response) {
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
}
}){
@Override
public Map<String, String> getHeaders() throws AuthFailureError {
HashMap<String, String> headers = new HashMap<String, String>();
headers.put("Content-Type", "application/x-www-form-urlencoded");
return headers;
}
};
谁能帮我解决这个问题。