URL url = new URL(path);
// GET 必须大写
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("GET");
// 超时 5秒
conn.setReadTimeout(5 * 1000);
InputStream is = conn.getInputStream();
ByteArrayOutputStream bos = new ByteArrayOutputStream();
byte[] buffer = new byte[1024];
int len;
while((len = is.read(buffer)) != -1 ) {
bos.write(buffer, 0, len);
}
byte[] data = bos.toByteArray();
File file = new File("zhiling.jpg");
FileOutputStream fos = new FileOutputStream(file);
fos.write(data);
fos.close();
网络编程
最新推荐文章于 2025-02-24 17:01:40 发布
本文提供了一个使用Java通过HTTP GET请求从指定URL下载图片到本地文件系统的示例代码。该示例展示了如何创建URL对象并打开连接,设置请求方法为GET,定义超时时间,并读取输入流将图片数据写入到文件。
2489

被折叠的 条评论
为什么被折叠?



