• Java-->利用URL类下载图片


    --> 通过get 请求访问图片地址,将通过服务器响应的数据(即图片数据)存到本地文件中...

    --> HttpURLConnectionUtil 工具类

    package com.dragon.java.downloadpic;
    
    import java.io.BufferedInputStream;
    import java.io.BufferedOutputStream;
    import java.io.File;
    import java.io.FileOutputStream;
    import java.io.IOException;
    import java.io.InputStream;
    import java.net.HttpURLConnection;
    import java.net.URL;
    
    public class HttpURLConnectionUtil {
            // 通过get请求得到读取器响应数据的数据流
        public static InputStream getInputStreamByGet(String url) {
            try {
                HttpURLConnection conn = (HttpURLConnection) new URL(url)
                        .openConnection();
                conn.setReadTimeout(5000);
                conn.setConnectTimeout(5000);
                conn.setRequestMethod("GET");
    
                if (conn.getResponseCode() == HttpURLConnection.HTTP_OK) {
                    InputStream inputStream = conn.getInputStream();
                    return inputStream;
                }
    
            } catch (IOException e) {
                e.printStackTrace();
            }
            return null;
        }
    
            // 将服务器响应的数据流存到本地文件
        public static void saveData(InputStream is, File file) {
            try (BufferedInputStream bis = new BufferedInputStream(is);
                    BufferedOutputStream bos = new BufferedOutputStream(
                            new FileOutputStream(file));) {
                byte[] buffer = new byte[1024];
                int len = -1;
                while ((len = bis.read(buffer)) != -1) {
                    bos.write(buffer, 0, len);
                    bos.flush();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    --> Test 测试类

    package com.dragon.java.downloadpic;
    
    import java.io.File;
    import java.io.InputStream;
    
    /*
     * 1. 从下面的地址下载图片,并保存在文件中。
     http://img.coocaa.com/www/attachment/forum/201602/16/085938u86ewu4l8z6flr6w.jpg
     *要求:封装相应的工具类*
     */
    public class Test {
        public static void main(String[] args) {
            String url = "http://img.coocaa.com/www/attachment/forum/201602/16/085938u86ewu4l8z6flr6w.jpg";

          String[] split = url.split("\/");
          String fileName = split[split.length - 1];
          File file = new File("f:/", fileName);

            InputStream inputStream = HttpURLConnectionUtil
                    .getInputStreamByGet(url);
            HttpURLConnectionUtil.saveData(inputStream, file);
        }
    }

    --> URL 类的简单应用...

  • 相关阅读:
    视觉里程计VO-直接法
    Linux安装libcholmod-dev找不到的解决方法
    Levenberg-Marquadt Method
    Gauss-Newton Method
    CMake
    方差 标准差 协方差
    SFM
    矩阵分解
    kvm学习笔记
    python学习笔记
  • 原文地址:https://www.cnblogs.com/xmcx1995/p/5799222.html
Copyright © 2020-2023  润新知