我正在尝试使用 Android Volley 库发送一个 JSON Post 请求,但我似乎没有正确获取 json 的正文,并且我在我的网络服务器上得到了未定义的正文参数。我需要 json 的参数主体是单个对象“name=someVal&comment=someOtherVal”。 name 和 comment 是键,someVal 和 someOtherVal 是值。
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);
我也在上面的代码中尝试过,但没有成功:
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 ... 之前将空值更改为
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 - 使用 Android Volley 发送带有正文的 JSON 帖子,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37100355/