2016-09-29 53 views
0

我試圖發送以下JSON:發送整數數組作爲凌空的PARAMS的值返回400代碼

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

使用,當我試圖發送一個哈希表與此代碼我沒有problemst String作爲鍵和值,但是在這種情況下,當值應爲整數數組服務器不承認它是這樣和我返回代碼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); 
+0

如果請求成功收到,請嘗試在服務器端打印值。我們無法確定哪些代碼會導致該錯誤。 – Enzokie

回答

0

使用第二種方法,在去除

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

的伎倆。