从Android发送数据到php服务器

时间:2021-06-25 13:36:27

标签: php android post

我正在尝试将数据从 Android 提交到我的 php 服务器。但是,所有答案似乎都使​​用了已弃用的 apache http 库。我不想使用它,当我尝试时它没有用。

现在它似乎没有做任何事情。好像连接到了web服务器,但是服务器并没有写入任何数据。如果我只是用浏览器访问这个 url,它会写入一个文件。

php代码为

<?php
// get the "message" variable from the post request
// this is the data coming from the Android app
$message=$_POST["message"]; 
// specify the file where we will save the contents of the variable message
$filename="androidmessages.html";
// write (append) the data to the file
file_put_contents($filename,$message."<br />",FILE_APPEND);
// load the contents of the file to a variable
$androidmessages=file_get_contents($filename);
// display the contents of the variable (which has the contents of the file)
echo $androidmessages;
?>

然后在 Android Studio 中,我在按下按钮后放置所有代码

    loginButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            loadingProgressBar.setVisibility(View.VISIBLE);
            loginViewModel.login(usernameEditText.getText().toString(),
                    passwordEditText.getText().toString());


            System.out.println("This is a test");

            Thread thread = new Thread(new Runnable() {

                @Override
                public void run() {
                    try  {
                        //Your code goes here

                        URL url = null;
                        OutputStream out = null;
                        String urlString = "https://mywebsite.net/php_script.php";
                        String data = "HelloWorld"; //data to post

                        try {
                            url = new URL(urlString);
                            HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
                            urlConnection.setRequestMethod("POST");
                            urlConnection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
                            urlConnection.setDoOutput(true);
                            out = new BufferedOutputStream(urlConnection.getOutputStream());
                            BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(out, "UTF-8"));
                            writer.write(data);
                            writer.flush();
                            writer.close();
                            out.close();
                            urlConnection.connect();

                        } catch (IOException e) {
                            System.out.println(e.getMessage());
                            e.printStackTrace();
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            });
            thread.start();

        }
    });
}

2 个答案:

答案 0 :(得分:2)

您的 PHP 代码正在 $_POST 中寻找名为“message”的变量

$message=$_POST["message"]; 

但是在您的 Android 代码中,您只需将消息数据写入 http 请求正文。

我建议查看 Volley,它是一个 HTTP 库,可以轻松发出 HTTP 请求。 This 的回答也可能有帮助。

答案 1 :(得分:1)

您可以为此使用 JSON 和 Volley!

<?php
$data = json_decode(file_get_contents('php://input'), true);
$filename="androidmessages.html";
file_put_contents($filename,$data["message"]."<br />",FILE_APPEND);
$reponse = array("message" => $androidmessages=file_get_contents($filename));
echo json_encode($reponse);
?>

这在 android (Kotlin) 中:

private fun sendHtmlRequest(view: View){
    val jsonobj = JSONObject()
    var url = "https://URL.php"

    jsonobj.put("message", "test message")

    val que = Volley.newRequestQueue(context)
    val req = JsonObjectRequest(Request.Method.POST, url, jsonobj,
        Response.Listener { response: JSONObject ->
            val messageResponse = response.getString("message")
            println("response: $messageResponse")
        }, Response.ErrorListener{
            println("Error")
        }
    )

    que.add(req)
}
相关问题