java – 下载html源码android?

我正在尝试下载一个网站源代码并将其显示在文本框中,但我似乎得到一个错误,无法弄明白:s

 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?

最佳答案 我想你可能在manifest.xml中缺少INTERNET权限

请注意< uses-permission>标签在下面的代码中提供.我在eclipse中测试了你的代码,它的工作原理.

BTW我认为以这种方式使用String结果不会起作用.虽然没有测试那么远.但我认为你不能只是在字符串中添加字符串.您需要使用stringBuilder并附加新字符串.

编辑:测试此字符串结果metod,它的工作原理.也许问题是你想要一次性抛出这么多的吐司.您的代码会为每行重新生成的html代码抛出一个祝酒词.我将你的getHtml()方法设置为String类型,并返回结果,并且它正确返回…除了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>
点赞