我希望能够在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中添加Internet权限:
<uses-permission android:name="android.permission.INTERNET" />
在进行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-httpclient 和 http://www.androidsnippets.com/get-the-content-from-a-httpresponse-or-any-inputstream-as-a-string
TextView yourTextView = (TextView) findViewById(R.id.NameOfYourTextView);
然后,您可以调用方法 yourTextView.setText("The HTML code");
来设置文本内容。另外,请查看下面的答案以提取HTML代码。 - KirilInputStream is =InputStream getInputStreamFromUrl("http://google.com");
String htmlText = inputStreamToString(is);
mTextView.setText(Html.fromHtml(htmlText));
但网络请求应该在单独的线程/异步任务中执行 :)