Android获取网页源代码
1、首先在AndroidManifest中加入Internet权限:
- <!-- 访问网络的权限 -->
- <uses-permission android:name="android.permission.INTERNET"/>
|
2、Activity中得代码如下:
- public class GetHtmlCodeActivity extends Activity {
- @Override
- public void onCreate(Bundle savedInstanceState) {
- super.onCreate(savedInstanceState);
- setContentView(R.layout.main);
-
- TextView textView = (TextView)this.findViewById(R.id.picture_textview);
- try {
- textView.setText(getPictureData("http://www.baidu.com"));
- } catch (Exception e) {
- Log.e("GetHtmlCodeActivity", e.toString());
- Toast.makeText(GetHtmlCodeActivity.this, "网络连接失败", 1).show();
- }
- }
-
- public String getPictureData(String path) throws Exception{
-
- URL url = new URL("http://www.baidu.com/");
-
-
- HttpURLConnection conn = (HttpURLConnection) url.openConnection();
-
- conn.setRequestMethod("GET");
-
-
- conn.setConnectTimeout(5 * 1000);
-
- InputStream inStream = conn.getInputStream();
- byte[] data = readInputStream(inStream);
- String html = new String(data);
- return html;
-
- }
-
- public byte[] readInputStream(InputStream inStream) throws Exception{
-
- ByteArrayOutputStream outStream = new ByteArrayOutputStream();
-
- byte[] buffer = new byte[1024];
- int len = 0;
-
- while ((len = inStream.read(buffer)) != -1) {
-
- outStream.write(buffer, 0, len);
- }
- inStream.close();
-
- return outStream.toByteArray();
- }
- }
|
评论暂时关闭