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

没有对图片进行压缩,只适合小的图片。关于图片,最好进行压缩。

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); }
	}

代码链接地址


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值