【发布时间】:2015-06-09 04:19:51
【问题描述】:
我正在尝试在 Volley JsonObjectRequest 中发送 POST 参数。最初,它对我有用,按照官方代码所说的在 JsonObjectRequest 的构造函数中传递包含参数的 JSONObject。然后突然之间它停止工作,我没有对以前工作的代码进行任何更改。服务器不再识别正在发送的任何 POST 参数。这是我的代码:
RequestQueue queue = Volley.newRequestQueue(this);
String url ="http://myserveraddress";
// POST parameters
Map<String, String> params = new HashMap<String, String>();
params.put("tag", "test");
JSONObject jsonObj = new JSONObject(params);
// Request a json response from the provided URL
JsonObjectRequest jsonObjRequest = new JsonObjectRequest
(Request.Method.POST, url, jsonObj, new Response.Listener<JSONObject>()
{
@Override
public void onResponse(JSONObject response)
{
Toast.makeText(getApplicationContext(), response.toString(), Toast.LENGTH_SHORT).show();
}
},
new Response.ErrorListener()
{
@Override
public void onErrorResponse(VolleyError error)
{
Toast.makeText(getApplicationContext(), error.toString(), Toast.LENGTH_SHORT).show();
}
});
// Add the request to the RequestQueue.
queue.add(jsonObjRequest);
这是服务器上的简单测试器 PHP 代码:
$response = array("tag" => $_POST["tag"]);
echo json_encode($response);
我得到的回复是{"tag":null}
昨天,它运行良好,并回复{"tag":"test"}
我没有改变任何东西,但今天它不再起作用了。
在 Volley 源代码构造函数 javadoc 中,它说您可以在构造函数中传递 JSONObject 以在“@param jsonRequest”处发送 post 参数: https://android.googlesource.com/platform/frameworks/volley/+/master/src/main/java/com/android/volley/toolbox/JsonObjectRequest.java
/**
* 创建一个新请求。
* @param method 要使用的 HTTP 方法
* @param url 获取 JSON 的 URL
* @param jsonRequest 与请求一起发布的 {@link JSONObject}。允许为空并且
* 表示不会随请求一起发布任何参数。
我已阅读其他类似问题的帖子,但解决方案对我不起作用:
Volley JsonObjectRequest Post request not working
Volley Post JsonObjectRequest ignoring parameters while using getHeader and getParams
Volley not sending a post request with parameters.
我尝试将 JsonObjectRequest 构造函数中的 JSONObject 设置为 null,然后覆盖并设置“getParams()”、“getBody()”和“getPostParams()”方法中的参数,但这些都没有覆盖对我有用。另一个建议是使用一个额外的帮助类,它基本上创建了一个自定义请求,但是这个修复对于我的需要来说有点太复杂了。如果归根结底,我会做任何事情来使它工作,但我希望有一个简单的原因来解释为什么我的代码 工作,然后只是停止,也是一个简单的解决方案。
【问题讨论】:
-
你找到解决办法了吗?
-
@Dory 是的,我确实找到了一个简单的解决方案。它没有解决 JsonObjectRequest 的问题,我只是完全放弃了 JsonObjectRequest,因为解决方案是改用 Volley 的 StringRequest。在下面查看我的答案,看看我做了什么。
标签: android post android-volley jsonobject