--> 通过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 类的简单应用...

最新文章

  1. 常用jdbc的url
  2. Oracle(创建视图)
  3. 手机上的页面转换page slider
  4. Backbone事件管理——Backbone.Events模块API结构
  5. 同步与异步&阻塞与非阻塞
  6. Jenkins进阶系列之——10Publish Over SSH插件
  7. 解决SQLServer2008 Express远程连接出错的问题[Error: 1326错误]
  8. POJ 1679 The Unique MST (次小生成树)
  9. asp.net+MVC--1
  10. 【HDOJ】5564 Clarke and digits
  11. PHP创建桌面快捷方式实例
  12. sql 合并相同条件的字段
  13. 虚拟主机的配置、DNS重定向网站
  14. Winform ComBox模糊查询
  15. fastjson SerializerFeature详解
  16. meta标签整合
  17. git 提交顺序
  18. CentOS6.5安装pip
  19. 第一章:HTML5的基础
  20. Vue.directive基础,在Vue模块开发中使用

热门文章

  1. 2.4G高频PCB天线设计
  2. python成长之路【第五篇】:python字符编码
  3. windows防火墙命令详解
  4. thinkphp分页搜索条件带中文参数
  5. java环境变量设定
  6. 补psp进度(11月4号-9号)
  7. 读javascript高级程序设计16-几条函数小技巧
  8. jQuery实现加入购物车飞入动画效果
  9. PDF 补丁丁 0.4.2.905 测试版发布:智能合并功能减小合并文件的大小
  10. IIS调试技巧