问题描述
我正在制作一个Android应用,该应用需要将Post请求发送到我的服务器,并且确实可以使用一些帮助!我一直在尝试使用Android Volley发出这些请求.我在这里已经阅读了许多相关的问题,以及有关android Volley的各种文档资料,但是由于我设法提出请求,因此我不可能在服务器端以正确的方式接收发布的数据,因此我一无所知我做错了什么...我尝试使用 stringRequest 覆盖 getParams()和自定义 JsonObjectRequest ,并将数据作为参数.我在两个请求的服务器端都得到了不同的结果,但是仍然无法以正确的方式捕获它.
I am making an android app that needs to send Post requests to my server and could really use some help!I've been trying to make these requests using android Volley. I've read a lot of related questions here and all kind of documenttion sources about android Volley but as I manage to make my requests, it's been impossible for me to receive the posted data the right way on server side and I have no clue about what I'm doing wrong...I've tried with stringRequest overriding getParams() and custom JsonObjectRequest with my data as a parameter. I get diferent results on server side with both requests but I'm still not able to catch it the right way.
在服务器端,我的调试 PHP文件如下所示:
On my server side my debug PHP file goes like this:
$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);
由于收到的响应始终为空,因此我也尝试将请求发送到 http://httpbin.org/post ,它为我提供了有趣的信息.
and as the response I get is always empty I've also tried sending my requests to http://httpbin.org/post which gives me interesting information.
因此,我将第一个 stringRequest 设置为:
So with the first stringRequest that I make like this:
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);
我从服务器上得到了这个答案:
I get this answer from my server:
{"ans":"fileGetContents: -- json encoded: null -- Request Method: GET -- $_REQUEST: [] -- $_POST: [] -- user: null -- $_GET: []"}
从httpbin.org我得到:
And from httpbin.org i get:
{ "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"
}
我可以看到信息实际上是发送的,但不是作为POST数据接收的,而是作为Form数据接收的,我实际上并不知道它是什么或如何从PHP接收它...
I can see that the information is actually sent but not received as POST data but as Form data which I don't really know what it is or how to receive it from PHP...
然后在我的第二个 JsonObjectRequest 中,如下所示:
Then in my second JsonObjectRequest that goes like this:
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);
从httpbin.org我得到:
From httpbin.org I get:
{ "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"
}
在这里我们看到数据现在显示在数据"和"json"中,而不是在窗体"中,但是从我的服务器上我仍然得到相同的空响应,所以我认为我的问题来自服务器端PHP代码我正在使用.我还注意到"$ _SERVER ['REQUEST_METHOD']"返回"GET".
and here we see that now the data is shown in "data" and "json" instead of in "form" but from my server I still get the same empty response so I gess my problem comes from the server side PHP code I'm using. I also note that "$_SERVER['REQUEST_METHOD']" is returning "GET".
我已经尝试了许多不同的方式来提出我的Volley请求,但是我不知道该怎么办.我尝试创建一个帮助器类,自定义JsonObjectRequest,重写getHeaders(),甚至使用AppController将请求添加到队列中……我想我对Post请求的工作方式还没有足够的了解,我是一个很新的人android develloping.
I've tried a lot of diferent ways to make my Volley request but I don't know what else to do. I've tried creating a helper class, custom JsonObjectRequest, overriding getHeaders(), even adding the request to the queue with the AppController... I guess I don't have enough understanding onhow the Post requests work, I'm pretty new with android develloping.
如果能帮助我了解如何使用Volley POST方法在服务器端接收数据,我将非常感激.非常感谢您的宝贵时间!
I would really be so grateful for any help to understand how am I supposed to receive my data on server side with the Volley POST method. Thank you very much for your time!
推荐答案
以下是可用于通过android中的 Volley库发出 POST 请求的代码.假设您将库这样导入您的应用程序build.gradle文件中:
Here is code you can use to make a POST request with the Volley library in android. Assuming you import your library as such in your application build.gradle file:
dependencies{
....
implementation 'com.android.volley:volley:1.1.0'
.....
}
下面的代码可以作为执行您的POST请求的一些常规任务放在方法中
The following code can be put in a method as some routine task to perform your POST request
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);
这篇关于Android Volley POST请求:在服务器端获取GET请求方法(php)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!