我正在尝试在 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 请求不起作用
Volley Post JsonObjectRequest 在使用 getHeader 和 getParams 时忽略参数
Volley 不发送带参数的 post 请求。
我尝试将 JsonObjectRequest 构造函数中的 JSONObject 设置为 null,然后重写并设置“getParams()”、“getBody()”和“getPostParams()”方法中的参数,但这些重写都不起作用我。另一个建议是使用一个额外的帮助程序类,它基本上创建一个自定义请求,但该修复对于我的需求来说有点太复杂了。如果归根结底,我会尽一切努力使其工作,但我希望有一个简单的原因来解释为什么我的代码was工作,然后只是stopped,也是一个简单的解决方案。