在AsyncTask或Thread中将HTTP更改为HTTPS时出现NetworkOnMainThreadException

时间:2015-03-13 15:18:30

标签: android multithreading android-asynctask

我遇到了这个问题。用户输入他们的网站。它是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:显示textview 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)

1 个答案:

答案 0 :(得分:3)

导致NetworkOnMainThreadException的原因是以下行

 String clientraw = reader.readLine();

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