从应用程序向服务器发送字符串

时间:2017-02-14 10:07:04

标签: php android mysql database android-studio

我一直在开发一个应用程序,它会将字符串发送到我服务器上的数据库,但由于某种原因没有收到任何数据。也许你可以指出我正确的方向,我一直在网上搜索,但找不到它无法正常工作的原因。

我的安卓代码:

    public class HttpURLConnectionHandler
    {
    protected String urlG = "http://example.com/";
    public String sendText(String text)
    {

        try {
            URL url = new URL(urlG+"phpcode.php");
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.setRequestMethod("POST");

            conn.setDoOutput(true);
            conn.setDoInput(true);
            conn.connect();
            DataOutputStream wr = new DataOutputStream(
                    conn.getOutputStream());

            wr.writeBytes("mydata:"+text);
            wr.flush();
            wr.close();

            InputStream is = conn.getInputStream();
            BufferedReader rd = new BufferedReader(new InputStreamReader(is));
            String line;
            StringBuffer response = new StringBuffer();
            while((line = rd.readLine()) != null) {
                response.append(line);
                response.append('\r');
            }
            rd.close();
            return response.toString();
        }
        catch(Exception e){ return "error";}
    }

}

我在php中的代码:

<?php
$servername = "here is my server";
$username = "my username";
$password = "my pass";
$dbname = "database";

// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
}



$image = $_POST['image'];


$sql = "INSERT INTO photos (image)
VALUES ('{$image}')";

if ($conn->query($sql) === TRUE) {
    echo "New record created successfully";
} else {
    echo "Error: " . $sql . "<br>" . $conn->error;
}

$conn->close();
?> 

我打电话给我班的方式是:

HttpURLConnectionHandler handler= new HttpURLConnectionHandler();
String response = handler.sendText("this is a text");

2 个答案:

答案 0 :(得分:0)

我让你看看Retrofit

答案 1 :(得分:0)

您试图在PHP中获得POST变量图像的值,但您发送变量 mydata