Android 在AsyncTask或线程中将HTTP更改为HTTPS时出现NetworkOnMainThreadException

Android 在AsyncTask或线程中将HTTP更改为HTTPS时出现NetworkOnMainThreadException,android,multithreading,android-asynctask,Android,Multithreading,Android Asynctask,我被这个问题难住了。用户输入他们的网站。它是http或https,但当他们输入https网站时,我会得到一个NetworkOnMainThreadExecution,下面是我的异步任务。我做错了什么?如果我删除runOnUiThread,我会得到一个错误,只有创建视图层次结构的原始线程才能接触其视图错误,我认为这意味着任何对UI的更新都需要在线程中完成?因此,当我将更新放在线程中时,会出现networkonmainthreadexeption错误 private class runBabyRun

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

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;
    }
我得到的错误日志是:

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调用获得的流读取仍然是一个阻塞操作,必须在后台线程上执行

请参见,orb,为什么我不喜欢
AsyncTask
中的
runOnUiThread
。如果已经有了解决这个问题的方法,事情就变得复杂了。。。我也不喜欢AsyncTask,但正如我所说,如果一个人知道在做什么,这种事情很少发生@codeMagic@codeMagic你能给我看一下或给我指一下这些已经可以做到这一点的方法吗?我对Android和Java还不熟悉,所以我应该在doInBackground中的onPostExecute(Result)方法中执行吗。reader对象正在从网络字符串clientraw=reader.readLine()读取;进入
doInBackground
logcat中的相关行。它还告诉您是哪个语句导致了异常。您应该从onPostExecute中删除BufferedReader。因此出现了readLine()。在doInBackground中这样做。此外,webs.close是不属于onPostExecute的网络代码;那么,我是否将webs.close和BufferReader放在doInBackgroud()和字符串clientraw=reader.readLine()?所有人都应该到后台去。这都是网络代码,所以这就是原因。
很高兴我解决了它。
。要高兴并意识到别人为你解决了这个问题。
 String clientraw = reader.readLine();