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 seatunnel-web使用SQL组件时候后台报错,无法找到表格
  • ¥15 fpga自动售货机数码管(相关搜索:数字时钟)
  • ¥15 用前端向数据库插入数据,通过debug发现数据能走到后端,但是放行之后就会提示错误
  • ¥30 3天&7天&&15天&销量如何统计同一行
  • ¥30 帮我写一段可以读取LD2450数据并计算距离的Arduino代码
  • ¥15 飞机曲面部件如机翼,壁板等具体的孔位模型
  • ¥15 vs2019中数据导出问题
  • ¥20 云服务Linux系统TCP-MSS值修改?
  • ¥20 关于#单片机#的问题:项目:使用模拟iic与ov2640通讯环境:F407问题:读取的ID号总是0xff,自己调了调发现在读从机数据时,SDA线上并未有信号变化(语言-c语言)
  • ¥20 怎么在stm32门禁成品上增加查询记录功能