安卓 - 如何在安卓设备中获取网页的HTML代码?

3
我希望能够在Android中获取网页的HTML代码。用户将在编辑文本框中提供网页URL,然后当用户单击按钮时,文本视图将显示该网页的代码。请解释并给出代码!
任何帮助都将不胜感激!
3个回答

2
HttpClient client = new DefaultHttpClient();
HttpGet request = new HttpGet(url);
HttpResponse response = client.execute(request);

String html = "";
InputStream in = response.getEntity().getContent();
BufferedReader reader = new BufferedReader(new InputStreamReader(in));
StringBuilder str = new StringBuilder();
String line = null;
while((line = reader.readLine()) != null)
{
    str.append(line);
}
in.close();
html = str.toString();

不要忘记在AndroidManifest中添加Internet权限:

不要忘记在AndroidManifest中添加Internet权限:

<uses-permission android:name="android.permission.INTERNET" /> 

你可以参考以下链接以获得更多帮助: 从 WebView 中提取 HTML 的方法 如何从 WebView 获取 HTML 代码 如何从 Android 中的 HTML 链接获取页面的 HTML 源代码

我该如何获取网页的部分HTML源代码?如果我获取整个源页面,可能需要很长时间,而且我不需要获取所有行,你能帮我吗?非常感谢。 - Milad gh

1

在进行HttpGet请求时,您需要一个HttpClient。然后,您可以读取该请求的内容。

此代码段提供了一个InputStream

  public static InputStream getInputStreamFromUrl(String url) {
  InputStream content = null;
  try {
    HttpClient httpclient = new DefaultHttpClient();
    HttpResponse response = httpclient.execute(new HttpGet(url));
    content = response.getEntity().getContent();
  } catch (Exception e) {
    Log.e("[GET REQUEST]", "Network exception", e);
  }
    return content;
}

这个方法返回 String

// Fast Implementation
private StringBuilder inputStreamToString(InputStream is) {
    String line = "";
    StringBuilder total = new StringBuilder();

    // Wrap a BufferedReader around the InputStream
    BufferedReader rd = new BufferedReader(new InputStreamReader(is));

    // Read response until the end
    while ((line = rd.readLine()) != null) { 
        total.append(line); 
    }

    // Return full string
    return total;
}

来源: http://www.androidsnippets.com/executing-a-http-get-request-with-httpclienthttp://www.androidsnippets.com/get-the-content-from-a-httpresponse-or-any-inputstream-as-a-string


你能告诉我如何将HTML代码显示在TextView中吗?我尝试过了,但它没有起作用!它意外停止了!@Kiril - Mohammad Areeb Siddiqui
1
我假设您已经在布局中定义了一个TextView。现在,您可以通过使用以下代码访问您的TextView:TextView yourTextView = (TextView) findViewById(R.id.NameOfYourTextView); 然后,您可以调用方法 yourTextView.setText("The HTML code"); 来设置文本内容。另外,请查看下面的答案以提取HTML代码。 - Kiril
@Kiril - 我该如何获取网页的某些HTML源代码行?如果我获取整个源页面,可能需要很长时间,而且我不需要获取所有行,你能帮我吗?非常感谢。 - Milad gh

-1
使用上述代码,并将其设置为像这样的文本视图:
InputStream is =InputStream getInputStreamFromUrl("http://google.com");
String htmlText = inputStreamToString(is);

mTextView.setText(Html.fromHtml(htmlText));

但网络请求应该在单独的线程/异步任务中执行 :)


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接