我正在尝试下载网站源代码并将其显示在文本框中,但我似乎收到错误并且无法弄清楚: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 权限...
Cheers!
<?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>
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)