1 php post android httprequest android-volley
我正在制作一个需要将 Post 请求发送到我的服务器的 android 应用程序,并且真的可以使用一些帮助!我一直在尝试使用 android Volley 发出这些请求。我在这里阅读了很多相关问题以及关于 android Volley 的各种文档来源,但是当我设法提出请求时,我不可能在服务器端以正确的方式接收发布的数据,我也不知道我做错了什么......我试过用stringRequest覆盖getParams()和自定义JsonObjectRequest并将我的数据作为参数。我在服务器端通过两个请求得到了不同的结果,但我仍然无法以正确的方式捕获它。
在我的服务器端,我的调试PHP 文件是这样的:
$content = file_get_contents("php://input");
$string = 'fileGetContents: ';
$json = json_decode($content, TRUE);
$string = 'fileGetContents: ';
$string .= $content;
$string .= ' -- json encoded: ';
$string .= json_encode($json);
$string .= ' -- Request Method: ';
$string .= $_SERVER['REQUEST_METHOD'];
$string .= ' -- $_REQUEST: ';
$string .= json_encode($_REQUEST);
$string .= ' -- $_POST: ';
$string .= json_encode($_POST);
$string .= ' -- user: ';
$string .= json_encode($_POST["user"]);
$string .= ' -- $_GET: ';
$string .= json_encode($_GET);
$string .= ' -- $_FORM: ';
$string .= json_encode($_FORM);
$array["ans"] = $string;
echo json_encode($array);
Run Code Online (Sandbox Code Playgroud)
由于我得到的响应始终为空,因此我也尝试将我的请求发送到http://httpbin.org/post,这为我提供了有趣的信息。
因此,对于我这样制作的第一个stringRequest:
RequestQueue requestQueue = Volley.newRequestQueue(this);
StringRequest stringRequest = new StringRequest(Request.Method.POST, "myServer.com/postRequest.php",
new Response.Listener<String>() {
@Override
public void onResponse(String response) {
displayTheResponse(response);
}
},
new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(RegisterActivity.this,error.toString(),Toast.LENGTH_LONG).show();
}
}){
@Override
protected Map<String,String> getParams(){
Map<String,String> params = new HashMap<String, String>();
params.put("user", "test");
params.put("pass", "passtest");
return params;
}
};
requestQueue.add(stringRequest);
Run Code Online (Sandbox Code Playgroud)
我从我的服务器得到这个答案:
{"ans":"fileGetContents: -- json encoded: null -- Request Method: GET -- $_REQUEST: [] -- $_POST: [] -- user: null -- $_GET: []"}
Run Code Online (Sandbox Code Playgroud)
从 httpbin.org 我得到:
{ "args": {},
"data": "",
"files": {},
"form": { "pass": "passtest", "user": "test" },
"headers": { "Accept-Encoding": "gzip", "Content-Length": "24", "Content-Type": "application/x-www-form-urlencoded; charset=UTF-8", "Host": "httpbin.org", "User-Agent": "Dalvik/2.1.0 (Linux; U; Android 7.1; Android SDK built for x86 Build/NPF26K)" },
"json": null,
"origin": "104.221.22.144",
"url": "http://httpbin.org/post"
}
Run Code Online (Sandbox Code Playgroud)
我可以看到信息实际上是发送的,但不是作为 POST 数据接收的,而是作为表单数据接收的,我真的不知道它是什么或如何从 PHP 接收它......
然后在我的第二个JsonObjectRequest中是这样的:
Map<String, String> jsonParams = new HashMap<String, String>();
jsonParams.put("user", "test");
JsonObjectRequest myRequest = new JsonObjectRequest(
Request.Method.POST,
"myServer.com/postTest.php",
new JSONObject(jsonParams),
new Response.Listener<JSONObject>() {
@Override
public void onResponse(JSONObject response) {
try {
displayResponse(response.toString(4));
} catch (JSONException e) {
e.printStackTrace();
}
},
new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(LogInActivity.this, "Error "+error.getMessage(), Toast.LENGTH_LONG).show();
fm.popBackStack();
}
});
requestQueue.add(myRequest);
Run Code Online (Sandbox Code Playgroud)
从 httpbin.org 我得到:
{ "args": {},
"data": "{\"user\":\"test\"}",
"files": {},
"form": {},
"headers": { "Accept-Encoding": "gzip", "Content-Length": "15", "Content-Type": "application\/json; charset=utf-8", "Host": "httpbin.org", "User-Agent": "Dalvik\/2.1.0 (Linux; U; Android 7.1; Android SDK built for x86 Build\/NPF26K)" },
"json": { "user": "test" },
"origin": "104.221.22.144",
"url": "http:\/\/httpbin.org\/post"
}
Run Code Online (Sandbox Code Playgroud)
在这里我们看到,现在数据显示在“data”和“json”中而不是“form”中,但从我的服务器我仍然得到相同的空响应,所以我猜我的问题来自服务器端的 PHP 代码,我是使用。我还注意到“$_SERVER['REQUEST_METHOD']”正在返回“GET”。
我尝试了很多不同的方法来提出我的 Volley 请求,但我不知道还能做什么。我已经尝试创建一个辅助类、自定义 JsonObjectRequest、覆盖 getHeaders(),甚至使用 AppController 将请求添加到队列中......我想我对 Post 请求的工作方式没有足够的了解,我很新随着安卓开发。
我真的很感激任何帮助来理解我应该如何使用 Volley POST 方法在服务器端接收我的数据。非常感谢您的宝贵时间!
以下代码可用于在 android 中使用Volley 库发出POST请求。假设你在你的应用程序 build.gradle 文件中导入你的库:
dependencies{
....
implementation 'com.android.volley:volley:1.1.0'
.....
}
Run Code Online (Sandbox Code Playgroud)
下面的代码可以放在一个方法中作为一些例行任务来执行你的 POST 请求
String requestUrl = "http://myapi.com/api/postresource.php";
StringRequest stringRequest = new StringRequest(Request.Method.POST, requestUrl, new Response.Listener<String>() {
@Override
public void onResponse(String response) {
Log.e("Volley Result", ""+response); //the response contains the result from the server, a json string or any other object returned by your server
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
error.printStackTrace(); //log the error resulting from the request for diagnosis/debugging
}
}){
@Override
protected Map<String, String> getParams() throws AuthFailureError {
Map<String, String> postMap = new HashMap<>();
postMap.put("param1", "value1");
postMap.put("param2", value2);
//..... Add as many key value pairs in the map as necessary for your request
return postMap;
}
};
//make the request to your server as indicated in your request url
Volley.newRequestQueue(getContext()).add(stringRequest);
Run Code Online (Sandbox Code Playgroud)