在Android应用程序中获取带有url的html源代码

时间:2011-06-14 21:57:25

标签: android html url

我试图编写一些代码从用户那里获取一个url,之后点击提交按钮,我将获取网址并进行调用并从页面中检索html源代码。但是,我有以下例外:

W / System.err(14858):android.os.NetworkOnMainThreadException W / System.err(14858):在android.os.StrictMode $ AndroidBlockGuardPolicy.onNetwork(StrictMode.java:1077)

对于android 3.0来说,我尝试开发的平台似乎不允许我在main方法上使用网络资源。我知道有一些方法,比如在后台运行它或使用异步方法应该可以工作,但有人可以指导我吗?我不太确定如何去做。我是编程新手。 提前谢谢。

以下是我当前的代码,onclick方法:

    String htmlCode = ""; 

    try {
    URL url = new URL("http://www.google.com");
    BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream()));

    String inputLine;

    while ((inputLine = in.readLine()) != null) {
        htmlCode += inputLine;
        Log.d(LOG_TAG, "html: " + inputLine);
    }

    in.close();
    } catch (Exception e) {
        e.printStackTrace();
        Log.d(LOG_TAG, "Error: " + e.getMessage());
        Log.d(LOG_TAG, "HTML CODE: " + htmlCode);
    }

1 个答案:

答案 0 :(得分:1)

您可以使用Runnable或Thread,但可能最常用的Android方法是使用AsyncTask。

new AsyncTask<String, Void, String>(){
  @Override
  protected String doInBackground(String... urlStr){
    // do stuff on non-UI thread
    StringBuffer htmlCode = new StringBuffer();
    try{
      URL url = new URL(urlStr[0]);
      BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream()));

      String inputLine;

      while ((inputLine = in.readLine()) != null) {
        htmlCode += inputLine;
        Log.d(LOG_TAG, "html: " + inputLine);
      }

      in.close();
    } catch (Exception e) {
        e.printStackTrace();
        Log.d(LOG_TAG, "Error: " + e.getMessage());
        Log.d(LOG_TAG, "HTML CODE: " + htmlCode);
    }
    return htmlCode.toString();
  }         

  @Override
  protected void onPostExecute(String htmlCode){
    // do stuff on UI thread with the html
    TextView out = (TextView) findViewById(R.id.out);
    out.setText(htmlCode);
  }
}.execute("http://www.google.com");
相关问题