1
try {
    URL url = null;
    url = new URL(url_string);
    URLConnection conn = url.openConnection();
    BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
    String line="";
    while((line = reader.readLine())!=null){
        Log.d("html",line);
    }

} catch (Exception e) {
    Log.d("Exception Error: ",e.toString());
}

我只是在阅读网站,但我遇到了 android.os.networkonmainthreadexception 错误

我的代码很简单..请看一下并告诉我我需要做什么..

谢谢,

4

2 回答 2

3

您需要将网络访问移至后台线程,例如通过AsyncTask. 您目前正尝试在主应用程序线程上执行网络 I/O,这不是一个好主意。

于 2012-11-17T20:14:06.310 回答
0

使用这个类来运行后台任务..

    public class getConnection extends AsyncTask<String, Void, Void> 
    {


           @Override
            protected void onPreExecute() 
           {
               super.onPreExecute();
               Utils.clearDialogs();
               Utils.showActivityViewer(Mainctivity.this);
           }

           @Override
           protected Void doInBackground(String... arg0)
           {

            try 
            {

               URL url = null;
url = new URL(url_string);
URLConnection conn = url.openConnection();
BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
String line="";
while((line = reader.readLine())!=null){
    Log.d("html",line);
            } 
            catch (Exception e) 
            {
             e.printStackTrace();
            }

            return null;
           }

           @Override
           protected void onPostExecute(Void result)
           {
               super.onPostExecute(result);
               Utils.hideActivityViewer();

            }
            catch (Exception e)
            {
             Log.v("log", e.toString());
            }
           }

          }
于 2012-11-17T20:31:22.670 回答