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类 本节导读:本节主要介绍通过序列 ...
随机推荐
- vue.js+SSH添加和查询
Vue.js 是一套构建用户界面的渐进式框架.与其他重量级框架不同的是,Vue 采用自底向上增量开发的设计.Vue 的核心库只关注视图层,它不仅易于上手,还便于与第三方库或既有项目整合.另一方面,当与 ...
- Linux - 文件和目录
文件和目录(理解) 目标 理解 Linux 文件目录的结构 01. 单用户操作系统和多用户操作系统(科普) 单用户操作系统:指一台计算机在同一时间 只能由一个用户 使用,一个用户独自享用系统的全部硬件 ...
- MSTP+ VRRP 交换机的 配置过程
配置思路采用以下思路配置: 1.在处于环形网络中的交换设备上配置MSTP基本功能,包括:a.配置MST域并创建多实例,配置VLAN2映射到MSTI1,VLAN3映射到MSTI2,实现流量的负载分担. ...
- java各历史版本官网下载
java各历史版本官网下载: http://www.oracle.com/technetwork/java/javase/archive-139210.html
- 关于java中分割字符串
例子:String path = "123.456.789"; 如果要使用“.”将path分割成String[], path.split("//."); or ...
- [leetcode]364. Nested List Weight Sum II嵌套列表加权和II
Given a nested list of integers, return the sum of all integers in the list weighted by their depth. ...
- [leetcode]156.Binary Tree Upside Down颠倒二叉树
Given a binary tree where all the right nodes are either leaf nodes with a sibling (a left node that ...
- Python开发——数据类型【运算符】
算数运算符 比较运算符 赋值运算符 逻辑运算符 成员运算符
- ping内网一台虚拟机延时很大(hyper-v虚拟机)的解决办法
问题现象: ping 内网一台虚拟机延时很大,不稳定,造成业务系统响应慢.查看服务器上各种资源都正常. 解决办法: 在物理机上找到和hyper-v绑定的那个网卡,把“虚拟机队列”禁用掉就好了,如下图: ...
- 家庭家长本-微信小程序
寒假在家的时候,做了一个简单的网页版家庭账本,后来自己学习了微信小程序的制作方法,现在想做一个微信小程序的家庭记账本. 首先要在微信公众平台注册一个微信小程序的账号,用的邮箱一个只能注册一个微信小程序 ...