将整数数组作为 volley 参数的值发送返回 400 代码



我正在尝试发送以下json:

{"communities" : [381, 382, 383, 384, 385]}

当我试图发送一个字符串作为键和值的哈希映射时,我没有问题,但在这种情况下,当值应该是整数数组时,服务器不识别它,并返回代码400:

JSONObject dataToPost = new JSONObject();
JSONArray jsa = new JSONArray();
jsa.put(381);
jsa.put(382);
jsa.put(383);
jsa.put(384);
jsa.put(385);
jsa.put(386);
try {
    dataToPost.put("communities", jsa);
} catch (JSONException e) {
    e.printStackTrace();
}
final JSONObject dataFinal = dataToPost;
Log.i("fdsfs", dataFinal.toString());
StringRequest postRequest = new StringRequest(Request.Method.POST, GlobalValues.registerSetCommunities,
        new Response.Listener<String>() {
            @Override
            public void onResponse(String response) {
                manageSuccessResponse(response);
            }
        },
        new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                manageErrorResponse(error);
            }
        }
) {
    @Override
    public byte[] getBody() {
        try {
            return dataFinal.toString().getBytes("utf-8");
        } catch (UnsupportedEncodingException e) {
            return null;
        }
    }
    @Override
    public Map<String, String> getHeaders() throws AuthFailureError {
        Map<String, String> headers = new HashMap<String, String>();
        headers.put("Content-Type", "application/x-www-form-urlencoded");
        headers.put("Authorization", "Bearer " + Credentials.getAuthToken(mContext));
        return headers;
    }
};
postRequest.setRetryPolicy(new DefaultRetryPolicy(
        GlobalValues.request_timeout,
        DefaultRetryPolicy.DEFAULT_MAX_RETRIES,
        DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
Volley.newRequestQueue(mContext).add(postRequest);

我尝试的另一种方法是JsonObjectRequest。下面是代码:

JsonObjectRequest request = new JsonObjectRequest(Request.Method.POST, GlobalValues.registerSetCommunities, dataFinal, new Response.Listener<JSONObject>() {
    @Override
    public void onResponse(JSONObject response) {
        Log.i("SENDMOVE", response.toString());
    }
}, new Response.ErrorListener() {
    @Override
    public void onErrorResponse(VolleyError error) {
        manageErrorResponse(error);
    }
}) {
    @Override
    public Map<String, String> getHeaders() throws AuthFailureError {
        Map<String, String> headers = new HashMap<String, String>();
        headers.put("cache-control", "no-cache");
        headers.put("Content-Type", "application/json");
        headers.put("Authorization", "Bearer " + Credentials.getAuthToken(mContext));
        return headers;
    }
};
request.setRetryPolicy(new DefaultRetryPolicy(
        GlobalValues.request_timeout,
        DefaultRetryPolicy.DEFAULT_MAX_RETRIES,
        DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
Volley.newRequestQueue(mContext).add(request);

使用第二种方法并删除

headers.put("Content-Type", "application/json");

最新更新