android利用Http协议实现从网络上面获取图片的方法如下:
public Bitmap getWebPicture(String urlStr){
Bitmap bitmap = null;
try {
URL url=new URL(urlStr);
HttpURLConnection conn=(HttpURLConnection)url.openConnection();
conn.setRequestMethod("GET");
conn.setConnectTimeout(5000);
conn.connect();
InputStream is=conn.getInputStream();
byte[] buffer=new byte[1024];
int len=0;
ByteArrayOutputStream bos=new ByteArrayOutputStream();
while((len=is.read(buffer))!=-1){
bos.write(buffer, 0, len);
}
byte[] data=bos.toByteArray();
bitmap=BitmapFactory.decodeByteArray(data, 0, data.length);
bos.close();
is.close();
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return bitmap;
}
这里需要用到ImageView的这个方法android.widget.ImageView.setImageBitmap(Bitmap bm),比如下面这个
ImageView iv =new ImageView(this) ;
iv.setImageBitmap(getWebPicture("http://pic.xinqiubai.com/picture/10001/100014476/medium/100014476.jpg"));
最后不要忘记了在AndroidManifest.xml中添加下面这个权限:
<uses-permission android:name="android.permission.INTERNET"/>