Volley 使用 POST 方法将 JSONObject 发送到服务器 [英] Volley send JSONObject to server with POST method
本文介绍了Volley 使用 POST 方法将 JSONObject 发送到服务器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想使用 volley 库将以下格式的 jsonobject 发送到服务器<强>{用户 ID":12,答案":{11":3,12":4,13":5}}
I want to send a jsonobject with below format to server by using volley library { "user_id": 12, "answers": { "11": 3, "12": 4, "13": 5 } }
JSONObject object = new JSONObject();
try {
object.put("user_id", user_id);
JSONObject answers = new JSONObject();
for (int i = 0; i < questions.size(); i++) {
JSONObject answer = new JSONObject();
answer.put(questions.get(i).getId(),questions.get(i).getAnswer());
answers.put("answers", answer);
object.put("answers", answer);
}
} catch (JSONException e) {
e.printStackTrace();
}
如果我想使用 StringRequest 我应该如何使用 POST 方法将这个 JsonObject 发送到服务器
If I want to use StringRequest how should I send this JsonObject to server by using POST method
推荐答案
您可以使用以下工作示例代码.我已经测试过了.希望这会有所帮助!
You can use the following working sample code. I have tested. Hope this helps!
try {
jsonBody = new JSONObject();
jsonBody.put("Title", "VolleyApp Android Demo");
jsonBody.put("Author", "BNK");
jsonBody.put("Date", "2015/08/26");
requestBody = jsonBody.toString();
StringRequest stringRequest = new StringRequest(1, url, new Response.Listener<String>() {
@Override
public void onResponse(String response) {
textView.setText(response);
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
textView.setText(error.toString());
}
}) {
@Override
public String getBodyContentType() {
return String.format("application/json; charset=utf-8");
}
@Override
public byte[] getBody() throws AuthFailureError {
try {
return requestBody == null ? null : requestBody.getBytes("utf-8");
} catch (UnsupportedEncodingException uee) {
VolleyLog.wtf("Unsupported Encoding while trying to get the bytes of %s using %s",
requestBody, "utf-8");
return null;
}
}
};
MySingleton.getInstance(this).addToRequestQueue(stringRequest);
} catch (JSONException e) {
e.printStackTrace();
}
更新:要根据您的要求创建 JSONObject,请使用以下内容:
UPDATE: To create JSONObject as your requirement, use the following:
JSONObject jsonObject = new JSONObject();
try {
jsonObject.put("11", 3);
jsonObject.put("12", 4);
jsonObject.put("13", 5);
JSONObject jsonObject2 = new JSONObject().put("answers", jsonObject);
jsonObject2.put("user_id", 12);
} catch (JSONException e) {
e.printStackTrace();
}
这篇关于Volley 使用 POST 方法将 JSONObject 发送到服务器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文