android - 使用 Android Volley 发送带有正文的 JSON 帖子

标签 android json post android-volley

我正在尝试使用 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/

相关文章:

android - 两个应用程序之间的数据共享

javascript - JSON.parse() 保持字符串编码

json - json字符串和解析后的json字符串的区别

javascript - 在ajax jquery中显示json响应,

database - ElasticSearch 异步发布

api - 被 SLM Monitor 加拿大邮政 api 拒绝

java - Android 完整图像,带有来自 php mysql 的 recyclerview、cardview 和 volley

android - 为什么我的程序崩溃?

android - ADT (Eclipse) 与 Android Studio : How much APK file size difference is normal?

java - 使用 API key 和 secret 连接到交易 API (Poloniex)