我一直在努力的應用程序將發送字符串到我的服務器上的數據庫,但由於某種原因沒有收到數據。也許你可以指出我的方向是正確的,我一直在網上尋找,但找不到它不工作的原因。從應用程序發送字符串到服務器
我的Android代碼:
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");
從服務器到客戶端的通信方面,Json會是一個更好的選擇 – IteratioN7T
我不確定你要在這裏做什麼,但首先你的android代碼和php代碼不匹配,它們都是爲不同的目的。其次嘗試一些庫,如volley或okhttp的網絡請求。 –
該應用程序的主要目的是發送一個字符串到我的服務器上的數據庫,我對此很新,這就是爲什麼我掙扎了一下。 –