我正在嘗試使用php將包括params在內的android與mysql連接起來。Android發送字符串到PHP
我發現了可以工作的php代碼。但我不明白爲什麼不工作android的代碼。我在logcat中沒有收到錯誤。
MainActivity:
...
boton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
sendMessage("mensaje");
}
});
}
public void sendMessage(String t){
ServerRequests serverRequests = new ServerRequests(this);
serverRequests.fetchUserDataAsyncTask(t);{
Log.d("", "sendMessage: "+t);
};
}
...
ServerRequest
> public class ServerRequests {
>
> URL url;
> HttpURLConnection conn;
> ProgressDialog progressDialog;
> String mensaje;
>
> public ServerRequests(Context context) {
> progressDialog = new ProgressDialog(context);
> progressDialog.setCancelable(false);
> progressDialog.setTitle("Authenticating...");
> progressDialog.setMessage("Please wait...");
> }
>
> public void fetchUserDataAsyncTask(String mensaje) {
> progressDialog.show();
> new fetchUserDataAsyncTask(mensaje,"hola").execute();
> }
>
> public class fetchUserDataAsyncTask extends AsyncTask<Void, Void, String> {
>
> String returnedUser;
>
>
> public fetchUserDataAsyncTask(String mensaje, String returnedUser) {
>
> }
>
> @Override
> protected String doInBackground(Void... params) {
>
> try {
>
> url = new URL("http://gclimb.com/androidphp/index.php");
>
> conn = (HttpURLConnection) url.openConnection();
> String param = "mensaje="+mensaje;
> conn.setRequestMethod("POST");
> conn.setDoInput(true);
> conn.setDoOutput(true);
> conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
> conn.setRequestProperty("charset", "UTF-8");
> conn.connect();
>
> OutputStreamWriter out = new OutputStreamWriter(conn.getOutputStream());
> out.write(param);
>
> //No code to receive response yet, want to get the POST working first.
>
> }
> catch (MalformedURLException e) {
> e.printStackTrace();
> } catch (ProtocolException e) {
> e.printStackTrace();
> } catch (IOException e) {
> e.printStackTrace();
> }
> catch (Exception e) {
>
> } finally {
> progressDialog.dismiss();
> }
>
> return returnedUser;
> }
> }
>
> }
編輯
這是一個簡單的index.php文件。
PHP文件:
<?php
$mensaje = $_POST['username'];
$mensaje2 = $_POST['password'];
$bo = $mensaje;
$servername = "zzzzzzz";
$username = "zzzzzz";
$password = "zzzzz";
$dbname = "zzzzz";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "INSERT INTO AndroidPhp (mensaje) VALUES ('$bo')";
$conn->query($sql);
$sql2="SELECT mensaje FROM AndroidPhp";
$result = $conn->query($sql2);
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
echo $row["mensaje"];
}
} else {
echo "0 results";
}
?>
你可以嘗試'conn.connect()'後你'write' PARAMS爲'OutputStream' –