2017-03-04 132 views
0

我想发送POST请求与正文参数中的字符串集合。下面是我的要求的采样格式 -如何使用volley发送POST请求与字符串集合

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

这里就是我trying-

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 

请给我建议克服这个问题。

回答

0

您的JSON结构的相应机构的要求:

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

是这样的:

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");