java通过文件的url获取文件的base64
package org.Util;
import java.io.*;
import java.net.URL;
import java.net.URLConnection;
import java.util.Base64;
/**
* @author Hmoumou
* @DATE 2022/1/3
* @apiNote
* 通过文件的url链接
* 获取文件的base64
*/
import java.io.IOException;
import java.io.InputStream;
/**
* @Description 文件转base64
*/
class Base64Util {
/**
* 文件转base64
* 直接返回base64结果
* @param
* @return
*/
public static String encryptToBase64(String urlString) throws IOException {
// 构造URL
URL url = new URL(urlString);
// 打开连接
URLConnection con = url.openConnection();
//设置请求超时为5s
con.setConnectTimeout(5 * 1000);
// 输入流
InputStream is = con.getInputStream();
// 将图片文件转化为字节数组字符串,并对其进行Base64编码处理
byte[] data = null;
// 读取图片字节数组
try {
ByteArrayOutputStream swapStream = new ByteArrayOutputStream();
byte[] buff = new byte[100];
int rc = 0;
while ((rc = is.read(buff, 0, 100)) > 0) {
swapStream.write(buff, 0, rc);
}
data = swapStream.toByteArray();
} catch (IOException e) {
e.printStackTrace();
}
return Base64.getEncoder().encodeToString(data);
}
public static void main(String[] args) throws Exception {
for (int i = 1; i < 10; i++) {
String url = "https://smartdl.lenovo.com.cn/frontend/browser/hao.edge/image/af4616c312d.png";
String dd = encryptToBase64(url);
System.out.println(dd);
System.out.println("---------------------------------------");
}
}
}