我想在android中获取网页的html代码。网页 url 将在编辑文本框中给出,然后当用户单击按钮时,文本视图将显示该网页的代码。请解释并给出代码!
任何帮助,将不胜感激!
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/
你需要一个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-任何输入流作为字符串
使用上面的代码,并将其设置为这样的文本视图:
InputStream is =InputStream getInputStreamFromUrl("http://google.com");
String htmlText = inputStreamToString(is);
mTextView.setText(Html.fromHtml(htmlText));
但在单独的线程/异步任务中执行网络请求:)