2011-08-10 89 views
0

我想在我的Android应用程序用下面的代码加载网页的HTML:如何获得网页HTML

HttpClient client = new DefaultHttpClient(); 
    HttpGet request = new HttpGet("http://www.stackoverflow.com/"); 
    HttpResponse response = client.execute(request); 

    String html = ""; 

    InputStream in = response.getEntity().getContent(); 
    BufferedReader reader = new BufferedReader(new InputStreamReader(in)); 
    StringBuilder str = new StringBuilder(); 
    String line = null; 
    while ((line = reader.readLine()) != null) { 
     str.append(line); 
    } 
    in.close(); 
    html = str.toString(); 

但我发现了错误: Unhandled exception type ClientProtocolExceptionUnhandled exception type IOError在第三行;和Unhandled exception type IOError 6日,10日和13日线

我也尝试添加try/catch语句:

try { 
     HttpResponse response = client.execute(request); 
    } catch (ClientProtocolException e) { 
    } catch (IOException e) { 
    } 

,但有上线InputStream in = response.getEntity().getContent();错误说response cannot be resolved

(我上网允许清单)

问题在哪里?非常感谢

回答

1

快速修复是将您的整个代码块封装在try/catch中。

但是,它将最终帮助您理解Java中的异常。当你发现异常时,你会想要适当地处理它。一个良好的开始是在这里:http://download.oracle.com/javase/tutorial/essential/exceptions/

为了解决你的第二个例子的问题,你可以这样做:

HttpResponse response = null; 
    try { 
     client.execute(request); 
    } catch (ClientProtocolException e) { 
     //log the exception, throw it, etc... 
    } catch (IOException e) { 
     //log the exception, throw it, etc... 
    } 
    //if response != null, continue using it 
+0

好的,谢谢,它工作正常,但不存在任何清洁的方式? – simPod

+0

我在回答中增加了一些代码,以显示另一种可以使事情顺利进行的方法。 – elevine