将BufferedWriter与HTTP

时间:2016-05-15 11:21:35

标签: java android http genymotion bufferedwriter

我遵循了一个关于将使用wamp服务器(在Windows上)运行的MyQSL数据库连接到Android应用程序的youtube教程。 (视频链接为:https://www.youtube.com/watch?v=eldh8l8yPew

在我的Android Studio代码中,我创建了一个类(名为" BackgroundWorker"),它扩展了AsyncTask,并且应该处理与连接到数据库的PHP文件的通信。

为了打开写入DB的写入通道,我使用BufferedWriter和OutputStream连接到httpURLConnection对象,该对象具有我的相关php脚本的URL,该脚本位于WAMPSERVER的www文件夹中。

经过这么长时间的生产,我的问题是我在尝试执行以下行时遇到IOException:

OutputStream outputStream = httpURLConnection.getOutputStream();

我已经多次复制了视频教程中的整个代码,所以我怀疑它有什么问题。 我更多地考虑URL设置的方向 - 我的URL对象获取具有地址的String:

String loginURL = "http://10.0.2.2/login.php";

其中" login.php"是我的PHP脚本,位于wamp服务器的www文件夹中。 我知道10.0.0.2是一种默认地址,可以代替Android Emulator中的localhost,但我怎么使用Genymotion Emulator,所以这可能不是正确的地址? 我还试图在运行IPCONFIG时看到我看到的所有其他IP地址,但没有更改结果。

我在dubugging方面不太好,所以我使用AsastTask的Toasts和PublishProgress方法来查找和隔离IOException。

以下是我认为可能与IOException相关的部分代码:

我的BackgroundWorker类(扩展了AsyncTask):

public class BackgroundWorker extends AsyncTask <String , Integer , String> {
    Context context;
    AlertDialog alertDialog;
    public BackgroundWorker(Context userContext) {
        this.context = userContext;
    }

    @Override
    protected String doInBackground(String... params) {
        // Reading the arguments in the order I sent them in MainActivity
        String username = params[0];
        String pass = params[1];
        String type = params[2];

        // Making structure for updating during the wat using Toasts (and showing the first one
        int progressValue = 0;          // Before if
        publishProgress(progressValue);
        // Initial String that will hold the text to read from server
        String result = "";
        // Initial the URL String , the IP address if standart for Android LocalHost
        String loginURL = "http://10.0.2.2/login.php";
        if (type.equals("login")) {

            progressValue++;    //1
            publishProgress(progressValue);

            try {
                URL url = new URL(loginURL);

                progressValue++;    //2
                publishProgress(progressValue);

                // Building the HttpUrlConnection object
                HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
                httpURLConnection.setRequestMethod("POST");
                httpURLConnection.setDoOutput(true);
                httpURLConnection.setDoInput(true);

                progressValue++;    //3
                publishProgress(progressValue);

                // Building the writing infrastructure
                // IOException occurs after the commit of the next line
                OutputStream outputStream = httpURLConnection.getOutputStream();
                BufferedWriter bufferedWriter = new BufferedWriter(new OutputStreamWriter(outputStream,"UTF-8"));

                progressValue++;    //4
                publishProgress(progressValue);

                // Building the message to the PHP script
                String post_data = URLEncoder.encode("user_name" , "UTF-8") + "=" + URLEncoder.encode(username , "UTF-8")
                        + "&" + URLEncoder.encode("user_pass" , "UTF-8") + "=" + URLEncoder.encode(pass , "UTF-8");

                progressValue++;    //5
                publishProgress(progressValue);

                // Writing the data
                bufferedWriter.write(post_data);

                progressValue++;    //6
                publishProgress(progressValue);

                // Closing all writing structures
                bufferedWriter.flush();
                bufferedWriter.close();
                outputStream.close();

                // Building the Reading Infrastructure
                InputStream inputStream = httpURLConnection.getInputStream();
                BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream , "iso-8859-1"));

                // Reading the data
                String line;
                while ((line = bufferedReader.readLine()) != null) {
                    result += line;
                }
                // Closing all reading structures
                bufferedReader.close();
                inputStream.close();
                httpURLConnection.disconnect();


            } catch (MalformedURLException e) {
                e.printStackTrace();
                progressValue = 10;
                publishProgress(progressValue);
            } catch (IOException e) {
                progressValue = 11;
                publishProgress(progressValue);
                e.printStackTrace();
            }
        }
        return result;
    }

    @Override
    protected void onProgressUpdate(Integer... values) {
        int progressValue = values[0];
        // Before IF statement
        if (progressValue == 0) Toast.makeText(this.context , "Before if" , Toast.LENGTH_SHORT).show();
        // After IF statement
        if (progressValue == 1) Toast.makeText(this.context , "After if" , Toast.LENGTH_SHORT).show();
        // After URL statement
        if (progressValue == 2) Toast.makeText(this.context , "After URL Setting" , Toast.LENGTH_SHORT).show();
        // Before Writing data
        if (progressValue == 3) Toast.makeText(this.context , "After making HTML" , Toast.LENGTH_SHORT).show();
        // After Writing data
        if (progressValue == 4) Toast.makeText(this.context , "After making writing infra" , Toast.LENGTH_SHORT).show();
        // After Writing data
        if (progressValue == 5) Toast.makeText(this.context , "Before Writing data" , Toast.LENGTH_SHORT).show();
        // After Writing data
        if (progressValue == 6) Toast.makeText(this.context , "After Writing data" , Toast.LENGTH_SHORT).show();
        // After Writing data
        if (progressValue == 10) Toast.makeText(this.context , "First exception" , Toast.LENGTH_SHORT).show();
        // After Writing data
        if (progressValue == 11) Toast.makeText(this.context , "IO Exception" , Toast.LENGTH_SHORT).show();
    }

    @Override
    protected void onPreExecute() {
        alertDialog = new AlertDialog.Builder(context).create();
        alertDialog.setTitle("Login Status");
    }

    @Override
    protected void onPostExecute(String result) {
        alertDialog.setMessage(result);
        alertDialog.show();
    }
}

这是我的login.php代码:

<?php
require "conn.php";
$user_name = $_POST["user_name"];
$user_pass = $_POST["user_pass"];
$mysql_qry = "select * from employee_data where user like '$user_name' and password like '$user_pass';";
$result = mysqli_query($conn ,$mysql_qry);
if(mysqli_num_rows($result) > 0) {
    echo "login success";
}
else {
    echo "login not seccess";
}
?>

conn.php是另一个只是连接数据库的脚本。 当我直接通过broswer运行我的login.php脚本时 - 它运行正常。

非常感谢, 我希望你能理解这个问题, 诺姆

1 个答案:

答案 0 :(得分:0)

我自己解决了。 IP地址不正确,因为我使用Genymotion Emulator我必须将IP更改为192.168.56.1 现在一切正常。