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条)

报告相同问题?

悬赏问题

  • ¥15 基于卷积神经网络的声纹识别
  • ¥15 Python中的request,如何使用ssr节点,通过代理requests网页。本人在泰国,需要用大陆ip才能玩网页游戏,合法合规。
  • ¥100 为什么这个恒流源电路不能恒流?
  • ¥15 有偿求跨组件数据流路径图
  • ¥15 写一个方法checkPerson,入参实体类Person,出参布尔值
  • ¥15 我想咨询一下路面纹理三维点云数据处理的一些问题,上传的坐标文件里是怎么对无序点进行编号的,以及xy坐标在处理的时候是进行整体模型分片处理的吗
  • ¥15 CSAPPattacklab
  • ¥15 一直显示正在等待HID—ISP
  • ¥15 Python turtle 画图
  • ¥15 stm32开发clion时遇到的编译问题