Android - 数据未发布到PHP脚本

时间:2017-01-31 12:07:35

标签: php android post

美好的一天!

我的Android应用程序需要将POST数据发送到PHP脚本,但脚本不会检测正在发送的数据。由于我对Java Android编程比较陌生,如果我忽略了一个简单的概念,请原谅我。

由于我从未涉及ajax,我希望找到一个无法实现ajax的解决方案,这就是“Get post data from Android to PHP”和“Posting data from android to PHP中解决方案的原因“不遵守我想要的解决方案。

以下是我的相关源代码:

insertContact.java

public void sendRequest() {
    SendtoPHP sendtoPHP = new SendtoPHP();
    sendtoPHP.execute(new String[] {
            "https://a/foo.php"
    });
}

private class SendtoPHP extends AsyncTask<String, Void, String> {
    @Override
    protected String doInBackground(String... urls) {
        BufferedReader reader = null;
        String text = "";

        try {
            String data = URLEncoder.encode("contactNo=98765432", "UTF-8");
            String type = "application/x-www-form-urlencoded";

            URL url = new URL(urls[0]);
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.setDoOutput(true);
            conn.setRequestMethod("POST");
            conn.setRequestProperty("Content-Type", type);
            conn.setRequestProperty("Content-Length", String.valueOf(data.length()));
            OutputStream outputStream = conn.getOutputStream();
            outputStream.write(data.getBytes());

            System.out.println("test success!");
            // server response
            reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
            StringBuilder sb = new StringBuilder();
            String line = null;

            // Read Server Response
            while ((line = reader.readLine()) != null) {
                // Append server response in string
                sb.append(line + "\n");
            }

            text = sb.toString();
        } catch (Exception e) {
            System.out.println(e);
        } finally {
            try {
                reader.close();
                return text;
            } catch (Exception e) {
                System.out.println(e);
                return "Failed to close reader.";
            }
        }
    }
    @Override
    protected void onPostExecute(String result) {
        System.out.println(result);
        System.out.println("SUCCESS!");
    }
}

foo.php

<?php
    if (isset($_POST['contactNo'])) {
        $contactNo = $_POST['contactNo'];

        //require_once 'dbHandler.php';
        //$con = new dbConnect();
        $querymysql = new mysqli("my_db_ip", "my_username", "my_password", "my_db");
        $result = $querymysql -> query("call insertContacts($contactNo)");

        if ($result) {
            echo "Insert successful!";
        } else {
            echo "Insert failed!";
        }

        $result -> close();
        $querymysql -> close();

    } else {
        echo "Hi! Welcome to foo.php. You have reached a dead end as you are physically connecting
        to our backend scripts.<br/>This page will unfortunately serve you no purpose. Sorry for the inconvenience
         caused.";
    }

Android Studio控制台日志

I/System.out: test success!
I/System.out: Hi! Welcome to foo.php. You have reached a dead end as you are physically connecting
I/System.out:         to our backend scripts.<br/>This page will unfortunately serve you no purpose. Sorry for the inconvenience
I/System.out:          caused.
I/System.out: SUCCESS!

正如我们从控制台日志中看到的那样,POST数据未被发送到PHP脚本,因为出现了不需要的回显消息。

欢迎任何帮助! :)

修改

根据@ FerryBig的答案修改我的代码后,我已经包含了错误的堆栈跟踪。

W/System.err: java.io.FileNotFoundException: https://a/foo.php
W/System.err:     at com.android.okhttp.internal.huc.HttpURLConnectionImpl.getInputStream(HttpURLConnectionImpl.java:250)
W/System.err:     at com.android.okhttp.internal.huc.DelegatingHttpsURLConnection.getInputStream(DelegatingHttpsURLConnection.java:210)
W/System.err:     at com.android.okhttp.internal.huc.HttpsURLConnectionImpl.getInputStream(HttpsURLConnectionImpl.java)
W/System.err:     at name.calvin.testdbconnect.insertContact$SendtoPHP.doInBackground(insertContact.java:62)
W/System.err:     at name.calvin.testdbconnect.insertContact$SendtoPHP.doInBackground(insertContact.java:41)
W/System.err:     at android.os.AsyncTask$2.call(AsyncTask.java:305)
W/System.err:     at java.util.concurrent.FutureTask.run(FutureTask.java:237)
W/System.err:     at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:243)
W/System.err:     at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1133)
W/System.err:     at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:607)
W/System.err:     at java.lang.Thread.run(Thread.java:761)

1 个答案:

答案 0 :(得分:0)

将数据发送到网络服务器时,您应该关注specifications。它说你应该使用=作为数据的分隔符,当你在数据中包含它时,你不小心通过urlencoder传递了这个,改变了字符。

通过单独更改urlencoder以对键侧(左侧)和值侧(右侧)进行编码,它将正确地发送数据。

String data = URLEncoder.encode("contactNo", "UTF-8") 
            + "=" 
            + URLEncoder.encode("98765432", "UTF-8");