【发布时间】:2015-09-23 17:02:45
【问题描述】:
我想在 Android 中发送一个简单的 POST 请求,其正文等于:
[
{
"value": 1
}
]
我尝试在 Android 中使用 Volley 库,这是我的代码:
// the jsonArray that I want to POST
String json = "[{\"value\": 1}]";
JSONArray jsonBody = null;
try {
jsonBody = new JSONArray(json);
} catch (JSONException e) {
e.printStackTrace();
}
final JSONArray finalJsonBody = jsonBody;
// starting the request
final RequestQueue queue = Volley.newRequestQueue(getApplicationContext());
JsonObjectRequest request =
new JsonObjectRequest(com.android.volley.Request.Method.POST,"https://...",null,
new Response.Listener<JSONObject>() {
@Override
public void onResponse(JSONObject response) {
Log.d("mytag", "Response is: " + response);}},
new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
Log.d("Mytag", "error");}}) {
@Override
protected Map<String,String> getParams() {
// the problem is here...
return (Map<String, String>) finalJsonBody;
}
@Override
public Map<String, String> getHeaders() throws AuthFailureError {
HashMap<String, String> params = new HashMap<String, String>();
// I put all my headers here like the following one :
params.put("Content-Type", "application/json");
return params;}};
queue.add(request);
问题在于 getParams 方法只接受一个 Map 对象,因为我想发送一个 JSONArray。所以,我不得不使用演员表,这会产生错误......
我不知道我该如何解决 谢谢
【问题讨论】:
-
阅读my asnwer here。但是,您的 json 是 JSONArray,而不是 JSONObject。
-
你能说得更清楚一点吗?我仍然无法对这个 jsonArray 进行编码...感谢您的理解
-
JSONObject jsonBody = new JSONObject("{\"value\": 1}"); JSONObject 以 { 开头并以 } 结尾。此外,您收到的错误信息是什么?如果可用,请发布它和任何 logcat 信息。
-
谢谢,我终于解决了这部分,因为我使用了 JSONArray。但是由于 getparams 方法,我得到了另一个错误...
-
请发布它和任何 logcat 信息(如果有)。此外,为 POST 正文参数覆盖 getBody 而不是 getParams
标签: android json request android-volley