我想在android中获取网页的html代码。该网页的网址将在编辑文本框中给出,然后当用户点击该按钮时,文本视图将显示该网页的代码。请解释并给出代码!android-如何在android中获取网页的html代码?
任何帮助,将不胜感激!
我想在android中获取网页的html代码。该网页的网址将在编辑文本框中给出,然后当用户点击该按钮时,文本视图将显示该网页的代码。请解释并给出代码!android-如何在android中获取网页的html代码?
任何帮助,将不胜感激!
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();
不要忘记添加Internet权限在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?
您需要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
你能告诉如何将html代码显示到textview中吗?我试过了,它没有奏效!它意外停止! @Kiril –
我假设你已经在布局中定义了一个TextView。现在你可以通过使用TextView yourTextView =(TextView)findViewById(R.id.NameOfYourTextView)来访问TextView;'之后你可以调用方法'yourTextView.setText(“HTML code”);' 编辑:同时请查看下面的提取HTML代码的答案 – Kiril
@Kiril - 我如何得到一些网页的html源代码?如果我获得完整的源页面,它可能会花费很多时间,我不需要获得所有的线路,你能帮助我吗? thx非常 –
使用上面的代码,并将其设置为像这样的文本视图:
InputStream is =InputStream getInputStreamFromUrl("http://google.com");
String htmlText = inputStreamToString(is);
mTextView.setText(Html.fromHtml(htmlText));
但做网络请求在一个单独的线程/ asynctask :)
工作就像一个魅力! :)谢谢:D –
我如何得到一些网页的html源代码?如果我获得完整的源页面,它可能会花费很多时间,我不需要获得所有的线路,你能帮助我吗? thx非常多 –