您的位置:首页 > 理论基础 > 计算机网络

第四章 网络下载之httpurlconnection 从网络上下载一张图片,在本地显示

2015-05-25 13:24 531 查看
没有对图片进行压缩,只适合小的图片。关于图片,最好进行压缩。

handler

private Handler handler = new Handler() {
public void handleMessage(Message msg) {
switch (msg.what) {
case SHOW:
imageView.setImageBitmap(myimage);
break;

default:
break;
}

};
};
button点击事件。

// button点击事件。
public void getImage(View v) {

new Thread(new Runnable() {

@Override
public void run() {
try {
//bitmap 是对象
myimage = myImageUtil.getImage(mystring);
Message msg = Message.obtain();
msg.what = SHOW;
handler.sendMessage(msg);
} catch (Exception e) {
e.printStackTrace();
}

}
}).start();


从网络中获取图片的方法。

public Bitmap getImage(String address) throws Exception {
// 1.获取url对象
URL url = new URL(address);
// 获取con对象

HttpURLConnection httpURLConnection=(HttpURLConnection)url.openConnection();
httpURLConnection.setReadTimeout(3000);
httpURLConnection.setConnectTimeout(6 * 1000); // 别超过6秒
myfile = new File(context.getCacheDir(), URLEncoder.encode(address));
if (myfile.exists()) {
httpURLConnection.setIfModifiedSince(myfile.lastModified());
}
int responseCode = httpURLConnection.getResponseCode();
if (responseCode==200) {
InputStream inputStream = httpURLConnection.getInputStream();
mybitmap = BitmapFactory.decodeStream(inputStream);
//yibu 开启一个线程存储到本地

new Thread(new Runnable() {

@Override
public void run() {
// TODO Auto-generated method stub
FileOutputStream fileOutputStream = null;
try {
fileOutputStream = new FileOutputStream(myfile);
//fileOutputStream.write(data);
mybitmap.compress(CompressFormat.JPEG,30, fileOutputStream);
fileOutputStream.close();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

}
}).start();

return mybitmap;
}

else if (responseCode==304) {
String pathName=myfile.getAbsolutePath();
mybitmap=BitmapFactory.decodeFile(pathName);
return mybitmap;
}
else
{   throw new NetworkErrorException("fang wen chu cuo"+responseCode); }
}

代码链接地址
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息