dssu33392 2019-07-16 15:31
浏览 79
已采纳

PHP无法识别来自Android HttpsURLConnection的POST

I am trying to send a login POST request to my PHP/MySQL backend from an Android app, and for some reason, my PHP app is not seeing the POST request from Android. I've checked in the Network Profiler section of Android Studio, and I can see that it is sending a POST request, but each time I send the request, the app receives the "Request method incorrect." JSON response I have setup.

I have tried every iteration of every possible solution I can think of to get this to work, and I have no idea what I'm missing. I will post both the Android code and the PHP code so that somebody somewhere can hopefully point me in the right direction of what I'm doing wrong here.

I have created a very simple web form on my server to test the login data, and it can see POST requests just fine from another PHP script. The problem comes, however, when Android tries to POST to the script - for some reason the app doesn't recognize what Android is sending as a POST request.

This is my entire "doInBackground" activity of the Async portion of my Android app.

String action = params[0];

        if (action.equals("login")) {
            // Url to login at
            String postUrl = Urls.URL_LOGIN;

            // Username and password from login form
            String username = params[1];
            String password = params[2];

            try {
                URL url = new URL(postUrl);
                boolean redirect = false;

                do {
                    redirect = false;

                    String urlParameters = URLEncoder.encode("username", "UTF-8") + "=" + URLEncoder.encode(username, "UTF-8") + "&" + URLEncoder.encode("password", "UTF-8") + "=" + URLEncoder.encode(password, "UTF-8");

                    byte[] postData = urlParameters.getBytes(StandardCharsets.UTF_8);
                    int postDataLength = postData.length;

                    HttpURLConnection conn = (HttpURLConnection) url.openConnection();
                    conn.setReadTimeout(20000);
                    conn.setConnectTimeout(20000);
                    conn.setRequestMethod("POST");
                    conn.setDoOutput(true);
                    conn.setDoInput(true);
                    conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded;charset=UTF-8");
                    conn.setRequestProperty("Content-Length", Integer.toString(postDataLength));
                    conn.setRequestProperty("Accept", "application/json");
                    conn.setUseCaches(false);

                    OutputStream os = conn.getOutputStream();
                    OutputStreamWriter osW = new OutputStreamWriter(os, "UTF-8");
                    BufferedWriter writer = new BufferedWriter(osW);

                    writer.write(urlParameters);
                    writer.flush();
                    writer.close();
                    os.close();

                    int responseCode = conn.getResponseCode();

                    if (responseCode == HttpsURLConnection.HTTP_OK) {
                        InputStream inputStream = conn.getInputStream();
                        BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream, "ISO-8859-1"));

                        StringBuilder sb = new StringBuilder();
                        String json;

                        while ((json = bufferedReader.readLine()) != null) {
                            sb.append(json + "
");
                        }

                        bufferedReader.close();
                        inputStream.close();

                        conn.disconnect();

                        return sb.toString().trim();
                    } else {
                        redirect = true;
                        Log.d("*** RANDOM CHAT ***", "HTTP Response Code: " + responseCode);

                        return null;
                    }
                } while (redirect);
            } catch (MalformedURLException e) {
                return null;
            } catch (IOException e) {
                return null;
            }
        }

        return null;

And this is my entire PHP app listening for POSTs.

header('Content-Type: application/json');

require_once("inc.db.php");
require_once("inc.fx.php");

$response = array();

if($_SERVER['REQUEST_METHOD'] == "POST"){
    if(isset($_GET["action"]) && $_GET["action"] == "login") {
        if(is_valid(array('username','password'))) {
            $username = $_POST["username"];
            $password = md5($_POST["password"]);

            if(count_db("users",array("username","password","banned"),array($username,$password,0))["data"] > 0) {
                $response = get_db("users",array("username","password"),array($username,$password));
            } else {
                $response["success"] = false;
                $response["data"] = "Invalid login information. Username: " . $username . ", Password: " . $password;
            }
        } else {
            $response["success"] = false;
            $response["data"] = "Username and password required for login. Username: " . $_POST["username"] .", Password: " . $_POST["password"];
        }
    } elseif(isset($_GET["action"]) && $_GET["action"] == "register") {
        if(is_valid(array('username','password'))) {
            $username = $_POST["username"];
            $email = $_POST["email"];
            $password = md5($_POST["password"]);

            if((count_db("users",array("username"),array($username))["data"] <= 0) && (count_db("users",array("email"),array($email))["data"] <= 0)) {
                if(insert_db("users",array("username","email","password"),array($username,$email,$password))) {
                    $response = get_db("users",array("username"),array($username));
                } else {
                    $response['success'] = false;
                    $response['data'] = "Unable to create user.";
                }
            } else {
                $response["success"] = false;
                $response["data"] = "Username or email exists.";
            }
        } else {
            $response["success"] = false;
            $response["data"] = "Username, email, and password required for registration.";
        }
    } else {
        $response['success'] = false;
        $response['data'] = "No server action specified.";
    }
} else {
    $response['success'] = false;
    $response['data'] = "Request method incorrect.";
}

echo json_encode($response);

I would expect that the very basic server REQUEST_METHOD check would pass since I am sending a POST, however it isn't. Once that check passes, I'm assuming the PHP code would have no problems reading the username and password of the POST request and sending the valid response back to the app for me to handle later.

And just in case anyone would like to see it, here is the Network Profiler information when attempting to login from the app:

Android Network Profiler

  • 写回答

2条回答 默认 最新

  • doucheng2053 2019-07-16 17:43
    关注

    After a lot of digging, I finally fixed the issue. I have an .htaccess file at the root of my website (this Android app is hitting a subdomain). That .htaccess file was redirecting ALL traffic to the https://www portion of my website, which for some reason, was catching my subdomain as well.

    I found this by looking at the apache logs on my server for the subdomain, and noticing that the response was 301, so I knew something was wrong and being redirected somewhere. After disabling the .htaccess redirects, I finally received a response back in the app that I was looking for.

    Sorry for the trouble, and hopefully this can help someone else out!

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥20 求快手直播间榜单匿名采集ID用户名简单能学会的
  • ¥15 DS18B20内部ADC模数转换器
  • ¥15 做个有关计算的小程序
  • ¥15 MPI读取tif文件无法正常给各进程分配路径
  • ¥15 如何用MATLAB实现以下三个公式(有相互嵌套)
  • ¥30 关于#算法#的问题:运用EViews第九版本进行一系列计量经济学的时间数列数据回归分析预测问题 求各位帮我解答一下
  • ¥15 setInterval 页面闪烁,怎么解决
  • ¥15 如何让企业微信机器人实现消息汇总整合
  • ¥50 关于#ui#的问题:做yolov8的ui界面出现的问题
  • ¥15 如何用Python爬取各高校教师公开的教育和工作经历