我想在android中获取网页的html代码。网页网址将在编辑文本框中显示,然后当用户点击该按钮时,文本视图将显示该网页的代码。请解释并提供代码!
任何帮助将不胜感激!
答案 0 :(得分: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/
Is it possible to get the HTML code from WebView
How to get the html-source of a page from a html link in android?
答案 1 :(得分: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-any-inputstream-as-a-string
答案 2 :(得分:-1)
使用上面的代码,并将其设置为如下文本视图:
InputStream is =InputStream getInputStreamFromUrl("http://google.com");
String htmlText = inputStreamToString(is);
mTextView.setText(Html.fromHtml(htmlText));
但是在单独的线程/ asynctask中执行网络请求:)