我正在尝试从用户输入的网站的字符串中获取HTML源代码,到目前为止我的代码看起来像这样:
public String getURLContent(String url)
{
try
{
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpGet httpGet = new HttpGet(url);
ResponseHandler<String> resHandler = new BasicResponseHandler();
String page = httpClient.execute(httpGet, resHandler);
return page;
}
catch (ClientProtocolException e)
{
e.printStackTrace();
return "";
}
catch (IOException e)
{
e.printStackTrace();
return "";
}
}
每次我尝试运行时,我都会遇到第二个问题(IOException),根据文档意味着服务器无法提供有效的响应...我正在使用“http:\ _www.google”这样的网站进行测试.com \“,所以他们肯定会回应
答案 0 :(得分:1)
除非你想用整个字符串做一些自定义解析,否则我建议你使用HTML解析器库。我使用HTML清理器,显示here。
这使得所有的马都适合你。
答案 1 :(得分:1)
您的代码没问题。确保您粘贴完整的网站路径:http://www. [page] . [domain]
例如:http://www.google.com
并将此权限添加到AndroidManifest.xml
<uses-permission android:name="android.permission.INTERNET" />
就在之前(如果是新项目):
<application android:label="@string/app_name">
完整示例:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example"
android:versionCode="1"
android:versionName="1.0">
<uses-sdk android:minSdkVersion="10"/>
<uses-permission android:name="android.permission.INTERNET" />
<application android:label="@string/app_name">
<activity android:name="MyActivity"
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>
</manifest>