简体   繁体   English

Android Volley POST请求:在服务器端获取GET请求方法(php)

[英]Android Volley POST request: getting GET request method on server side (php)

I am making an android app that needs to send Post requests to my server and could really use some help! 我正在制作一个需要将Post请求发送到我的服务器的android应用,确实​​可以使用一些帮助! I've been trying to make these requests using android Volley. 我一直在尝试使用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 . 我已经在这里阅读了许多相关问题以及有关Android Volley的各种文档资料,但是由于我设法提出请求,因此我不可能在服务器端以正确的方式接收发布的数据,而且我也不了解我做错了什么...我尝试用stringRequest覆盖getParams()和自定义JsonObjectRequest,并将数据作为参数 I get diferent results on server side with both requests but I'm still not able to catch it the right way. 我在两个请求的服务器端都得到了不同的结果,但是仍然无法以正确的方式捕获它。

On my server side my debug PHP file goes like this: 在服务器端,我的调试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);

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. 由于收到的响应始终为空,因此我也尝试将请求发送到http://httpbin.org/post ,这会给我带来有趣的信息。

So with the first stringRequest that I make like this: 因此,使用以下第一个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);

I get this answer from my server: 我从服务器获得以下答案:

{"ans":"fileGetContents:  -- json encoded: null -- Request Method: GET -- $_REQUEST: [] -- $_POST: [] -- user: null -- $_GET: []"}

And from httpbin.org i get: 从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" 
}

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... 我可以看到信息实际上是发送的但不是作为POST数据接收的,而是作为Form数据接收的,我实际上并不知道它是什么或如何从PHP接收它...

Then in my second JsonObjectRequest that goes like this: 然后在我的第二个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);

From httpbin.org I get: 从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" 
}

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. 在这里,我们看到现在数据以“数据”和“ json”而不是“表单”显示,但是从我的服务器上我仍然得到相同的空响应,所以我觉得我的问题来自服务器端PHP代码使用。 I also note that "$_SERVER['REQUEST_METHOD']" is returning "GET". 我还注意到,“ $ _ SERVER ['REQUEST_METHOD']”返回“ GET”。

I've tried a lot of diferent ways to make my Volley request but I don't know what else to do. 我已经尝试了许多不同的方式来提出我的Volley请求,但是我不知道该怎么办。 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. 我尝试创建一个帮助器类,自定义JsonObjectRequest,覆盖getHeaders(),甚至使用AppController将请求添加到队列中……我想我对Post请求的工作方式还没有足够的了解,我是一个很新的人与android develloping。

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. 我真的很感谢您提供帮助,以帮助我了解如何使用Volley POST方法在服务器端接收数据。 Thank you very much for your time! 非常感谢您的宝贵时间!

Here is code you can use to make a POST request with the Volley library in android. 这是您可以用来在android的Volley库中发出POST请求的代码。 Assuming you import your library as such in your application build.gradle file: 假设您在应用程序build.gradle文件中这样导入库:

dependencies{
     .... 
     implementation 'com.android.volley:volley:1.1.0'
     .....
 }

The following code can be put in a method as some routine task to perform your POST request 可以将以下代码作为执行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);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM