douyou8047 2017-06-07 00:20
浏览 52
已采纳

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

I'm new to Android and after a long time I finally manage to create a database using PHP scripts and MySQL.

While I'm using the Android Studio emulator I do succeed sending data to the database but when I run the application on my device I failed to do so. I don't get any error and the app keeps running (not crushing) but the database doesn't get the data.

This is the doInbackground method in my BackgroundTask class:

@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条回答 默认 最新

  • download1214 2017-06-07 02:22
    关注

    you want to do setting of the wampp server in your pc. i will give a URL for doing your work. please any query ask for it.

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

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)
编辑
预览

报告相同问题?

手机看
程序员都在用的中文IT技术交流社区

程序员都在用的中文IT技术交流社区

专业的中文 IT 技术社区,与千万技术人共成长

专业的中文 IT 技术社区,与千万技术人共成长

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

客服 返回
顶部