2010-06-18 72 views
4

我想下載一個網站的源代碼,並在文本框中顯示,但我似乎得到一個錯誤,無法弄明白:■下載html源碼android?

public void getHtml() throws ClientProtocolException, IOException 
{ 
    HttpClient httpClient = new DefaultHttpClient(); 
    HttpContext localContext = new BasicHttpContext(); 
    HttpGet httpGet = new HttpGet("http://www.spartanjava.com"); 
    HttpResponse response = httpClient.execute(httpGet, localContext); 
    String result = ""; 

    BufferedReader reader = new BufferedReader(
     new InputStreamReader(
      response.getEntity().getContent() 
     ) 
    ); 

    String line = null; 
    while ((line = reader.readLine()) != null){ 
     result += line + "\n"; 
     Toast.makeText(activity.this, line.toString(), Toast.LENGTH_LONG).show(); 

    } 

} 

怎麼來的,這並不工作,並拋出IOException?

+0

...其中它拋出異常 - 你可以標記的代碼行,請和發佈錯誤消息? – 2010-06-18 07:23:56

+0

HttpResponse response = httpClient.execute(httpGet,localContext); 這就是拋出異常,但Levara的評論固定它:D這是一個許可的事情 – Mars 2010-06-18 09:02:48

回答

2

我想你可能在你的manifest.xml中缺少INTERNET權限 請注意<uses-permission>標籤下面的代碼中提供。我在eclipse中測試了你的代碼,它工作。

順便說一句我認爲在這種方式使用String result不會工作。沒有測試那麼遠。但我認爲你不能只將字符串添加到字符串中。您需要使用stringBuilder並追加新的字符串。

編輯:測試了這個String result metod,它的工作原理。也許問題在於你試圖一次性扔掉這麼多面包。你的代碼會爲每一行retrived html代碼拋出敬酒。我設置你的getHtml()方法鍵入字符串,並返回result,它正確地返回它...我想不出有任何其他原因的異常,除了你的AndroidManifest.xml中缺少INTERNET權限....

乾杯!

<?xml version="1.0" encoding="utf-8"?> 
<manifest xmlns:android="http://schemas.android.com/apk/res/android" 
    package="test.test.test" 
    android:versionCode="1" 
    android:versionName="1.0"> 
<application android:icon="@drawable/icon" android:label="@string/app_name" android:debuggable="true"> 
    <activity android:name=".test" 
       android:label="@string/app_name"> 
     <intent-filter> 
      <action android:name="android.intent.action.MAIN" /> 
      <category android:name="android.intent.category.LAUNCHER" /> 
     </intent-filter> 
    </activity> 
</application> 
<uses-sdk android:minSdkVersion="3" /> 
<uses-permission android:name="android.permission.INTERNET"></uses-permission> 

+0

謝謝,雖然我還沒有測試代碼,因爲我現在不在我的筆記本電腦上,但是。我認爲你剛剛解決了它:D謝謝=) – Mars 2010-06-18 08:05:55

+0

它現在正在工作,我所做的只是更改權限......我用敬酒來測試下載:D – Mars 2010-06-18 09:03:11