1
luodangjia
2025-01-21 c6a78cee309fdc17b96e69f75cab275e98844544
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
package com.ruoyi.common.core.utils;
 
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
 
public class UrlDownloader {
 
    /**
     * 将指定的URL内容下载为输入流
     *
     * @param urlString 要下载的URL
     * @return 包含URL内容的输入流
     * @throws IOException 如果发生I/O错误
     */
    public static InputStream downloadAsStream(String urlString) throws IOException {
        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) {
        String urlString = "https://example.com/file.txt"; // 替换为你要下载的URL
 
        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();
        }
    }
}