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
65
66
67
68
package com.by4cloud.platformx.business.utils;
 
import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Base64;
 
public class NetworkFileToBase64 {
 
    /**
     * 将网络地址的文件转换为 Base64 字符串
     *
     * @param fileUrl 网络文件的 URL 地址
     * @return Base64 编码字符串,失败返回 null
     */
    public static String convertNetworkFileToBase64(String fileUrl) {
        InputStream inputStream = null;
        ByteArrayOutputStream outputStream = null;
 
        try {
            // 1. 创建 URL 对象
            URL url = new URL(fileUrl);
 
            // 2. 打开连接
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
 
            // 3. 设置请求属性和超时时间(防止长时间挂起)
            conn.setRequestMethod("GET");
            conn.setConnectTimeout(5000); // 连接超时 5秒
            conn.setReadTimeout(10000);   // 读取超时 10秒
 
            // 4. 获取输入流
            int responseCode = conn.getResponseCode();
            if (responseCode != HttpURLConnection.HTTP_OK) {
                System.err.println("HTTP 错误代码: " + responseCode);
                return null;
            }
 
            inputStream = conn.getInputStream();
            outputStream = new ByteArrayOutputStream();
 
            // 5. 读取数据到内存
            byte[] buffer = new byte[1024];
            int len;
            while ((len = inputStream.read(buffer)) != -1) {
                outputStream.write(buffer, 0, len);
            }
 
            // 6. 获取字节数组并编码
            byte[] fileBytes = outputStream.toByteArray();
            return Base64.getEncoder().encodeToString(fileBytes);
 
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        } finally {
            // 7. 关闭资源
            try {
                if (inputStream != null) inputStream.close();
                if (outputStream != null) outputStream.close();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
 
}