java下载图片(通用)httpClient,io流

java下载图片(通用)httpClient,io流

废话不多说,直接干!!!。

httpClient下载图片

 public static void downImage(CloseableHttpClient client, String imgUrl, String savePath) {
        HttpGet request = new HttpGet(imgUrl);
        // 设置请求超时和传输超时
        RequestConfig requestConfig = RequestConfig.custom()
                .setSocketTimeout(50000).setConnectTimeout(50000).build();

        //伪造请求头
        request.setHeader("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/68.0.3440.75 Safari/537.36");
        request.setConfig(requestConfig);


     // 报错PKIX path building failed   不验证证书添加下面注释语句
     /*   try {
            SSLContext sslcontext = SSLContexts.custom().loadTrustMaterial(null, new TrustSelfSignedStrategy()).build();
            SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslcontext, new String[]{"TLSv1"}, null, SSLConnectionSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
            client = HttpClients.custom().setSSLSocketFactory(sslsf).build();
        } catch (Exception e) {
            e.printStackTrace();
        }*/

            try {
                CloseableHttpResponse response = client.execute(request);
                if (HttpStatus.SC_OK == response.getStatusLine().getStatusCode()) {
                    HttpEntity entity = response.getEntity();
                    InputStream in = entity.getContent();
                    FileUtils.copyInputStreamToFile(in, new File(savePath));
                    System.out.println("下载成功:" + imgUrl);
                }
            } catch (Exception e) {
                e.printStackTrace();
                throw new RuntimeException(e);
            } finally {
                request.releaseConnection();

            }
        }


我们测试一下:

public static void main(String[] args) {
        CloseableHttpClient client =null;
        try {
            client =   HttpClients.createDefault();//写循环外
            downImage(client,"http://www.XXXX.com.cn/uploadfile/ftpfile/XXX.png", "E:/image/1478150765619314881279.PNG");
        } catch (Exception e) {
            e.printStackTrace();
        }finally{
            if(client!=null){
                try {
                    client.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }

    }

io流下载

public class ImageDownload {
    public static boolean httpDownload(String httpUrl, String saveFile) {
        // 1.下载网络文件
        int byteRead;
        URL url;
        try {
            url = new URL(httpUrl);
        } catch (MalformedURLException e1) {
            e1.printStackTrace();
            return false;
        }

        try {
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            //2.获取链接
            //  URLConnection conn = url.openConnection();
            if (conn.getResponseCode() == 404) {
                System.out.println("状态码呱啦啦啦啦啦啦啦啦==" + url);
                return false;
            }

            //3.输入流
            InputStream inStream = conn.getInputStream();
            //3.写入文件

            File file = new File(saveFile);
            if (!file.exists()) {
                //先得到文件的上级目录,并创建上级目录,在创建文件
                file.getParentFile().mkdir();
                try {
                    //创建文件
                    file.createNewFile();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            FileOutputStream fs = new FileOutputStream(file);

            byte[] buffer = new byte[1024];
            while ((byteRead = inStream.read(buffer)) != -1) {
                fs.write(buffer, 0, byteRead);
            }

            inStream.close();
            fs.close();
            return true;
        } catch (FileNotFoundException e) {
            System.out.println("文件找不到呱啦啦啦啦啦啦啦啦==" + url);
            e.printStackTrace();
            return false;
        } catch (IOException e) {
            System.out.println("IO呱啦啦啦啦啦啦啦啦==" + url);
            e.printStackTrace();
            return false;
        }
    }


}

测试一下:

public static void main(String[] args) {
        ImageDownload.httpDownload("http://www.xxxxx.cn/uploadfile/ftpfile/xxxxx.png,", "E:\\image\\xxxx.PNG");
    }

ok!!!

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值