3

我想在android中获取网页的html代码。网页 url 将在编辑文本框中给出,然后当用户单击按钮时,文本视图将显示该网页的代码。请解释并给出代码!

任何帮助,将不胜感激!

4

3 回答 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 中添加互联网权限:

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

您可以参考这些链接以获得更多帮助:

http://lexandera.com/2009/01/extracting-html-from-a-webview/

是否可以从 WebView 获取 HTML 代码

如何从android中的html链接获取页面的html源?

于 2012-06-05T19:33:35.490 回答
1

你需要一个HttpClient来执行一个HttpGet请求。然后您可以阅读该请求的内容。

这个片段给你一个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-httpclient和http://www.androidsnippets.com/get-the-content-from-a-httpresponse-or-任何输入流作为字符串

于 2012-06-05T19:36:13.493 回答
-1

使用上面的代码,并将其设置为这样的文本视图:

InputStream is =InputStream getInputStreamFromUrl("http://google.com");
String htmlText = inputStreamToString(is);

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

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

于 2012-06-05T19:59:47.837 回答