HttpClient实现HTTP文件通用下载类
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文件通用下载类的更多相关文章
- [转]httpclient 上传文件、下载文件
用httpclient4.3 post方式推送文件到服务端 准备:httpclient-4.3.3.jar:httpcore-4.3.2.jar:httpmime-4.3.3.jar/** * 上传 ...
- C# ICSharpCode.SharpZipLib.dll文件压缩和解压功能类整理,上传文件或下载文件很常用
工作中我们很多时候需要进行对文件进行压缩,比较通用的压缩的dll就是ICSharpCode.SharpZipLib.dll,废话不多了,网上也有很多的资料,我将其最常用的两个函数整理了一下,提供了一个 ...
- [上传下载] C#FileUp文件上传类 (转载)
点击下载 FileUp.zip 主要功能如下 .把上传的文件转换为字节数组 .流转化为字节数组 .上传文件根据FileUpload控件上传 .把Byte流上传到指定目录并保存为文件 看下面代码吧 // ...
- js文件流下载通用方法
通常我们会用到文件流下载文件,下面给大家一个通用的文件流下载的js /* *下载文件 * options:{ * url:'', //下载地址 * isNewWinOpen:false,是否新窗口打开 ...
- PHP扩展类ZipArchive实现压缩解压Zip文件和文件打包下载 && Linux下的ZipArchive配置开启压缩 &&搞个鸡巴毛,写少了个‘/’号,浪费了一天
PHP ZipArchive 是PHP自带的扩展类,可以轻松实现ZIP文件的压缩和解压,使用前首先要确保PHP ZIP 扩展已经开启,具体开启方法就不说了,不同的平台开启PHP扩增的方法网上都有,如有 ...
- C# 应用 - 使用 HttpClient 发起上传文件、下载文件请求
1. 示例代码 using System; using System.IO; using System.Net.Http; /// <summary> /// 下载文件 /// </ ...
- SQL 横转竖 、竖专横 (转载) 使用Dapper.Contrib 开发.net core程序,兼容多种数据库 C# 读取PDF多级书签 Json.net日期格式化设置 ASPNET 下载共享文件 ASPNET 文件批量下载 递归,循环,尾递归 利用IDisposable接口构建包含非托管资源对象 《.NET 进阶指南》读书笔记2------定义不可改变类型
SQL 横转竖 .竖专横 (转载) 普通行列转换 问题:假设有张学生成绩表(tb)如下: 姓名 课程 分数 张三 语文 74 张三 数学 83 张三 物理 93 李四 语文 74 李四 数学 84 ...
- [.net 面向对象程序设计进阶] (13) 序列化(Serialization)(五) Json 序列化利器 Newtonsoft.Json 及 通用Json类
[.net 面向对象程序设计进阶] (13) 序列化(Serialization)(五) Json 序列化利器 Newtonsoft.Json 及 通用Json类 本节导读: 关于JSON序列化,不能 ...
- [.net 面向对象程序设计进阶] (11) 序列化(Serialization)(三) 通过接口 IXmlSerializable 实现XML序列化 及 通用XML类
[.net 面向对象程序设计进阶] (11) 序列化(Serialization)(三) 通过接口 IXmlSerializable 实现XML序列化 及 通用XML类 本节导读:本节主要介绍通过序列 ...
随机推荐
- 《Android Studio开发实战 从零基础到App上线》资源下载和内容勘误
转载于:https://blog.csdn.net/aqi00/article/details/73065392 资源下载 下面是<Android Studio开发实战 从零基础到App上线&g ...
- mysql创建表和数据库
创建数据库,创建数据库表,例子.MySQL语句 1.创建数据库: 创建的代码:create 数据库的代码:database 数据库表名:随便起,只要自己记住就行.test create ...
- Binary Space Partitioning
[Binary Space Partitioning] BSP was discovered by John Carmack used BSP trees in Doom and Quake. Alt ...
- vi怎么统计查找字符串的个数
vi怎么统计查找字符串的个数 用vi打开一个比较大的文本,用vi查找指定字符串,现在怎么统计该字符串的个数呢?比如我查找ORA字符串,直接输入 /ORA的时候vi会高亮显示.现在怎么统计ORA的个数呢 ...
- matplotlib 坑
1 archlinux里安装好matplotlib之后一定要安装python-cario pacman -S python-cairo
- Windbg驱动双机调试环境配置
[由于进入了Windows驱动编程领域第一步就是搭建环境,整个环境来说说难也不难,只是比较麻烦.文章有些地方比较繁琐的,而且别人写的比较好,作为引用参考直接贴连接了.如果你按照我写的一步步完成,很快就 ...
- 判断JS的数据类型
typeof.instanceof. constructor. prototype方法比较 (摘自如何判断JS中的数据类型) 1. 使用typeof操作符. 对一个值使用 typeof 操作符可能返回 ...
- CentOS 6.7快速搭建lamp环境
安装前要关闭防火墙,防止外网不能访问,这一点很重要,要不然外网访问不了: ①关闭防火墙:service iptables stop ②永久关闭防火墙:chkconfig iptables off ③查 ...
- c#npoi 报错Cannot get a numeric value from a text cell 的解决
一般是因为cell里边的值为数字导致,有时变成文本格式还是解决不了这个问题. 下边的代码是c# 改变设置cell类型的方法 是用这个参数 CellType.String Row.GetCell((in ...
- HDU2028
#include <bits/stdc++.h> using namespace std; ; int gcd(int a, int b) { ? b:gcd(b, a%b); } int ...