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 ...
随机推荐
- 前端校招知识体系之HTML5
啥是HTML5?官方说HTML5 是下一代的 HTML... 本文主要介绍HTML5三个方面的知识,继续往下看看吧. 语义化标签 canvas&svg 响应式meta 一.语义化标签 语义化标 ...
- 基于TCP/UDP协议的socket
基于TCP协议的socket tcp是基于链接的,必须先启动服务端,然后再启动客户端去链接服务端 server端 import socket sk = socket.socket() sk.bind( ...
- ERROR: Unable to clean up existing run directory
Project Navigator - Launching PlanAhead gives: ERROR: Unable to clean up existing run directory De ...
- shell脚本中oldIFS=$IFS
https://blog.csdn.net/champwang/article/details/54670293 转自https://man.linuxde.net/shell-script/shel ...
- Spring AOP注解配置demo
https://blog.csdn.net/yhl_jxy/article/details/78815636#commentBox
- linux-lampweb
http://www.lampweb.org/linux/2/6.html
- 多对多关系表的创建方式、forms组件
目录 多对多关系表的三种创建方式 1.全自动,Django自动创建 2.纯手撸 3.半自动(推荐使用) forms组件 小例子 forms组件 校验器 钩子函数 局部钩子 全局钩子 forms组件常用 ...
- Java面试之集合框架篇(3)
21.ArrayList和Vector的区别 这两个类都实现了List接口(List接口继承了Collection接口),他们都是有序集合,即存储在这两个集合中的元素的位置都是有顺序的,相当于一种动态 ...
- logback系列二:logback在项目中的应用
1.输出http日志 2.输出dubbo日志 3.输出interfacer日志 4.输出到access,remote,app等目录中
- k-means原理和python代码实现
k-means:是无监督的分类算法 k代表要分的类数,即要将数据聚为k类; means是均值,代表着聚类中心的迭代策略. k-means算法思想: (1)随机选取k个聚类中心(一般在样本集中选取,也可 ...