php - 无法使用设备向服务器发送数据

标签 php android mysql

我是 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/

相关文章:

php - 用css设计php输出表

php - Laravel Nova 索引按钮没有出现

php - Facebook、Oauth、PHP 和在 MySQL 中存储 access_tokens

java - 如何将第三方 jar 文件添加到我的 android 应用程序 jar 文件中?

java - 我可以在 android studio 中将布局 View 转换为 pdf 文件吗?

mysql - 对值是否存在进行性能检查

php - 如何从cakePHP中的连接表中不可用的表中获取数据

android - 清除 Android 上的解析安装缓存

php - PHP/SQL 中的日期格式

mysql - M :N relation an query