NetworkOnMainThreadException 当我在 AsyncTask 或 Thread 中将 HTTP



我被困在这个问题上。用户输入他们的网站。它要么是http,要么是https,但是当他们输入https网站时,我会得到一个NetworkOnMainThreadExecption,下面是我的AsyncTask。我做错了什么?如果我删除 runOnUiThread,我会收到一个只有创建视图层次结构的原始线程才能触摸其视图错误,我认为这意味着对 UI 的任何更新都需要在线程中完成?因此,当我将更新放入线程中时,我收到NetworkOnMainThreadExecption错误。

private class runBabyRun extends AsyncTask<Void, Integer, String> {

    final TextView temperature = (TextView) findViewById(R.id.mTemp4);
    // a few more TextViews here
    @Override
    protected String doInBackground(Void... params) {
        try {
            if (httpSelection.equals("http://")) {
                HttpClient httpClient = new DefaultHttpClient();
                // get url data
                HttpPost httppost = new HttpPost(weburi);
                HttpResponse response = httpClient.execute(httppost);
                HttpEntity entity = response.getEntity();
                webs = entity.getContent();
            }
            if (httpSelection.equals("https://")) {
                Log.e("log_tag", "Entered https if statement ");
                HostnameVerifier hostnameVerifier = org.apache.http.conn.ssl.SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER;
                DefaultHttpClient client = new DefaultHttpClient();
                SchemeRegistry registry = new SchemeRegistry();
                SSLSocketFactory socketFactory = SSLSocketFactory.getSocketFactory();
                socketFactory.setHostnameVerifier((X509HostnameVerifier) hostnameVerifier);
                registry.register(new Scheme("https", socketFactory, 443));
                SingleClientConnManager mgr = new SingleClientConnManager(client.getParams(), registry);
                DefaultHttpClient httpClient = new DefaultHttpClient(mgr, client.getParams());
                // Set verifier
                HttpsURLConnection.setDefaultHostnameVerifier(hostnameVerifier);
                // get url data
                HttpPost httpPost = new HttpPost(weburi);
                HttpResponse response = httpClient.execute(httpPost);
                HttpEntity entity = response.getEntity();
                webs = entity.getContent();
            }
            // convert response to string
            try {
                final BufferedReader reader = new BufferedReader(
                        new InputStreamReader(webs, "iso-8859-1"),
                        8);
                // read one line of code, file is one whole string.
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        try {
                            //split file into array using space as delimiter
                            String clientraw = reader.readLine();
                            String[] parts = clientraw.split(" ");
                               clientRawData.addAll(Arrays.asList(parts));
                            //A few more setting up of fields here
                            // Get Weather Station Title
                            getSupportActionBar().setTitle(name(parts[32]));
                            temperature.setText(parts[4] + degrees);
                            time.setText(parts[29] + ":" + parts[30]);
                            date.setText(parts[74]);
                            webs.close();
                        } catch (Exception e) {
                            Log.e("log_tag", "Error in displaying textview " + e.toString());
                            e.printStackTrace();
                        }
                    }

                });
            } catch (Exception e) {
                Log.e("log_tag", "Error converting string " + e.toString());
            }
        } catch (Exception e) {
            Log.e("log_tag", "Error in http connection " + e.toString());
            Toast.makeText(getApplicationContext(), "Error in Connection, please check your URL - " + weburi, Toast.LENGTH_LONG).show();
            // setup intent for Settings
            Intent intent = new Intent(MainActivity.this, Setting.class);
            // Launch the Settings Activity using the intent for result
            startActivityForResult(intent, UPDATE_WEBURL);
        }
        return null;
    }

在下面的评论后编辑我已经更新了我的应用程序,它有onPostExecute,它看起来像下面的代码,但我仍然收到NetworkOnMainThreadExeption错误: E/log_tag:显示文本视图时出错 android.os.NetworkOnMainThreadException

    @Override
    protected void onPostExecute(String s) {
        super.onPostExecute(s);
        // convert response to string
        try {
            final BufferedReader reader = new BufferedReader(
                    new InputStreamReader(webs, "iso-8859-1"),
                    8);
            // read one line of code, file is one whole string.
            try {
                //split file into array using space as delimiter
                String clientraw = reader.readLine();
                String[] parts = clientraw.split(" ");
                // Get Weather Station Title
                getSupportActionBar().setTitle(name(parts[32]));
                temperature.setText(parts[4] + degrees);
                //and various other setTexts
                windDirection.setText(convertDegrees(parts[3]) + " " + "(" + (parts[3]) + "u00b0" + ")");
                time.setText(parts[29] + ":" + parts[30]);
                date.setText(parts[74]);
                webs.close();
            } catch (Exception e) {
                Log.e("log_tag", "Error in displaying textview " + e.toString());
                e.printStackTrace();
            }
        } catch (Exception e) {
            Log.e("log_tag", "Error converting string " + e.toString());
        }
    }

