Android 如何使用截击和字符串集合发送POST请求
我想发送带有正文参数中字符串集合的POST请求。下面是我的请求格式示例-Android 如何使用截击和字符串集合发送POST请求,android,json,android-volley,Android,Json,Android Volley,我想发送带有正文参数中字符串集合的POST请求。下面是我的请求格式示例- { "Emails": [ "sample string 1", "sample string 2" ] } 这就是我正在尝试的- private void sendEmailRequest(final String email, String playId) { String url = "https://someurl"; Map<String, String> p
{
"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);
}
请给出解决此问题的建议。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");
headers.put("Content-Type", "application/json; charset=utf-8");