歡迎來到Linux教程網
Linux教程網
Linux教程網
Linux教程網
Linux教程網 >> Linux編程 >> Linux編程 >> Android 網絡圖片獲取與網絡內容獲取

Android 網絡圖片獲取與網絡內容獲取

日期:2017/3/1 10:50:11   编辑:Linux編程

//代碼很簡單,不做什麼解釋

//圖片的獲取。

//main.xml

  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. <TextView
  7. android:layout_width="fill_parent"
  8. android:layout_height="wrap_content"
  9. android:text="@string/request" />
  10. <EditText
  11. android:id="@+id/imageaddress"
  12. android:layout_width="fill_parent"
  13. android:layout_height="wrap_content"
  14. />
  15. <Button
  16. android:id="@+id/getimagebutton"
  17. android:layout_width="wrap_content"
  18. android:layout_height="wrap_content"
  19. android:text="@string/getimage"
  20. />
  21. <ImageView
  22. android:id="@+id/imageview"
  23. android:layout_width="wrap_content"
  24. android:layout_height="wrap_content"
  25. />
  26. </LinearLayout>
//strings.xml
  1. <?xml version="1.0" encoding="utf-8"?>
  2. <resources>
  3. <string name="request">重網絡獲取圖片</string>
  4. <string name="app_name">網絡獲取圖片數據</string>
  5. <string name="getimage">得到圖片</string>
  6. <string name="requestout">請求超時</string>
  7. </resources>
//GetImageService.java 業務類
  1. package sn.len.service;
  2. import java.io.IOException;
  3. import java.io.InputStream;
  4. import java.net.HttpURLConnection;
  5. import java.net.URL;
  6. import sn.len.util.ImageByte;
  7. public class GetImageService
  8. {
  9. public static byte[] imageByte(String path) throws IOException
  10. {
  11. URL url=new URL(path);
  12. HttpURLConnection con=(HttpURLConnection)url.openConnection();
  13. con.setRequestMethod("GET");
  14. con.setConnectTimeout(5*1000);
  15. InputStream inStream=con.getInputStream();
  16. byte imageData[]=ImageByte.getBtye(inStream);
  17. return imageData;
  18. }
  19. }
//ImageByte.java工具類
  1. package sn.len.util;
  2. import java.io.ByteArrayOutputStream;
  3. import java.io.IOException;
  4. import java.io.InputStream;
  5. public class ImageByte
  6. {
  7. public static byte[] getBtye(InputStream inStream) throws IOException
  8. {
  9. byte b[]=new byte[1024];
  10. ByteArrayOutputStream byteoutstream=new ByteArrayOutputStream();
  11. int len=0;
  12. while((len=inStream.read(b))!=-1)
  13. {
  14. byteoutstream.write(b,0,len);
  15. }
  16. return byteoutstream.toByteArray();
  17. }
  18. }
Copyright © Linux教程網 All Rights Reserved