import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream; import org.apache.http.Header;
import org.apache.http.HeaderElement;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient; /**
* 说明
* 利用httpclient下载文件
* maven依赖
* <dependency>
* <groupId>org.apache.httpcomponents</groupId>
* <artifactId>httpclient</artifactId>
* <version>4.0.1</version>
* </dependency>
* 可下载http文件、图片、压缩文件
* bug:获取response header中Content-Disposition中filename中文乱码问题
* @author tanjundong
*
*/
public class HttpDownload { public static final int cache = 10 * 1024;
public static final boolean isWindows;
public static final String splash;
public static final String root;
static {
if (System.getProperty("os.name") != null && System.getProperty("os.name").toLowerCase().contains("windows")) {
isWindows = true;
splash = "\\";
root="D:";
} else {
isWindows = false;
splash = "/";
root="/search";
}
} /**
* 根据url下载文件,文件名从response header头中获取
* @param url
* @return
*/
public static String download(String url) {
return download(url, null);
} /**
* 根据url下载文件,保存到filepath中
* @param url
* @param filepath
* @return
*/
public static String download(String url, String filepath) {
try {
HttpClient client = new DefaultHttpClient();
HttpGet httpget = new HttpGet(url);
HttpResponse response = client.execute(httpget); HttpEntity entity = response.getEntity();
InputStream is = entity.getContent();
if (filepath == null)
filepath = getFilePath(response);
File file = new File(filepath);
file.getParentFile().mkdirs();
FileOutputStream fileout = new FileOutputStream(file);
/**
* 根据实际运行效果 设置缓冲区大小
*/
byte[] buffer=new byte[cache];
int ch = 0;
while ((ch = is.read(buffer)) != -1) {
fileout.write(buffer,0,ch);
}
is.close();
fileout.flush();
fileout.close(); } catch (Exception e) {
e.printStackTrace();
}
return null;
}
/**
* 获取response要下载的文件的默认路径
* @param response
* @return
*/
public static String getFilePath(HttpResponse response) {
String filepath = root + splash;
String filename = getFileName(response); if (filename != null) {
filepath += filename;
} else {
filepath += getRandomFileName();
}
return filepath;
}
/**
* 获取response header中Content-Disposition中的filename值
* @param response
* @return
*/
public static String getFileName(HttpResponse response) {
Header contentHeader = response.getFirstHeader("Content-Disposition");
String filename = null;
if (contentHeader != null) {
HeaderElement[] values = contentHeader.getElements();
if (values.length == 1) {
NameValuePair param = values[0].getParameterByName("filename");
if (param != null) {
try {
//filename = new String(param.getValue().toString().getBytes(), "utf-8");
//filename=URLDecoder.decode(param.getValue(),"utf-8");
filename = param.getValue();
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
return filename;
}
/**
* 获取随机文件名
* @return
*/
public static String getRandomFileName() {
return String.valueOf(System.currentTimeMillis());
}
public static void outHeaders(HttpResponse response) {
Header[] headers = response.getAllHeaders();
for (int i = 0; i < headers.length; i++) {
System.out.println(headers[i]);
}
}
public static void main(String[] args) {
// String url = "http://bbs.btwuji.com/job.php?action=download&pid=tpc&tid=320678&aid=216617";
String url="http://www.dy1000.com/img/20120701/1999311085_150_200.JPG";
// String filepath = "D:\\test\\a.torrent";
String filepath = "D:\\test\\a.jpg";
HttpDownload.download(url, filepath);
}
}

参考资料: 
http://eyecm.com/httpclient4-1-tutorial-official-examples-to-explain-httpclient4-1-usage/ 
http://eyecm.com/httpclient-download/

HttpClient实现HTTP文件通用下载类的更多相关文章

  1. [转]httpclient 上传文件、下载文件

    用httpclient4.3 post方式推送文件到服务端  准备:httpclient-4.3.3.jar:httpcore-4.3.2.jar:httpmime-4.3.3.jar/** * 上传 ...

  2. C# ICSharpCode.SharpZipLib.dll文件压缩和解压功能类整理,上传文件或下载文件很常用

    工作中我们很多时候需要进行对文件进行压缩,比较通用的压缩的dll就是ICSharpCode.SharpZipLib.dll,废话不多了,网上也有很多的资料,我将其最常用的两个函数整理了一下,提供了一个 ...

  3. [上传下载] C#FileUp文件上传类 (转载)

    点击下载 FileUp.zip 主要功能如下 .把上传的文件转换为字节数组 .流转化为字节数组 .上传文件根据FileUpload控件上传 .把Byte流上传到指定目录并保存为文件 看下面代码吧 // ...

  4. js文件流下载通用方法

    通常我们会用到文件流下载文件,下面给大家一个通用的文件流下载的js /* *下载文件 * options:{ * url:'', //下载地址 * isNewWinOpen:false,是否新窗口打开 ...

  5. PHP扩展类ZipArchive实现压缩解压Zip文件和文件打包下载 && Linux下的ZipArchive配置开启压缩 &&搞个鸡巴毛,写少了个‘/’号,浪费了一天

    PHP ZipArchive 是PHP自带的扩展类,可以轻松实现ZIP文件的压缩和解压,使用前首先要确保PHP ZIP 扩展已经开启,具体开启方法就不说了,不同的平台开启PHP扩增的方法网上都有,如有 ...

  6. C# 应用 - 使用 HttpClient 发起上传文件、下载文件请求

    1. 示例代码 using System; using System.IO; using System.Net.Http; /// <summary> /// 下载文件 /// </ ...

  7. SQL 横转竖 、竖专横 (转载) 使用Dapper.Contrib 开发.net core程序,兼容多种数据库 C# 读取PDF多级书签 Json.net日期格式化设置 ASPNET 下载共享文件 ASPNET 文件批量下载 递归,循环,尾递归 利用IDisposable接口构建包含非托管资源对象 《.NET 进阶指南》读书笔记2------定义不可改变类型

    SQL 横转竖 .竖专横 (转载)   普通行列转换 问题:假设有张学生成绩表(tb)如下: 姓名 课程 分数 张三 语文 74 张三 数学 83 张三 物理 93 李四 语文 74 李四 数学 84 ...

  8. [.net 面向对象程序设计进阶] (13) 序列化(Serialization)(五) Json 序列化利器 Newtonsoft.Json 及 通用Json类

    [.net 面向对象程序设计进阶] (13) 序列化(Serialization)(五) Json 序列化利器 Newtonsoft.Json 及 通用Json类 本节导读: 关于JSON序列化,不能 ...

  9. [.net 面向对象程序设计进阶] (11) 序列化(Serialization)(三) 通过接口 IXmlSerializable 实现XML序列化 及 通用XML类

    [.net 面向对象程序设计进阶] (11) 序列化(Serialization)(三) 通过接口 IXmlSerializable 实现XML序列化 及 通用XML类 本节导读:本节主要介绍通过序列 ...

随机推荐

  1. 吴裕雄 python深度学习与实践(8)

    import cv2 import numpy as np img = cv2.imread("G:\\MyLearning\\TensorFlow_deep_learn\\data\\le ...

  2. python入门(三):循环

    1.for i in xxx xxx: 序列(列表,元祖,字符串) xxx: 可迭代对象 >>> for i in "abc": ...     print(i) ...

  3. 定时任务 spring @Scheduled注解

    使用spring @Scheduled注解执行定时任务: 运行!!! 关于Cron表达式(转载) 表达式网站生成: http://cron.qqe2.com/  直接点击 cronExpression ...

  4. 《CSAPP》地址翻译

    本节所使用的符号: 地址翻译 地址翻译是一个N元素的虚拟地址空间(VAS)中的元素和一个M元素的物理地址空间(PAS)中元素之间的映射. 映射实现: MMU利用页表来实现这种映射.CPU中的一个控制寄 ...

  5. vw, vh视区覆盖和自适应图片

      CSS .wrap{width:100vw;height:100vh;background: rgba(0,0,0,0.3);position: fixed;top:0;left:0;text-a ...

  6. C#使用 params object[] 将参数个数不一样的方法 集成一个

    getChange("1"); getChange("1","2"); public string getChange(params obj ...

  7. 20175126《Java程序设计》第一周学习总结

    # 学号 20175126 <Java程序设计>第一周学习总结   ## 教材学习内容总结   - 1.安装了WINDOS系统的JDK,并学会了利用JDK编写并编译JAVA程序的基本方法. ...

  8. String 中intern

    首先贴上源码中的注释 在一个String类上调用这个方法的时候如果常量池中存在和这个String对象相同的对象的时候,直接返回常量池中的常量,如果常量池中不存在这个对象,就直接将其将其加入常量池,并且 ...

  9. 529. Minesweeper扫雷游戏

    [抄题]: Let's play the minesweeper game (Wikipedia, online game)! You are given a 2D char matrix repre ...

  10. [leetcode]200. Number of Islands岛屿个数

    Given a 2d grid map of '1's (land) and '0's (water), count the number of islands. An island is surro ...