java用HttpURLConnection实现互联网图片下载
以下是Java使用HttpURLConnection实现互联网图片下载的示例代码:
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
public class ImageDownloader {
public static void main(String[] args) {
String imageUrl = "https://example.com/image.jpg"; // 图片的URL地址
String savePath = "C:/images/image.jpg"; // 保存图片的本地路径
try {
URL url = new URL(imageUrl);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("GET"); // 使用GET请求方式获取图片
connection.setConnectTimeout(5000); // 设置连接超时时间为5秒
connection.setReadTimeout(5000); // 设置读取超时时间为5秒
int responseCode = connection.getResponseCode(); // 获取服务器返回的状态码
if (responseCode == HttpURLConnection.HTTP_OK) { // 如果状态码为200,表示请求成功
InputStream inputStream = connection.getInputStream(); // 获取输入流
FileOutputStream outputStream = new FileOutputStream(savePath); // 创建输出流
byte[] buffer = new byte[1024];
int length;
while ((length = inputStream.read(buffer)) != -1) { // 读取输入流中的数据,并写入到输出流中
outputStream.write(buffer, 0, length);
}
outputStream.close(); // 关闭输出流
inputStream.close(); // 关闭输入流
System.out.println("图片下载成功!");
} else {
System.out.println("图片下载失败,错误码:" + responseCode);
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
以上代码使用HttpURLConnection发送GET请求获取图片,并将图片保存到本地硬盘。在实际开发中,可能需要根据具体需求对代码进行修改
原文地址: https://www.cveoy.top/t/topic/ggAH 著作权归作者所有。请勿转载和采集!