Android访问网络图片部分代码

 

	// 类 URL 代表一个统一资源定位符,它是指向互联网“资源”的指针。
		URL url = new URL("http://www.sohu.com/");
		// 每个 HttpURLConnection 实例都可用于生成单个请求,
		//但是其他实例可以透明地共享连接到 HTTP 服务器的基础网络
		HttpURLConnection conn = (HttpURLConnection) url.openConnection();
		//设置 URL 请求的方法
		conn.setRequestMethod("GET");
		//设置一个指定的超时值(以毫秒为单位),
		//该值将在打开到此 URLConnection 引用的资源的通信链接时使用。
		conn.setConnectTimeout(5 * 1000);
		// conn.getInputStream()返回从此打开的连接读取的输入流
		InputStream inStream = conn.getInputStream();// 通过输入流获取html数据
		byte[] data = readInputStream(inStream);// 得到html的二进制数
                  File imageFile = new File("baidu.jpg");
                  FileOutputStream outStream = new FileOutputStream(imageFile);
                  outStream.write(data);
                  outStream.close();
                  System.out.println("完成!");



用到的函数readInputStream():

public static byte[] readInputStream(InputStream inStream) throws Exception {
		//此类实现了一个输出流,其中的数据被写入一个 byte 数组
		ByteArrayOutputStream outStream = new ByteArrayOutputStream();
		// 字节数组
		byte[] buffer = new byte[1024];
		int len = 0;
		//从输入流中读取一定数量的字节,并将其存储在缓冲区数组 b 中
		while ((len = inStream.read(buffer)) != -1) {
			// 将指定 byte 数组中从偏移量 off 开始的 len 个字节写入此输出流
			outStream.write(buffer, 0, len);
		}
		inStream.close();
		//toByteArray()创建一个新分配的 byte 数组。
		return outStream.toByteArray();
	}


 

 

 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值