Java如何使用 HTTP 请求下载图片

工具类:

java 复制代码
    public FileInputStream fileDownload(String fileLink) throws Exception {
        System.out.println("==============开始下载"+fileLink);
        // 转码中文
        URL url = new URL(encodeURLChinese(fileLink));
        System.out.println("fileLink:======================"+url);
        // 开始下载
        TrustStrategy acceptingTrustStrategy = (chain, authType) -> true;
        SSLContext sslContext = SSLContexts.custom().loadTrustMaterial(null, acceptingTrustStrategy).build();
        SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslContext, NoopHostnameVerifier.INSTANCE);
        HttpClientBuilder clientBuilder = HttpClients.custom();
        CloseableHttpClient httpClient = clientBuilder.setSSLSocketFactory(sslsf).build();
        HttpComponentsClientHttpRequestFactory httpRequestFactory = new HttpComponentsClientHttpRequestFactory();
        httpRequestFactory.setConnectTimeout(30000);
        httpRequestFactory.setConnectionRequestTimeout(30000);
        httpRequestFactory.setReadTimeout(30000);
        httpRequestFactory.setHttpClient(httpClient);
        RestTemplate template = new RestTemplate(httpRequestFactory);
        // 避免二次转码
        DefaultUriBuilderFactory uriBuilderFactory = new DefaultUriBuilderFactory();
        uriBuilderFactory.setEncodingMode(DefaultUriBuilderFactory.EncodingMode.NONE);
        template.setUriTemplateHandler(uriBuilderFactory);
        HttpHeaders headers = new HttpHeaders();
        HttpEntity<org.springframework.core.io.Resource> httpEntity = new HttpEntity<org.springframework.core.io.Resource>(headers);
        ResponseEntity<byte[]> response = template.exchange(url.toString(), HttpMethod.GET,
                httpEntity, byte[].class);

        byte[] body = response.getBody();
        // 创建临时文件
        File tempFile = File.createTempFile("temp", ".png");

        // 将 byte[] 写入临时文件
        try (FileOutputStream fos = new FileOutputStream(tempFile)) {
            if (body != null) {
                fos.write(body);
            }
        }
        // 创建 FileInputStream 对象
        FileInputStream stream = new FileInputStream(tempFile);

        System.out.println("=============下载结束");
        // 最后,记得在使用完后删除临时文件
        tempFile.delete();
        return stream;
    }

    public  String encodeURLChinese(String url) {
        if (StringUtils.isEmpty(url)) {
            return null;
        }
        url = StringUtils.trim(url);
        try {
            if (!needEncoding(url)) {
                // 不需要编码
                return url;
            } else {
                // 需要编码
                String allowChars = ".!*'();:@&=+_\\-$,/?#\\[\\]{}|\\^~`<>%\"";
//              String  allowChars = ".!*'();:@&=+_\\-$,/?#\\[\\]{}|\\^~`<>%\"";
                // UTF-8 大写
                return encode(url, "UTF-8", allowChars, false);

            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

测试代码

java 复制代码
    @GetMapping("export")
    public WebResult<?> exportTeaAndStu() {
        try {
            String url = "https://6c6f-lowcode-9g7kjvsl444eff34-1304647831.tcb.qcloud.la/weda-uploader/7cafc8106cb7cddf27b11dc5c8673562-imageaaa.png?sign=70c4c8a6372fb8b8c743b996a4d1e7b0&t=1723021617";
            String aa = "http://localhost:1401/weda/myLecture/main/speaker/getPhotoByPhotoName?photoName=45550120240510094227.png";
            String fileName = "777";
            //通过链接返回一个输入流
            FileInputStream stream = fileDownload(url);

            minioUtil.uploadInputStream("mpbucket", "sjs/wdjz/zjrgl" + "/" + fileName + ".png", stream);

            return WebResult.ok();
        } catch (Exception e) {
            return WebResult.error(e.getMessage());
        }
    }
相关推荐
roshy30 分钟前
RPC 与http对比
网络协议·http·rpc
太阳的后裔33 分钟前
随笔一些用C#封装的控件
开发语言·c#
tianyuanwo34 分钟前
Rust语言组件RPM包编译原理与Cargo工具详解
开发语言·网络·rust·rpm
float_六七3 小时前
IntelliJ IDEA双击Ctrl的妙用
java·ide·intellij-idea
能摆一天是一天5 小时前
JAVA stream().flatMap()
java·windows
CodeCraft Studio5 小时前
PDF处理控件Aspose.PDF教程:使用 Python 将 PDF 转换为 Base64
开发语言·python·pdf·base64·aspose·aspose.pdf
零点零一5 小时前
VS+QT的编程开发工作:关于QT VS tools的使用 qt的官方帮助
开发语言·qt
颜如玉5 小时前
🤲🏻🤲🏻🤲🏻临时重定向一定要能重定向🤲🏻🤲🏻🤲🏻
java·http·源码
程序员的世界你不懂7 小时前
【Flask】测试平台开发,新增说明书编写和展示功能 第二十三篇
java·前端·数据库
星空寻流年7 小时前
设计模式第一章(建造者模式)
java·设计模式·建造者模式