android - 从 Android 应用程序读取 HTML 源代码

标签 android html http httpclient http-get

我正在尝试从用户输入的网站获取字符串中的 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/

相关文章:

android - 如何使用 iText 库在动态 pdf 中添加页眉和页脚?

html - 如何在一排 Bootstrap 中将两列中带有按钮的列居中?

html - (HTML & CSS) 当选中另一个复选框时如何显示一个复选框

javascript - 使用 Axios 从 http 响应下载 PDF

android - 从URI获取真实路径,Android KitKat新存储访问框架

android - 使用 View.GenerateViewId 创建 ID 时如何查找带 ID 的 TextView

java - 启动应用程序时在 Android 上找不到类异常

javascript - JQuery '$' 在我的 .JS 文件中得到 "ReferenceError: $ is not defined"

c - 与 HTTP 1.0 相比,HTTP 1.1 延迟 20 秒

http - 如何使用 nginx 根据日期重定向?