第四章 网络下载之httpurlconnection 从网络上下载一张图片,在本地显示
2015-05-25 13:24
531 查看
没有对图片进行压缩,只适合小的图片。关于图片,最好进行压缩。
handler
从网络中获取图片的方法。
代码链接地址
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); } }
代码链接地址
相关文章推荐
- [置顶] Android开发之下载服务器上的一张图片到本地java代码实现HttpURLConnection
- Android开发之下载服务器上的一张图片到本地java代码实现HttpURLConnection
- 0314-使用HttpURLConnection下载网络图片并显示
- 使用HttpURLConnection下载网络图片并显示
- Android HttpURLConnection获取网络下载图片POST请求方式
- Android使用HttpURLConnection显示网络图片
- AsyncTask与HttpURLConnection下载网络图片
- 使用HttpURLConnection下载网络图片
- android 如何使用httpurlconnection下载一张图片demo
- android-HttpURLConnection+Handler+Thread下载图片并显示
- HttpURLConnection下载网络图片
- HttpURLConnection获取网络读片,读取本地缓存图片
- 关于HttpUrlConnection加载和下载网络图片的学习
- 使用HttpURLConnection实现图片的下载与现显示
- HttpURLConnection下载网络图片
- 【Android进阶】使用HttpURLConnection实现图片的下载与现显示
- android httpUrlConnection 方式从网络上面下载图片
- Android - HttpURLConnection下载网络文件,加载网络图片
- 练习URL进行网络编程-HttpURLConnection显示外部图片
- 使用HttpURLConnection从网络中下载图片