java通过URL类下载图片

一、概述
URL(Uniform Resource Locator) :统一资源定位符,它表示 Internet 某一
资源 的地址。
它是一种具体的 URI ,即 URL 可以用来标识一个资源,而且还指明了如何 locate
这个资源。
通过 URL 我们可以访问 Internet 上的各种网络资源,比如最常见的 www ftp
站点。浏览器通过解析给定的 URL 可以在网络上查找相应的文件或其他资源。
URL 的基本结构由 5 部分组成:
< 传输协议 >://< 主机名 >:< 端口号 >/< 文件名 ># 片段名 ? 参数列表
二、通过URL下载图片
HttpsURLConnection httpsURLConnection = null;
        InputStream is = null;
        FileOutputStream fos = null;
        try {
            //1.创建URL对象
            URL url = new URL("https://img1.baidu.com/it/u=3009731526,373851691&fm=253&fmt=auto&app=138&f=JPEG?w=800&h=500");
            //2.与URL建立连接:首先要在一个 URL 对象上通过方法 openConnection() 生成对应的 URLConnection
            //对象。
            httpsURLConnection = (HttpsURLConnection) url.openConnection();
            httpsURLConnection.connect();
            //3.获取输入流,并创建输出流对象
            is = httpsURLConnection.getInputStream();
            fos = new FileOutputStream(new File("test.jpg"));
            //4.输出图片
            byte[] buffer = new byte[1024];
            int len;
            while ((len = is.read(buffer)) != -1) {
                fos.write(buffer, 0, len);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            //5.关闭资源
            try {
                if (is != null)
                    is.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
            try {
                if (fos != null)
                    fos.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
            if (httpsURLConnection != null)
                httpsURLConnection.disconnect();
        }

你可能感兴趣的:(服务器,网络)