我得到的错误日志是:

03-13 01:39:18.984    5299-5299/uk.co.diong.weatherlive_ish E/log_tag﹕ Error in displaying textview android.os.NetworkOnMainThreadException
03-13 01:39:18.984    5299-5299/uk.co.diong.weatherlive_ish W/System.err﹕ android.os.NetworkOnMainThreadException
03-13 01:39:18.984    5299-5299/uk.co.diong.weatherlive_ish W/System.err﹕ at android.os.StrictMode$AndroidBlockGuardPolicy.onNetwork(StrictMode.java:1147)
03-13 01:39:18.984    5299-5299/uk.co.diong.weatherlive_ish W/System.err﹕ at com.android.org.conscrypt.OpenSSLSocketImpl$SSLInputStream.read(OpenSSLSocketImpl.java:657)
03-13 01:39:18.984    5299-5299/uk.co.diong.weatherlive_ish W/System.err﹕ at org.apache.http.impl.io.AbstractSessionInputBuffer.fillBuffer(AbstractSessionInputBuffer.java:103)
03-13 01:39:18.984    5299-5299/uk.co.diong.weatherlive_ish W/System.err﹕ at org.apache.http.impl.io.AbstractSessionInputBuffer.read(AbstractSessionInputBuffer.java:134)
03-13 01:39:18.984    5299-5299/uk.co.diong.weatherlive_ish W/System.err﹕ at org.apache.http.impl.io.ContentLengthInputStream.read(ContentLengthInputStream.java:174)
03-13 01:39:18.984    5299-5299/uk.co.diong.weatherlive_ish W/System.err﹕ at org.apache.http.conn.EofSensorInputStream.read(EofSensorInputStream.java:159)
03-13 01:39:18.984    5299-5299/uk.co.diong.weatherlive_ish W/System.err﹕ at java.io.InputStreamReader.read(InputStreamReader.java:231)
03-13 01:39:18.984    5299-5299/uk.co.diong.weatherlive_ish W/System.err﹕ at java.io.BufferedReader.fillBuf(BufferedReader.java:145)
03-13 01:39:18.984    5299-5299/uk.co.diong.weatherlive_ish W/System.err﹕ at java.io.BufferedReader.readLine(BufferedReader.java:397)
03-13 01:39:18.984    5299-5299/uk.co.diong.weatherlive_ish W/System.err﹕ at uk.co.diong.weatherlive_ish.MainActivity$runBabyRun.onPostExecute(MainActivity.java:307)
03-13 01:39:18.984    5299-5299/uk.co.diong.weatherlive_ish W/System.err﹕ at uk.co.diong.weatherlive_ish.MainActivity$runBabyRun.onPostExecute(MainActivity.java:227)
03-13 01:39:18.984    5299-5299/uk.co.diong.weatherlive_ish W/System.err﹕ at android.os.AsyncTask.finish(AsyncTask.java:632)
03-13 01:39:18.997    5299-5299/uk.co.diong.weatherlive_ish W/System.err﹕ at android.os.AsyncTask.access$600(AsyncTask.java:177)
03-13 01:39:18.997    5299-5299/uk.co.diong.weatherlive_ish W/System.err﹕ at android.os.AsyncTask$InternalHandler.handleMessage(AsyncTask.java:645)
03-13 01:39:18.997    5299-5299/uk.co.diong.weatherlive_ish W/System.err﹕ at android.os.Handler.dispatchMessage(Handler.java:102)
03-13 01:39:18.997    5299-5299/uk.co.diong.weatherlive_ish W/System.err﹕ at android.os.Looper.loop(Looper.java:135)
03-13 01:39:18.997    5299-5299/uk.co.diong.weatherlive_ish W/System.err﹕ at android.app.ActivityThread.main(ActivityThread.java:5221)
03-13 01:39:18.997    5299-5299/uk.co.diong.weatherlive_ish W/System.err﹕ at java.lang.reflect.Method.invoke(Native Method)
03-13 01:39:18.997    5299-5299/uk.co.diong.weatherlive_ish W/System.err﹕ at java.lang.reflect.Method.invoke(Method.java:372)
03-13 01:39:18.997    5299-5299/uk.co.diong.weatherlive_ish W/System.err﹕ at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:899)
03-13 01:39:18.997    5299-5299/uk.co.diong.weatherlive_ish W/System.err﹕ at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:694)
导致

NetworkOnMainThreadException的原因是以下行

 String clientraw = reader.readLine();

从 http 调用获得的流中读取,仍然是阻塞操作,必须在后台线程上执行

最新更新