Android开发之获取网络数据


Android开发之获取网络数据

获取网络图片

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

  1. <?xml version="1.0" encoding="utf-8"?>  
  2.   
  3. <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"  
  4.   
  5.     android:layout_width="fill_parent"  
  6.   
  7.     android:layout_height="fill_parent"  
  8.   
  9.     android:orientation="vertical" >  
  10.   
  11.    
  12.   
  13.     <Button  
  14.   
  15.         android:id="@+id/showImageID"  
  16.   
  17.         android:layout_width="wrap_content"  
  18.   
  19.         android:layout_height="wrap_content"  
  20.   
  21.         android:text="@string/btn" />  
  22.   
  23. //用来点击事件  
  24.   
  25.    
  26.   
  27.     <ImageView  
  28.   
  29.         android:id="@+id/imageViewID"  
  30.   
  31.         android:layout_width="wrap_content"  
  32.   
  33.         android:layout_height="wrap_content" />  
  34.   
  35. //用来显示图片  
  36.   
  37.    
  38.   
  39. </LinearLayout>  

接下来我们需要添加ImageService类

  1. package cn.class3g.service;  
  2.   
  3.    
  4.   
  5. import java.io.ByteArrayOutputStream;  
  6.   
  7. import java.io.InputStream;  
  8.   
  9. import java.net.HttpURLConnection;  
  10.   
  11. import java.net.URL;  
  12.   
  13.    
  14.   
  15. public class ImageService {  
  16.   
  17.    public static byte[] getImageData(String path) throws Exception {  
  18.   
  19.       URL url = new URL(path);  
  20.   
  21.    
  22.   
  23.       HttpURLConnection conn = (HttpURLConnection) url.openConnection();  
  24.   
  25.    
  26.   
  27.       conn.setRequestMethod("GET");  
  28.   
  29.    
  30.   
  31.       conn.setConnectTimeout(5000);  
  32.   
  33.    
  34.   
  35.       InputStream inStream = conn.getInputStream();  
  36.   
  37.    
  38.   
  39.       ByteArrayOutputStream bos = new ByteArrayOutputStream();  
  40.   
  41.    
  42.   
  43.       byte[] buffer = new byte[1024];  
  44.   
  45.       int len = 0;  
  46.   
  47.       while ((len = inStream.read(buffer)) != -1) {  
  48.   
  49.         bos.write(buffer, 0, len);  
  50.   
  51.       }  
  52.   
  53.    
  54.   
  55.       byte[] data = bos.toByteArray();  
  56.   
  57.    
  58.   
  59.       return data;  
  60.   
  61.    
  62.   
  63.    }  
  64.   
  65. }  
  • 1
  • 2
  • 下一页

相关内容