android下载网络图片
来源:互联网 发布:网址导航手机版源码 编辑:程序博客网 时间:2024/04/27 11:24
- package com.home;
- import java.io.ByteArrayOutputStream;
- import java.io.File;
- import java.io.FileOutputStream;
- import java.io.InputStream;
- import java.net.HttpURLConnection;
- import java.net.URL;
- public class DownloadImage {
- public DownloadImage() {
- try {
- getImage();
- } catch (Exception e) {
- e.printStackTrace();
- }
- }
- public static void main(String[] args) {
- new DownloadImage();
- }
- /**
- * 读取网络图片
- *
- * @throws Exception
- */
- public void getImage() throws Exception {
- // 图片url路劲
- String urlpath = "http://pica.nipic.com/2008-05-23/200852381811521_2.jpg";
- // 建立URL对象,抛出异常
- URL url = new URL(urlpath);
- // 得到HttpURLConnection对象
- HttpURLConnection conn = (HttpURLConnection) url.openConnection();
- // 声明请求方式
- conn.setRequestMethod("GET");
- // 设置连接超时
- conn.setConnectTimeout(6 * 1000);
- // 连接成功
- if (conn.getResponseCode() == 200) {
- // 得到服务器传回来的数据,相对我们来说输入流
- InputStream inputStream = conn.getInputStream();
- // 得到数据
- byte[] data = readInStream(inputStream);
- // 创建保存文件
- File file = new File("C:/image.jpg");
- // 创建一个文件输出流
- FileOutputStream outputStream = new FileOutputStream(file);
- // 将我们所得的二进制数据全部写入我们建好的文件中
- outputStream.write(data);
- // 关闭输出流
- outputStream.close();
- }
- }
- /**
- * 读取流文件的内容
- *
- * @param inputStream
- * @return
- * @throws Exception
- */
- public byte[] readInStream(InputStream inputStream) throws Exception {
- ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
- // 声明缓冲区
- byte[] buffer = new byte[1024];
- // 定义读取默认长度
- int length = -1;
- while ((length = inputStream.read(buffer)) != -1) {
- // 把缓冲区中输出到内存中
- byteArrayOutputStream.write(buffer, 0, length);
- }
- // 关闭输出流
- byteArrayOutputStream.close();
- // 关闭输入流
- inputStream.close();
- // 返回这个输出流的字节数组
- return byteArrayOutputStream.toByteArray();
- }
- }
0 0
- android下载网络图片
- Android 网络下载图片
- Android:下载网络图片
- Android 下载网络图片
- Android 下载网络图片
- Android异步下载网络图片
- Android异步下载网络图片
- Android异步下载网络图片
- Android异步下载网络图片
- Android异步下载网络图片
- Android异步下载网络图片
- Android 多线程网络下载图片
- android 中下载网络图片
- Android异步下载网络图片
- Android下载网络图片资源
- Android Retrofit下载网络图片
- Android如何下载网络图片
- Android之网络下载与图片解码-----网络图片浏览器
- IO - 同步,异步,阻塞,非阻塞 (亡羊补牢篇)
- ONE源代码分析——movement1
- STL 之算法
- Android APK反编译详解(附图)
- 摘录5:走势终完美
- android下载网络图片
- apktool编译出错
- 台词
- 排序——插入排序法
- LUA常见库和工具
- 删除ssh默认known_hosts
- Unsupported compiler 'com.apple.compilers.llvmgcc42' selected for architecture 'armv7'
- Android使用socket使底层和framework通信
- 巧妙解决问题:&CMFCcodeDlg::RunCommands”创建指向成员的指针。MFC多线程调用要求调用的接口必须是全局函数或静态成员函数