如何使用带有字符串集合的齐射发送POST请求

时间:2017-03-04 17:58:06

标签: android json android-volley

我想在body参数中发送带有字符串集合的POST请求。以下是我的请求格式示例 -

{
  "Emails": [
    "sample string 1",
    "sample string 2"
  ]
}

这是我正在尝试的 -

private void sendEmailRequest(final String email, String playId) {
    String url = "https://someurl";
    Map<String, String> postParam = new HashMap<String, String>();
    postParam.put("Emails", "["+ email +"]");

    JsonObjectRequest jsonRequest = new JsonObjectRequest(Request.Method.POST, url,new JSONObject(postParam),
            new Response.Listener<JSONObject>() {
                @Override
                public void onResponse(JSONObject response) {
                    Log.d(TAG, response.toString());              
                }
            }, new Response.ErrorListener() {
        @Override
        public void onErrorResponse(VolleyError error) {
            VolleyLog.d(TAG, "Error: " + error.getMessage());
        }
    }){
        /**
         * Passing some request headers
         * */
        @Override
        public Map<String, String> getHeaders() throws AuthFailureError {
            HashMap<String, String> headers = new HashMap<String, String>();
            headers.put("Authorization", "Bearer " + myToken);
            headers.put("Content-Type", "application/json; charset=utf-8");
            return headers;
        }
    };
    // Adding request to request queue
    AppController.getInstance().addToRequestQueue(jsonRequest, tagStringReq);
}

但它总是带有错误日志的 onErrorResponse 方法 -

E/Volley: [613] BasicNetwork.performRequest: Unexpected response code 500 for https://someurl

请给我一些建议,以解决这个问题。

1 个答案:

答案 0 :(得分:0)

JSON结构的等效Body请求:

 try {
    JSONObject body = new JSONObject();
    JSONArray array = new JSONArray();
    array.put("sample string 1");
    array.put("sample string 2");
    body.put("Emails", array.toString());

    new JsonObjectRequest(Request.Method.POST, url, body, listener, listener);
    ....
 } catch (JSONException e) {
     // ignores exception
 }

是这样的:

JsonObjectRequest

注意:使用headers.put("Content-Type", "application/json; charset=utf-8"); 时,无需添加内容类型。我在提到这一行:

config.action_controller.perform_caching