mitao
2025-01-21 19ce15ddb66af0fb0b2e447bd70dd39e08bb30fd
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
package com.ruoyi.common.core.utils;
 
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
 
public class UrlDownloader {
 
    /**
     * 将指定的URL内容下载为输入流
     *
     * @param urlString 要下载的URL
     * @return 包含URL内容的输入流
     * @throws IOException 如果发生I/O错误
     */
    public static InputStream downloadAsStream(String urlString) throws IOException {
        // 找到最后一个斜杠的位置
        int lastSlashIndex = urlString.lastIndexOf("/");
        // 从斜杠后提取文件名
        String baseUrl = urlString.substring(0, lastSlashIndex);
        String fileName = urlString.substring(lastSlashIndex + 1);
        String encode = URLEncoder.encode(fileName, "UTF-8");
        urlString = baseUrl + "/" + encode;
        URL url = new URL(urlString);
        HttpURLConnection connection = (HttpURLConnection) url.openConnection();
        connection.setRequestMethod("GET");
        connection.connect();
 
        // 检查HTTP响应码
        int responseCode = connection.getResponseCode();
        if (responseCode != HttpURLConnection.HTTP_OK) {
            throw new IOException("HTTP response code: " + responseCode);
        }
 
        return connection.getInputStream();
    }
 
    public static void main(String[] args) throws UnsupportedEncodingException {
        String urlString = "http://192.168.110.188:9300/statics/2025/01/21/身份证人像面_20250121171827A014.png"; // 替换为你要下载的URL
        //将路径中的中文进行编码
        //String urlString = "http://192.168.110.188:9300/statics/2025/01/21/%E8%BA%AB%E4%BB%BD%E8%AF%81%E4%BA%BA%E5%83%8F%E9%9D%A2_20250121171827A014.png";
        // 找到最后一个斜杠的位置
        int lastSlashIndex = urlString.lastIndexOf("/");
        // 从斜杠后提取文件名
        String baseUrl = urlString.substring(0, lastSlashIndex);
        String fileName = urlString.substring(lastSlashIndex + 1);
        String encode = URLEncoder.encode(fileName, "UTF-8");
        urlString = baseUrl + "/" + encode;
        try (InputStream inputStream = downloadAsStream(urlString)) {
            // 这里你可以处理输入流,例如将其写入文件或进行其他操作
            byte[] buffer = new byte[1024];
            int bytesRead;
            while ((bytesRead = inputStream.read(buffer)) != -1) {
                // 处理读取的数据,例如写入文件或打印到控制台
                System.out.write(buffer, 0, bytesRead);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}