【问题标题】:IOException when using BufferedWriter with HTTP将 BufferedWriter 与 HTTP 一起使用时出现 IOException
【发布时间】:2023-03-29 17:50:01
【问题描述】:

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

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

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

经过这么长的 itroduction 之后,我的问题是在尝试执行以下行时出现 IOException:

OutputStream outputStream = httpURLConnection.getOutputStream();

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

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

其中“login.php”是我的 php 脚本,它位于 wamp 服务器的 www 文件夹中。 我知道 10.0.0.2 是一种默认地址,它代表 Android Emulators 中的 localhost ,我是如何使用 Genymotion Emulator 的,所以这可能不是正确的地址? 我还尝试输入运行 IPCONFIG 时看到的所有其他 IP 地址,但没有改变结果。

我在调试方面不太好,所以我使用 Toasts 和 AsyncTask 的 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 是另一个用于连接数据库的脚本。 当我直接通过浏览器运行我的 login.php 脚本时 - 它工作正常。

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

【问题讨论】:

  • 仅供参考,您的 PHP 登录脚本不安全,令人难以置信。请学习how to bind parameters in PHP
  • 感谢您的评论。它仅用于 POC,不用于任何实际用途。
  • 是的,我已经觉得这不是一个供公众使用的脚本。尽管如此,我发现指出这一点很重要。是的,我正在推动一些个人议程:当涉及到注入攻击时,我非常警惕:/
  • 好吧,请随时在我的任何帖子中推送您的个人议程

标签: java android http genymotion bufferedwriter


【解决方案1】:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-04-11
    • 2021-02-28
    • 2017-10-19
    • 2017-12-04
    • 2022-01-04
    相关资源
    最近更新 更多