【问题标题】:Android Volley POST request: getting GET request method on server side (php)Android Volley POST 请求:在服务器端获取 GET 请求方法(php)
【发布时间】:2017-05-21 21:45:33
【问题描述】:

我正在制作一个需要向我的服务器发送 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);

由于我得到的回复总是空的,我还尝试将我的请求发送到 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);

我从我的服务器得到这个答案:

{"ans":"fileGetContents:  -- json encoded: null -- Request Method: GET -- $_REQUEST: [] -- $_POST: [] -- user: null -- $_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" 
}

我可以看到信息实际上是发送的,但不是作为 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);

从 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" 
}

在这里我们看到现在数据显示在“数据”和“json”而不是“表单”中,但是从我的服务器我仍然得到相同的空响应,所以我猜我的问题来自服务器端 PHP 代码我正在使用。我还注意到“$_SERVER['REQUEST_METHOD']”正在返回“GET”。

我已经尝试了很多不同的方法来提出我的 Volley 请求,但我不知道还能做什么。我已经尝试创建一个帮助类、自定义 JsonObjectRequest、覆盖 getHeaders(),甚至使用 AppController 将请求添加到队列中......我想我对 Post 请求的工作方式没有足够的了解,我很新安卓开发。

如果能帮助我了解我应该如何使用 Volley POST 方法在服务器端接收数据,我将不胜感激。非常感谢您的宝贵时间!

【问题讨论】:

    标签: php android post httprequest android-volley


    【解决方案1】:

    以下代码可用于通过 android 中的 Volley 库 发出 POST 请求。假设您在应用程序 build.gradle 文件中导入您的库:

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

    以下代码可以作为一些例行任务放入方法中以执行您的 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);
    

    【讨论】:

    • 值 1 和值 2 如何传递给 getParams() 函数?
    • 否 @AhmedRebai ,您的值应该是您从中发起请求的类的字段
    猜你喜欢
    • 2021-03-11
    • 1970-01-01
    • 2017-10-18
    • 1970-01-01
    • 1970-01-01
    • 2018-01-13
    • 2017-03-06
    • 1970-01-01
    • 2023-03-30
    相关资源
    最近更新 更多