java.lang.RuntimeException的未知原因

时间:2020-03-13 08:05:01

标签: java android mysql ip runtimeexception

当我尝试启动要检查数据库内容的应用程序时,遇到了非理性错误。我的应用程序在以下行中抛出了java.lang.RuntimeException:OutputStream ops = http.getOutputStream();

我的代码是:

 String result = "";
        String connstr = "http://myip:8080/androidlogin.php";

        try {
            URL url = new URL(connstr);
            HttpURLConnection http = (HttpURLConnection) url.openConnection();
            http.setRequestMethod("POST");
            http.setDoInput(true);
            http.setDoOutput(true);

Log.d("TAG", "1");
            OutputStream ops = http.getOutputStream();
            Log.d("TAG", "2");
            BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(ops,"UTF-8"));
            Log.d("TAG", "3");
            String data = URLEncoder.encode("user","UTF-8")+"="+URLEncoder.encode(id,"UTF-8");
            Log.d("TAG", "4");
            writer.write(data);
            writer.flush();
            writer.close();
            ops.close();

            InputStream ips = http.getInputStream();
            BufferedReader reader = new BufferedReader(new InputStreamReader(ips,"ISO-8859-1"));
            String line ="";
            while ((line = reader.readLine()) != null)
            {
                result += line;
            }
            reader.close();
            ips.close();
            http.disconnect();
            return result;

        } catch (MalformedURLException e) {
            result = e.getMessage();
        } catch (IOException e) {
            result = e.getMessage();
        }


        return result;

我的错误看起来像这样:

2020-03-13 08:01:07.460 10633-10633/com.hu.jam E/AndroidRuntime: FATAL EXCEPTION: main
    Process: com.hu.jam, PID: 10633
    java.lang.RuntimeException: Unable to start activity ComponentInfo{com.hu.jam/com.hu.jam.MainActivity}: android.os.NetworkOnMainThreadException
        at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2984)
        at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3045)
        at android.app.ActivityThread.-wrap14(ActivityThread.java)
        at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1642)
        at android.os.Handler.dispatchMessage(Handler.java:102)
        at android.os.Looper.loop(Looper.java:154)
        at android.app.ActivityThread.main(ActivityThread.java:6776)
        at java.lang.reflect.Method.invoke(Native Method)
        at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1496)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1386)
     Caused by: android.os.NetworkOnMainThreadException

最有趣的部分是在Log 1和错误之间,logcat上有三个有趣的消息:

2020-03-13 08:01:07.442 10633-10633/com.hu.jam D/TAG: 1
2020-03-13 08:01:07.444 10633-10633/com.hu.jam I/System.out: (HTTPLog)-Static: isSBSettingEnabled false
2020-03-13 08:01:07.444 10633-10633/com.hu.jam I/System.out: (HTTPLog)-Static: isSBSettingEnabled false
2020-03-13 08:01:07.451 10633-10633/com.hu.jam D/AndroidRuntime: Shutting down VM
2020-03-13 08:01:07.460 10633-10633/com.hu.jam E/AndroidRuntime: FATAL EXCEPTION: main

这是一个php脚本:

<?php
$db = "database1";
$user = $_POST["user"];
$host = "localhost";

$conn = mysqli_connect($host, "root", "", $db);
if($conn){
    echo "connected....!";
    $q= "select * from article where a_title='$user'";

    $result = mysqli_query($conn, $q);
    if(mysqli_num_rows($result) > 0){
        echo"login successfull...!";
    }else {
        echo"login failed....!";
    }

}else{
    echo"connection failed....!";
}


?>

我的代码有什么问题?一切似乎都还不错,但是却行不通...

3 个答案:

答案 0 :(得分:0)

要处理网络请求,建议在单独的线程How to run a Runnable thread in Android at defined intervals?中运行代码

Runnable r = new Runnable() {
    public void run() {
      //Put your network code here
    }
}.start();

答案 1 :(得分:0)

首先,创建一个新的Runnable。记住,它需要为您提供一种机制,以便在完成后获得结果。另外,我强烈建议您利用try-with-Resources statement而不是显式关闭。像

public class MyLoginRunnable implements Runnable {
    private StringBuilder sb = new StringBuilder();
    private String connstr;
    private String id;

    public MyLoginRunnable(String connstr, String id) {
        this.connstr = connstr;
        this.id = id;
    }

    public String getResult() {
        return sb.toString();
    }

    @Override
    public void run() {
        try {
            URL url = new URL(connstr);
            HttpURLConnection http = (HttpURLConnection) url.openConnection();
            http.setRequestMethod("POST");
            http.setDoInput(true);
            http.setDoOutput(true);

            try (OutputStream ops = http.getOutputStream();
                    BufferedWriter writer = new BufferedWriter( //
                            new OutputStreamWriter(ops, "UTF-8"))) {
                String data = URLEncoder.encode("user", "UTF-8") //
                        + "=" + URLEncoder.encode(id, "UTF-8");
                writer.write(data);
            }

            try (InputStream ips = http.getInputStream();
                    BufferedReader reader = new BufferedReader( //
                            new InputStreamReader(ips, "ISO-8859-1"))) {
                String line = "";
                while ((line = reader.readLine()) != null) {
                    sb.append(line).append(System.lineSeparator());
                }
            }
            http.disconnect();
        } catch (MalformedURLException e) {
            sb.append(e.getMessage());
        } catch (IOException e) {
            sb.append(e.getMessage());
        }
    }
}

然后您可以像使用它

String connstr = "http://myip:8080/androidlogin.php";
MyLoginRunnable mlr = new MyLoginRunnable(connstr, "");
Thread t = new Thread(mlr);
t.start();
try {
    t.join(); // <-- this is for your simple example, in real code you don't want to pause
} catch (InterruptedException e) {
    e.printStackTrace();
}
String result = mlr.getResult();

答案 2 :(得分:0)

例外是因为您正在主UI线程上运行网络任务,该任务应该是后台任务。将AsyncTask用于网络或IO任务。 https://developer.android.com/reference/android/os/AsyncTask