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 ...
随机推荐
- React 使用相对于根目录进行引用组件
在对自己开发的组件中经常会做诸如以下的引用: import genFetchEntryListArgs from '../../../utils/table/genFetchEntryListArgs ...
- pureftp安装
1.下载 #cd /usr/local/src #wget http://download.pureftpd.org/pub/pure-ftpd/releases/pure-ftpd-1.0.36.t ...
- 小程序之如和使用view内部组件来进行页面的排版功能
这篇文章主要介绍了关于小程序之如和使用view内部组件来进行页面的排版功能,有着一定的参考价值,现在分享给大家,有需要的朋友可以参考一下 涉及知识点: 1.垂直排列,水平排列 2.居中对齐 示例: 1 ...
- losetup - 设 定 与 控 制 环回设备
总览 SYNOPSIS losetup [ -e encryption ] [ -o offset ] loop_device file losetup [ -d ] loop_device 描述 l ...
- 05-转置-置换-向量空间R
一.置换矩阵 一个矩阵的行或者列交换,可以借助另外一个矩阵相乘来实现 首先是行交换: $\underbrace{\left[\begin{array}{ccc}{1} & {1} & ...
- Keepalived+Nginx+tomcat实现主备+负载
部署系统: Red Hat Enterprise Linux Server release 7.0 软件版本:apache-tomcat-7.0.92.tar.gzkeepalived-2.0.11. ...
- vue2.0 之 slot 内容分发
前提:父组件模板的内容在父组件作用域内编译:子组件模板的内容在子组件作用域内编译.被分发的内容会在父作用域内编译. 一.单个插槽 // 子组件模板 child-component <div> ...
- u-boot 用哪个lds链接脚本
顶层Makefile文件中 : ifndef LDSCRIPT #LDSCRIPT := $(srctree)/board/$(BOARDDIR)/u-boot.lds.debug ifd ...
- 3.docker镜像管理基础
一.docker镜像相关 1.About Docker Image Docker镜像含有启动容器所需要的文件系统及其内容,因此,其用于创建并启动docker容器. 采用分层构建机制,最底层为bootf ...
- 【NOIP2016提高A组8.11】钱仓
题目 分析 发现,一定有一个点作为起点,所有的路径都不经过这个起点. 接着贪心求答案, 如果\(c_i>1\),将其中\(c_i-1\)个钱往后"铺". 易证\(x^2+y^ ...