This repository was archived by the owner on Jul 8, 2025. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 29
This repository was archived by the owner on Jul 8, 2025. It is now read-only.
请教大佬,通过chatGPT生成的图片,一般怎么下载呀,我通过URL下载的时候会报错 #4
Copy link
Copy link
Open
Description
Linux上的代码为:
`public static void download(String urlString, String filename, String savePath) {
URL url = null;
HttpsURLConnection con = null;
try {
url = new URL(urlString);
try {
// trust all hosts
trustAllHosts();
HttpsURLConnection https = (HttpsURLConnection) url.openConnection();
//如果请求是https,忽略证书校验
if (url.getProtocol().toLowerCase().equals("https")) {
https.setHostnameVerifier(DO_NOT_VERIFY);
con = https;
} else {
con = (HttpsURLConnection) url.openConnection();
}
//设置请求超时为5s
con.setConnectTimeout(50 * 1000);
// 输入流
InputStream is = con.getInputStream();
// 1K的数据缓冲
byte[] bs = new byte[1024];
// 读取到的数据长度
int len;
// 输出的文件流
File sf = new File(savePath);
if (!sf.exists()) {
sf.mkdirs();
}
/* 获取图片的扩展名(我没用到,所以先注释了)
String extensionName = urlString.substring(urlString.lastIndexOf(".") + 1);*/
OutputStream os = new FileOutputStream(sf.getPath() + "/" + filename);
// 开始读取
while ((len = is.read(bs)) != -1) {
os.write(bs, 0, len);
}
// 完毕,关闭所有链接
os.close();
is.close();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
} catch (MalformedURLException e) {
e.printStackTrace();
}
}`
报错信息如下:超时时间设置很长也没有作用
java.net.ConnectException: Connection timed out (Connection timed out)
Metadata
Metadata
Assignees
Labels
No labels