其实就是通过浏览器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下载文件的更多相关文章

  1. 从指定的URL下载文件

    通过使用URLDownLoadToFile函数,我们能从指定的URL下载文件,保存到本地,并且下载的文件类型可以是可执行文件 实例如下,http://www.xuexic.com 的根目录下存在一个l ...

  2. QT实现,通过URL下载文件的接口实现

    今天来把坑填上. 具体就是提供一个URL,并通过这个URL下载文件. MyDownloader.h: #ifndef MYDOWNLOADER_H #define MYDOWNLOADER_H cla ...

  3. 根据URL下载文件

    commons-io 包中已经封装好了,直接可以使用 一.添加依赖 <dependency> <groupId>org.apache.commons</groupId&g ...

  4. wget---从指定的URL下载文件

    wget命令用来从指定的URL下载文件.wget非常稳定,它在带宽很窄的情况下和不稳定网络中有很强的适应性,如果是由于网络的原因下载失败,wget会不断的尝试,直到整个文件下载完毕.如果是服务器打断下 ...

  5. Java从指定URL下载文件并保存到指定目录

    1.基本流程 当我们想要下载网站上的某个资源时,我们会获取一个url,它是服务器定位资源的一个描述,下载的过程有如下几步: (1)客户端发起一个url请求,获取连接对象. (2)服务器解析url,并且 ...

  6. 前端通过url下载文件方法

    前端通过url下载文件方法 产生背景 浏览器通过url下载文件,当浏览器识别出资深能播放的资源文件,就不会走下载流程,会直接打开 解决方法 1.让后台转成请求的方式,输出文件流(如果想实现批量下载-因 ...

  7. 根据文件url,下载文件到本地

    /// <summary> /// 根据文件url,下载文件到本地 /// </summary> /// <param name="fileUrl"& ...

  8. 通过url 下载文件

    1.问题简介 通过文件的url,将文件下载到本地.文件存储的位置为:tomcat服务器的文件夹(通过读取properties文件:可看:http://www.cnblogs.com/0201zcr/p ...

  9. JAVA 实现通过URL下载文件到本地库

    /** * TODO 下载文件到本地 * @author nadim * @date Sep 11, 2015 11:45:31 AM * @param fileUrl 远程地址 * @param f ...

随机推荐

  1. Linux :环境变量设置和本地变量加载

    bash: 全局变量: /etc/profile,  /etc/profile.d/*,  /etc/bashrc 个人变量: ~/.bash_profile,   ~/.bashrc bash运行方 ...

  2. c# 杀死占用某个文件的进程

    原文:c# 杀死占用某个文件的进程 需要使用微软提供的工具Handle.exe string fileName = @"H:\abc.dll";//要检查被那个进程占用的文件 Pr ...

  3. 检验Excel中数据是否与数据库中数据重复

    #region 记录Excel中的重复列 /// <summary> /// 记录Excel中的重复列 /// </summary> /// <param name=&q ...

  4. 41. First Missing Positive (JAVA)

    Given an unsorted integer array, find the smallest missing positive integer. Example 1: Input: [1,2, ...

  5. newgrp - 登录到新的用户组中

    总览 (SYNOPSIS) newgrp [ group ] 描述 (DESCRIPTION) Newgrp 改变 调用者 的 用户组标识, 类似于 login(1). 调用者 仍旧 登录 在 系统 ...

  6. Linux读写物理内存

    一.基础知识 1.打开设备文件: mem是一个字符设备文件,是计算机主存的一个映像.通常只有root用户对其有读写权限.因此只有root用户能进行这些操作. 如果要打开设备文件/dev/mem,需要系 ...

  7. JVM Direct Memory

    JVM除了堆内存.栈内存,还有DirectMemory内存,DirectMemory是java nio引入的. 在JDK1.4中新加入了NIO(New INput/Output)类,引入了一种基于通道 ...

  8. MySQL高可用集群方案

    一.Mysql高可用解决方案 方案一:共享存储 一般共享存储采用比较多的是 SAN/NAS 方案. 方案二:操作系统实时数据块复制 这个方案的典型场景是 DRBD,DRBD架构(MySQL+DRBD+ ...

  9. vue组件样式scoped

    1.vue组件中的样式如果没加scrped,样式代表的是全局样式(避免组件之间样式的冲突).加了属性代表是模块化的. 其他组件引用button组件 上面分析了单个组件渲染后的结果,那么组件互相调用之后 ...

  10. dede后台系统基本参数空白怎么办?

    dede后台系统基本参数空白怎么办? 如图:   解决办法:还原dede_sysconfig表即可 后台 系统-SQL命令行工具,执行如下sql delete table dede_sysconfig ...