HttpClient实现通过url下载文件
其实就是通过浏览器url,点击就会下载文件。
这里是从代码层面上,对文件进行下载。
package main.java.com.abp.util; import org.apache.http.*;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.impl.client.HttpClients; import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream; 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 = HttpClients.createDefault();
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 = "https://codeload.github.com/douban/douban-client/legacy.zip/master";
String filepath = "F:\\xxxx\\workspace\\httpClientProj\\file\\test.zip";
HttpDownload.download(url, filepath);
}
}
测试(可忽略,主要自己业务要用到)
@Test
public void test1(){
String docRootPath = "F:\\xxxx\\workspace\\httpClientProj\\file";
String readFileName = "test.zip";
String writeFileName = "write.zip"; File readFile = new File(docRootPath+"\\"+readFileName);
File writeFile = new File(docRootPath+"\\"+writeFileName); try {
byte[] content1 = "CONTENT=".getBytes();
byte[] content2 = FileUtils.readFileToByteArray(readFile); //拷贝文件文件
FileUtils.writeByteArrayToFile(writeFile,content1);
FileUtils.writeByteArrayToFile(writeFile,content2,true);
System.out.println("------------------------------ok"); } catch (IOException e) {
e.printStackTrace();
}
} @Test
public void test2(){
String docRootPath = "F:\\xxxx\\workspace\\httpClientProj\\file";
String readFileName = "write.zip";
String writeFileName = "write1.zip"; File readFile = new File(docRootPath+"\\"+readFileName);
File writeFile = new File(docRootPath+"\\"+writeFileName); try {
byte[] content1 = "CONTENT=".getBytes();
int startIndex = content1.length; byte[] content2 = FileUtils.readFileToByteArray(readFile); byte[] content3 = Arrays.copyOfRange(content2,startIndex,content2.length); //拷贝文件文件
FileUtils.writeByteArrayToFile(writeFile,content3);
System.out.println("------------------------------ok"); } catch (IOException e) {
e.printStackTrace();
}
}
HttpClient实现通过url下载文件的更多相关文章
- 从指定的URL下载文件
通过使用URLDownLoadToFile函数,我们能从指定的URL下载文件,保存到本地,并且下载的文件类型可以是可执行文件 实例如下,http://www.xuexic.com 的根目录下存在一个l ...
- QT实现,通过URL下载文件的接口实现
今天来把坑填上. 具体就是提供一个URL,并通过这个URL下载文件. MyDownloader.h: #ifndef MYDOWNLOADER_H #define MYDOWNLOADER_H cla ...
- 根据URL下载文件
commons-io 包中已经封装好了,直接可以使用 一.添加依赖 <dependency> <groupId>org.apache.commons</groupId&g ...
- wget---从指定的URL下载文件
wget命令用来从指定的URL下载文件.wget非常稳定,它在带宽很窄的情况下和不稳定网络中有很强的适应性,如果是由于网络的原因下载失败,wget会不断的尝试,直到整个文件下载完毕.如果是服务器打断下 ...
- Java从指定URL下载文件并保存到指定目录
1.基本流程 当我们想要下载网站上的某个资源时,我们会获取一个url,它是服务器定位资源的一个描述,下载的过程有如下几步: (1)客户端发起一个url请求,获取连接对象. (2)服务器解析url,并且 ...
- 前端通过url下载文件方法
前端通过url下载文件方法 产生背景 浏览器通过url下载文件,当浏览器识别出资深能播放的资源文件,就不会走下载流程,会直接打开 解决方法 1.让后台转成请求的方式,输出文件流(如果想实现批量下载-因 ...
- 根据文件url,下载文件到本地
/// <summary> /// 根据文件url,下载文件到本地 /// </summary> /// <param name="fileUrl"& ...
- 通过url 下载文件
1.问题简介 通过文件的url,将文件下载到本地.文件存储的位置为:tomcat服务器的文件夹(通过读取properties文件:可看:http://www.cnblogs.com/0201zcr/p ...
- JAVA 实现通过URL下载文件到本地库
/** * TODO 下载文件到本地 * @author nadim * @date Sep 11, 2015 11:45:31 AM * @param fileUrl 远程地址 * @param f ...
随机推荐
- console 对象
JavaScript 原生中默认是没有 Console 对象,这是宿主对象(也就是游览器)提供的内置对象. 用于访问调试控制台,在不同的浏览器里效果可能不同.Console 对象方法:
- Linux下RabbitMQ安装、运行与管理
Linux下RabbitMQ安装.运行与管理 安装erlang 安装参考官网 RabbitMQ的安装需要Erlang的基础环境,必须按照RabbitMQ Erlang版本要求进行安装. 关于Erlan ...
- 4Linux 终端命令格式
Linux 终端命令格式 转自 目标 了解终端命令格式 知道如何查阅终端命令帮助信息 01. 终端命令格式 command [-options] [parameter] 说明: command:命令名 ...
- 北京师范大学第十五届ACM决赛-重现赛K Keep In Line ( 字符串模拟实现)
链接:https://ac.nowcoder.com/acm/contest/3/K 来源:牛客网 Keep In Line 时间限制:C/C++ 1秒,其他语言2秒 空间限制:C/C++ 26214 ...
- Maven高级
第一章 Maven解决冲突的方式 1.1 第一声明者优先原则 那个jar包的坐标在pom.xml文件上属于靠上的位置,这个jar包就是先声明的.先声明的jar包坐标下的依赖包,可以优先进入项目中. 示 ...
- JVM内存结构之本地方法栈
Native Method Stacks(本地方法栈) 本地方法:指不是用Java语言编写的方法,因为Java语言是有一定限制的,有些情况下它是不能直接和操作系统打交道的.这时就需要调用一些用C或C+ ...
- 29.密码学知识-消息认证码MAC-6——2019年12月19日
1. 消息认证码 1.1 消息认证 消息认证码(message authentication code)是一种确认完整性并进行认证的技术,取三个单词的首字母,简称为MAC. 思考改进方案? 从哈希函数 ...
- v-if 和 v-show
关于条件渲染 所谓条件渲染,就是根据不同的条件,使用不同的模板来生成 html. 在 Vue.js 中,使用 v-if 和 v-show 指令来控制条件渲染. 区别 v-show 会在app初始化的时 ...
- MySQL数据库3分组与单表、多表查询
目录 一.表操作的补充 1.1null 和 not null 1.2使用not null的时候 二.单表的操作(import) 2.1分组 2.1.1聚合函数 2.1.2group by 2.1.3h ...
- day02记
一.Tomcat搭建 1.service和controller分别搭建独立的Tomcat且port不一致 2.部署项目选择带有exploded的 3.运行时应先启动service再启动controll ...