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

时间:2017-06-07 08:20:51

标签: 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;
}

2 个答案:

答案 0 :(得分:0)

您想在电脑中设置wampp服务器。我会给你一个工作的URL。请任何询问询问。

http://androidcss.com/android/test-android-app-php-localhost-wamp/

答案 1 :(得分:0)

将您的PC和Android设备连接到相同的wifi网络。

如果您在Windows上运行,请在ipconfig上输入cmd,如果在ifconfig上运行terminal以获取IP地址

它就像192.168.0.*。如果您获得的**MyIP**IP Address相同,则忽略它。

请确保您已获得在清单文件中访问互联网的权限。