[英]download html source 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中测试了您的代码,并且可以正常工作。
顺便说一句,我认为以这种方式使用String result
无法工作。 没测试那么远。 但是我认为您不能仅将字符串添加到字符串中。 您需要使用stringBuilder
并追加新字符串。
编辑:测试了此String result
方法,并且可以正常工作。 也许问题是您试图一次吐出这么多的吐司。 您的代码为检索的html代码的每一行都吐司。 我将您的getHtml()
方法设置为String类型,并返回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>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.