import org.apache.http.HttpEntity;
// 本地保存路径
String destinationFilePath = "C:\\Users\\YourUsername\\Desktop\\downloaded_image.jpg";
// 代理信息
String proxyHost = "www.16yun.cn";
int proxyPort = 5445; // 确保端口是整数类型
String proxyUser = "16QMSOML";
String proxyPass = "280651";
try {
downloadImage(imageUrl, destinationFilePath, proxyHost, proxyPort, proxyUser, proxyPass);
System.out.println("图片下载完成,保存路径:" + destinationFilePath);
} catch (IOException | URISyntaxException e) {
System.err.println("下载失败:" + e.getMessage());
}
}
/**
* 下载图片并保存到本地
* @param imageUrl 图片的URL
* @param destinationFilePath 本地保存路径
* @param proxyHost 代理服务器地址
* @param proxyPort 代理服务器端口
* @param proxyUser 代理服务器用户名
* @param proxyPass 代理服务器密码
* @throws IOException 如果发生I/O错误
* @throws URISyntaxException 如果URL格式不正确
*/
public static void downloadImage(String imageUrl, String destinationFilePath,
String proxyHost, int proxyPort,
String proxyUser, String proxyPass)
throws IOException, URISyntaxException {
// 创建凭证提供器
CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
credentialsProvider.setCredentials(
new AuthScope(proxyHost, proxyPort),
new UsernamePasswordCredentials(proxyUser, proxyPass)
);
// 创建HttpClient实例并设置代理和凭证
HttpClient client = HttpClients.custom()
.setProxy(new HttpHost(proxyHost, proxyPort))
.setDefaultCredentialsProvider(credentialsProvider)
.build();
// 创建HttpGet请求
HttpGet request = new HttpGet(new URI(imageUrl));
try {
// 发送请求并获取响应
HttpResponse response = client.execute(request);
// 检查响应状态码
if (response.getStatusLine().getStatusCode() == 200) {
// 获取响应实体
HttpEntity entity = response.getEntity();
// 将响应实体转换为字节数组
byte[] imageData = EntityUtils.toByteArray(entity);
// 创建本地文件
File destinationFile = new File(destinationFilePath);
try (FileOutputStream fos = new FileOutputStream(destinationFile)) {
// 将图片数据写入本地文件
fos.write(imageData);
}
System.out.println("图片已成功保存到:" + destinationFilePath);
} else {
System.err.println("无法下载图片,服务器返回状态码:" + response.getStatusLine().getStatusCode());
}
} finally {
// 关闭请求
request.releaseConnection();
}
}
}
HttpHost proxy = new HttpHost("代理服务器地址", 代理服务器端口);
HttpClient client = HttpClients.custom()
.setProxy(proxy)
.build();
try {
downloadImage(imageUrl, destinationFilePath);
} catch (URISyntaxException e) {
System.err.println("URL格式错误:" + e.getMessage());
} catch (IOException e) {
System.err.println("I/O错误:" + e.getMessage());
} catch (Exception e) {
System.err.println("未知错误:" + e.getMessage());
}