android 获取网络资源

时间:2022-11-26 11:06:28
 

 1、 Android获取网络图片
下面来写一个小程序来说明:

 

首先是资源文件:

<resources>

    <string name="app_name">Net</string>

    <string name="btn_text">显示网络数据</string>

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

</resources>

 

然后就是布局文件:

<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:layout_width="fill_parent"

    android:layout_height="wrap_content"

    android:text="@string/btn_text"

    android:id="@+id/showImageBtn"/>

 

  <ImageView

      android:layout_width="wrap_content"

      android:layout_height="wrap_content"

      android:id="@+id/imageView"/>

</LinearLayout>

 

 

在就是:Activity

 

public class NetActivity extends Activity implements OnClickListener {

    Button btn;

    ImageView imgView;

 

    public void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);

        setContentView(R.layout.img_layout);

        findViews();

     

    }

    private void findViews() {

       btn = (Button) this.findViewById(R.id.showImageBtn);

        imgView = (ImageView) this.findViewById(R.id.imageView);

        btn.setOnClickListener(this);

    }

   

    public void onClick(View v) {

 

// 获取图片的地址     

String path=

"http://img.nie.163.com/images/2011/12/20/2011-12-20_144791.jpg";

       try {

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

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

           imgView.setImageBitmap(bitmap); 

        } catch (Exception e) {

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

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

       }

      }

}

 

最后是:ImageService类

 

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;

    }

}

效果如图: