[置顶] 获取网络数据

J2SE实现网络图片的获取

public static void main(String[] args) throws Exception {

       String path = "http://t3.baidu.com/it/u=1786103592,4245522417&fm=0&gp=0.jpg";

      

       URL url = new URL(path);

      

       HttpURLConnection conn = (HttpURLConnection) url.openConnection();

       conn.setRequestMethod("GET");

       conn.setConnectTimeout(5*1000);

       InputStream inStream = conn.getInputStream();

      

       ByteArrayOutputStream outStream = newByteArrayOutputStream();

       byte[] buffer = new byte[1024];

      

       int len=0;

       while((len=inStream.read(buffer))!=-1){

           outStream.write(buffer,0,len);

       }

      

       byte[] data = outStream.toByteArray();

      

       File f = new File("pic.jpg");

       FileOutputStream fos = new FileOutputStream(f);

       fos.write(data);

       fos.close();

    }

Androd中获取网络图片

<string name="btn_text">显示网络图片</string>

    <string name="error">下载图片失败!!</string>

<Button

        android:layout_width="fill_parent"

        android:layout_height="wrap_content"

        android:text="@string/btn_text"

        android:id="@+id/showBtn"

        />

   

    <ImageView

        android:layout_width="wrap_content"

        android:layout_height="wrap_content"

        android:id="@+id/imageView"

        />  

添加ImageService类

package cn.class3g.service;

public class ImageService {

    public static byte[] getImage(Stringpath) throws Exception{

       URL url = new URL(path);

       //get //post

       HttpURLConnection conn =(HttpURLConnection)url.openConnection();

       conn.setRequestMethod("GET");

       conn.setConnectTimeout(5*1000);

       InputStream inStream = conn.getInputStream();

      

       ByteArrayOutputStream outStream = new ByteArrayOutputStream();

       byte[] buffer = new byte[1024];

       int len = 0;

       while( (len = inStream.read(buffer)) !=-1 ){

           outStream.write(buffer, 0, len);

       }

       byte[] data = outStream.toByteArray();//图片的二进制数据

       outStream.close();

       inStream.close();

       return data;

    }

}

Activity

public void onClick(View v) {

       String path = "http://t3.baidu.com/it/u=1786103592,4245522417&fm=0&gp=0.jpg";

 

       try {

           byte[] data = ImageService.getImage(path);

 

           Bitmap bitmap = BitmapFactory.decodeByteArray(data,0, data.length);

           imgView.setImageBitmap(bitmap);

          

       } catch (Exception e) {

//         e.printStackTrace();

           Log.e("TAG", e.toString());

           Toast.makeText(this, R.string.error, 1).show();

       }

    }

[置顶] 获取网络数据_第1张图片http://t3.baidu.com/it/u=1786103592,4245522417&fm=0&gp=0.jpg

你可能感兴趣的:([置顶] 获取网络数据)