Linux教程網
Android開發之獲取網絡數據
獲取網絡圖片
首先我們需要把界面搭建好
- <?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" >
-
-
-
- <Button
-
- android:id="@+id/showImageID"
-
- android:layout_width="wrap_content"
-
- android:layout_height="wrap_content"
-
- android:text="@string/btn" />
-
- //用來點擊事件
-
-
-
- <ImageView
-
- android:id="@+id/imageViewID"
-
- android:layout_width="wrap_content"
-
- android:layout_height="wrap_content" />
-
- //用來顯示圖片
-
-
-
- </LinearLayout>
接下來我們需要添加ImageService類
- package cn.class3g.service;
-
-
-
- import java.io.ByteArrayOutputStream;
-
- import java.io.InputStream;
-
- import java.net.HttpURLConnection;
-
- import java.net.URL;
-
-
-
- public class ImageService {
-
- public static byte[] getImageData(String path) throws Exception {
-
- URL url = new URL(path);
-
-
-
- HttpURLConnection conn = (HttpURLConnection) url.openConnection();
-
-
-
- conn.setRequestMethod("GET");
-
-
-
- conn.setConnectTimeout(5000);
-
-
-
- InputStream inStream = conn.getInputStream();
-
-
-
- ByteArrayOutputStream bos = new ByteArrayOutputStream();
-
-
-
- byte[] buffer = new byte[1024];
-
- int len = 0;
-
- while ((len = inStream.read(buffer)) != -1) {
-
- bos.write(buffer, 0, len);
-
- }
-
-
-
- byte[] data = bos.toByteArray();
-
-
-
- return data;
-
-
-
- }
-
- }
Copyright ©
Linux教程網 All Rights Reserved