Java-->利用URL类下载图片
2024-10-11 12:23:22
--> 通过get 请求访问图片地址,将通过服务器响应的数据(即图片数据)存到本地文件中...
--> HttpURLConnectionUtil 工具类
package com.dragon.java.downloadpic; import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL; public class HttpURLConnectionUtil {
// 通过get请求得到读取器响应数据的数据流
public static InputStream getInputStreamByGet(String url) {
try {
HttpURLConnection conn = (HttpURLConnection) new URL(url)
.openConnection();
conn.setReadTimeout(5000);
conn.setConnectTimeout(5000);
conn.setRequestMethod("GET"); if (conn.getResponseCode() == HttpURLConnection.HTTP_OK) {
InputStream inputStream = conn.getInputStream();
return inputStream;
} } catch (IOException e) {
e.printStackTrace();
}
return null;
} // 将服务器响应的数据流存到本地文件
public static void saveData(InputStream is, File file) {
try (BufferedInputStream bis = new BufferedInputStream(is);
BufferedOutputStream bos = new BufferedOutputStream(
new FileOutputStream(file));) {
byte[] buffer = new byte[1024];
int len = -1;
while ((len = bis.read(buffer)) != -1) {
bos.write(buffer, 0, len);
bos.flush();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
--> Test 测试类
package com.dragon.java.downloadpic; import java.io.File;
import java.io.InputStream; /*
* 1. 从下面的地址下载图片,并保存在文件中。
http://img.coocaa.com/www/attachment/forum/201602/16/085938u86ewu4l8z6flr6w.jpg
*要求:封装相应的工具类*
*/
public class Test {
public static void main(String[] args) {
String url = "http://img.coocaa.com/www/attachment/forum/201602/16/085938u86ewu4l8z6flr6w.jpg";
String[] split = url.split("\\/");
String fileName = split[split.length - 1];
File file = new File("f:/", fileName);
InputStream inputStream = HttpURLConnectionUtil
.getInputStreamByGet(url);
HttpURLConnectionUtil.saveData(inputStream, file);
}
}
--> URL 类的简单应用...
最新文章
- 常用jdbc的url
- Oracle(创建视图)
- 手机上的页面转换page slider
- Backbone事件管理——Backbone.Events模块API结构
- 同步与异步&;阻塞与非阻塞
- Jenkins进阶系列之——10Publish Over SSH插件
- 解决SQLServer2008 Express远程连接出错的问题[Error: 1326错误]
- POJ 1679 The Unique MST (次小生成树)
- asp.net+MVC--1
- 【HDOJ】5564 Clarke and digits
- PHP创建桌面快捷方式实例
- sql 合并相同条件的字段
- 虚拟主机的配置、DNS重定向网站
- Winform ComBox模糊查询
- fastjson SerializerFeature详解
- meta标签整合
- git 提交顺序
- CentOS6.5安装pip
- 第一章:HTML5的基础
- Vue.directive基础,在Vue模块开发中使用