我正在尝试使用 php 将 android 与 mysql 连接起来,将参数包含到表中。
我编写了可以运行的 php 代码。但我不明白为什么 android 的代码不起作用。我在 logcat 中没有收到错误。
主要 Activity :
...
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);
};
}
...
服务器请求
> 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";
}
?>
最佳答案
关于php - Android 向 PHP 发送字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37207879/