//代碼很簡單,不做什麼解釋
//圖片的獲取。
//main.xml
- <?xml version="1.0" encoding="utf-8"?>
- <LinearLayout xmlns:Android="http://schemas.android.com/apk/res/android"
- android:layout_width="fill_parent"
- android:layout_height="fill_parent"
- android:orientation="vertical" >
-
- <TextView
- android:layout_width="fill_parent"
- android:layout_height="wrap_content"
- android:text="@string/request" />
- <EditText
- android:id="@+id/imageaddress"
- android:layout_width="fill_parent"
- android:layout_height="wrap_content"
- />
- <Button
- android:id="@+id/getimagebutton"
- android:layout_width="wrap_content"
- android:layout_height="wrap_content"
- android:text="@string/getimage"
- />
- <ImageView
- android:id="@+id/imageview"
- android:layout_width="wrap_content"
- android:layout_height="wrap_content"
- />
-
- </LinearLayout>
//strings.xml
- <?xml version="1.0" encoding="utf-8"?>
- <resources>
-
- <string name="request">重網絡獲取圖片</string>
- <string name="app_name">網絡獲取圖片數據</string>
- <string name="getimage">得到圖片</string>
- <string name="requestout">請求超時</string>
-
- </resources>
//GetImageService.java 業務類
- package sn.len.service;
-
- import java.io.IOException;
- import java.io.InputStream;
- import java.net.HttpURLConnection;
- import java.net.URL;
-
- import sn.len.util.ImageByte;
-
- public class GetImageService
- {
- public static byte[] imageByte(String path) throws IOException
- {
- URL url=new URL(path);
- HttpURLConnection con=(HttpURLConnection)url.openConnection();
- con.setRequestMethod("GET");
- con.setConnectTimeout(5*1000);
- InputStream inStream=con.getInputStream();
- byte imageData[]=ImageByte.getBtye(inStream);
- return imageData;
- }
- }
//ImageByte.java工具類
- package sn.len.util;
-
- import java.io.ByteArrayOutputStream;
- import java.io.IOException;
- import java.io.InputStream;
-
- public class ImageByte
- {
- public static byte[] getBtye(InputStream inStream) throws IOException
- {
- byte b[]=new byte[1024];
- ByteArrayOutputStream byteoutstream=new ByteArrayOutputStream();
- int len=0;
- while((len=inStream.read(b))!=-1)
- {
- byteoutstream.write(b,0,len);
- }
- return byteoutstream.toByteArray();
- }
- }