我正在尝试从用户输入的网站获取字符串中的 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\”,所以他们肯定应该做出回应
最佳答案
你的代码没问题。确保粘贴完整的网站路径:http://www。 [页] 。 [域名]
例如:http://www.google.com
并将此 PERMISSION 添加到 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>
关于android - 从 Android 应用程序读取 HTML 源代码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10155938/