我一直在开发一个应用程序,它会将字符串发送到我服务器上的数据库,但由于某种原因没有收到任何数据。也许你可以指出我正确的方向,我一直在网上搜索,但找不到它无法正常工作的原因。
我的安卓代码:
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");