我是 Android 新手,经过很长一段时间,我终于成功地使用 PHP 脚本和 MySQL 创建了一个数据库。
当我使用 Android Studio 模拟器时,我确实成功地将数据发送到数据库,但当我在设备上运行应用程序时,我却失败了。 我没有收到任何错误,应用程序继续运行(没有崩溃),但数据库没有获取数据。
这是我的BackgroundTask 类中的doInbackground 方法:
@Override
// send info to MySQL DB
// it gets 4 parameters - the first if the opertaion should be "register" and the others are
// user info (name,pass,gender)
protected String doInBackground(String... params) {
// the ip is default for localhost
String reg_url = "http://**MyIP**/webapp/register.php";
String login_url = "http://**MyIP**/webapp/login.php";
String method = params[0];
if (Objects.equals(method, "register")){
String userName = params[1];
String userPass = params[2];
String gender = params[3];
try {
URL url = new URL(reg_url);
// run the register php script.
HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
httpURLConnection.setRequestMethod("POST");
httpURLConnection.setDoOutput(true);
OutputStream OS = httpURLConnection.getOutputStream();
BufferedWriter bufferedWriter = new BufferedWriter(new OutputStreamWriter(OS, "UTF-8"));
// applied the "userName,"userPass" and "gender" that I define in the POST (at the register.php)
// the info the user typed.
String data = URLEncoder.encode("userName", "UTF-8") + "=" + URLEncoder.encode(userName,"UTF-8") + "&" +
URLEncoder.encode("userPass", "UTF-8") + "=" +URLEncoder.encode(userPass,"UTF-8") + "&" +
URLEncoder.encode("gender", "UTF-8") + "=" +URLEncoder.encode(gender,"UTF-8");
// write the data to server
bufferedWriter.write(data);
bufferedWriter.flush();
bufferedWriter.close();
OS.close();
InputStream IS = httpURLConnection.getInputStream();
IS.close();
return "Registration Successs";
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
return null;
}
最佳答案
你想在你的电脑上设置wamp服务器。我会给你一个URL来完成你的工作。如有任何疑问,请询问。
http://androidcss.com/android/test-android-app-php-localhost-wamp/
关于php - 无法使用设备向服务器发送数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44407261/