歡迎來到Linux教程網
Linux教程網
Linux教程網
Linux教程網
Linux教程網 >> Linux編程 >> Linux編程 >> Android開發之獲取網絡數據

Android開發之獲取網絡數據

日期:2017/3/1 10:45:18   编辑:Linux編程

Android開發之獲取網絡數據

獲取網絡圖片

首先我們需要把界面搭建好

  1. <?xml version="1.0" encoding="utf-8"?>
  2. <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
  3. android:layout_width="fill_parent"
  4. android:layout_height="fill_parent"
  5. android:orientation="vertical" >
  6. <Button
  7. android:id="@+id/showImageID"
  8. android:layout_width="wrap_content"
  9. android:layout_height="wrap_content"
  10. android:text="@string/btn" />
  11. //用來點擊事件
  12. <ImageView
  13. android:id="@+id/imageViewID"
  14. android:layout_width="wrap_content"
  15. android:layout_height="wrap_content" />
  16. //用來顯示圖片
  17. </LinearLayout>

接下來我們需要添加ImageService類

  1. package cn.class3g.service;
  2. import java.io.ByteArrayOutputStream;
  3. import java.io.InputStream;
  4. import java.net.HttpURLConnection;
  5. import java.net.URL;
  6. public class ImageService {
  7. public static byte[] getImageData(String path) throws Exception {
  8. URL url = new URL(path);
  9. HttpURLConnection conn = (HttpURLConnection) url.openConnection();
  10. conn.setRequestMethod("GET");
  11. conn.setConnectTimeout(5000);
  12. InputStream inStream = conn.getInputStream();
  13. ByteArrayOutputStream bos = new ByteArrayOutputStream();
  14. byte[] buffer = new byte[1024];
  15. int len = 0;
  16. while ((len = inStream.read(buffer)) != -1) {
  17. bos.write(buffer, 0, len);
  18. }
  19. byte[] data = bos.toByteArray();
  20. return data;
  21. }
  22. }
Copyright © Linux教程網 All Rights Reserved