使用Android Volley发送带有正文的JSON帖子 [英] Sending JSON Post with Body using Android Volley
问题描述
我正在尝试使用Android Volley库发送JSON Post请求,但是我似乎没有正确获取JSON的主体,并且在Web服务器上得到了未定义的主体参数.我需要json的参数主体为单个对象"name = someVal& comment = someOtherVal".名称和注释是键,someVal和someOtherVal是值.
I am trying to send a JSON Post request using Android Volley library but I dont seem to get the body of the json right and I get undefined body parameters on my web server. I need the json's parameters body to be a single object "name=someVal&comment=someOtherVal". name and comment are the keys and someVal and someOtherVal are the values.
String spreadsheetID = "1111111-11111N92RT9h-11111111111111111111111111111";
String url = "https://script.google.com/macros/s/" + spreadsheetID + "/exec";
// Instantiate the RequestQueue.
RequestQueue queue = Volley.newRequestQueue(this);
// Request a string response from the provided URL.
JsonObjectRequest jsonObjReq = new JsonObjectRequest(Request.Method.POST,
url, null,
new Response.Listener<JSONObject>() {
@Override
public void onResponse(JSONObject response) {
Log.d("JSONPost", response.toString());
//pDialog.hide();
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
VolleyLog.d("JSONPost", "Error: " + error.getMessage());
//pDialog.hide();
}
}) {
@Override
protected Map<String, String> getParams() {
Map<String, String> params = new HashMap<String, String>();
params.put("name=someVal&comment=someOtherVal");
//params.put("comment", "someOtherVal");
return params;
}
};
// Add the request to the RequestQueue.
queue.add(jsonObjReq);
}
我也在上面的代码中尝试过,但是没有运气:
I also tried this in the above code but no luck:
params.put("comment", "someOtherVal");
params.put("name", "someVal");
推荐答案
尝试放置
Map<String, String> params = new HashMap<String, String>();
params.put("comment", "someOtherVal");
params.put("name", "someVal");
在JsonObjectRequest jsonObjReq ...之前,并将null值更改为
before JsonObjectRequest jsonObjReq ... and change the null value by
new JsonObject(params)
因此您的代码将是
Map<String, String> params = new HashMap<String, String>();
params.put("comment", "someOtherVal");
params.put("name", "someVal");
JsonObjectRequest jsonObjReq = new JsonObjectRequest(Request.Method.POST,
url, new JsonObject(params),
new Response.Listener<JSONObject>() {
@Override
public void onResponse(JSONObject response) {
Log.d("JSONPost", response.toString());
//pDialog.hide();
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
VolleyLog.d("JSONPost", "Error: " + error.getMessage());
//pDialog.hide();
}
})
这篇关于使用Android Volley发送带有正文的JSON帖子的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!