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 ...
随机推荐
- SpringBoot_04springDataJPA
说明:底层使用Hibernate 一.springDataJPA和mybatisPlus的使用区别 第一步: 把mybatisPlus的依赖.配置删除 包括:实体类的注解.引导类的mapperScan ...
- vue项目1-pizza点餐系统6-路由精讲之复用router-view
1.在主组件展示二级路由的组件内容,在App.vue中添加 <br> <div class="container"> <!-- row 行排列 --& ...
- Vue 创建多页面应用模式
一.多页和单页 应用模式对比 多页应用模式 单页应用模式 应用组成 由多个完整页面组成 由一个外壳页面和多个页面片段组成 跳转方式 页面间跳转 在外壳页面里面,进行页面片段的跳转 加载方式 重新加 ...
- iOS APP 国际化
pp Store 中很多流行的应用程序有多种语言版本.虽然这些应用程序可能因为很多因素而变得流行,但是具有多种本地化版本,肯定是其中一个因素.越多的人可以理解并使用您的应用程序,潜在的买家也就越多. ...
- Linux日常之Ubuntu系统中sendmail的安装、配置、发送邮件
一. 安装 1. sendmail必须先要安装两个包 (1)sudo apt-get install sendmail (2)sudo apt-get install sendmail-cf 2. u ...
- 生成对抗网络资源 Adversarial Nets Papers
来源:https://github.com/zhangqianhui/AdversarialNetsPapers AdversarialNetsPapers The classical Papers ...
- MixConv
深度分离卷积一般使用的是3*3的卷积核,这篇论文在深度分离卷积时使用了多种卷积核,并验证了其有效性 1.大的卷积核能提高模型的准确性,但也不是越大越好.如下,k=9时,精度逐渐降低 2. mixCon ...
- c库函数 rewind fseek
rewind(3) 将文件内部的位置指针重新指向一个流(数据流/文件)的开头 不是文件指针而是文件内部的位置指针 rewind函数作用等同于 (void)fseek(stream, 0L, SEEK_ ...
- 将windows下的文件复制到linux
首先先将你xshell配置好用户名及密码等,必须使用有权限下载的账号进行操作. 使用 yum provides */rz 这条命令,查看你系统自带的软件包的信息.可以看到下方有具体的输出. 2 在输出 ...
- font-awesome样式只显示方框
这是一个踩过的坑:使用font-awesome中的css样式库时,比如fa-user-circle-o,显示的不是一个用户图标,而是一个方框. 怎么回事呢? 进入css文件,发现: 咦,这些文件呢?我 ...