HTTP文件的下载后台JAVA代码

1、使用org.apache.http.impl.client.CloseableHttpClient

先上代码:

    public String downloadFile(String src_file, String dest_file) throws Throwable {

        String fileName = getFileName(src_file);
try (CloseableHttpClient httpclient = HttpClients.createDefault()) {
HttpGet httpget = new HttpGet(src_file);
httpget.setConfig(RequestConfig.custom() //
.setConnectionRequestTimeout(downloadTimeout) //
.setConnectTimeout(downloadTimeout) //
.setSocketTimeout(downloadTimeout) //
.build());
try (CloseableHttpResponse response = httpclient.execute(httpget)) {
org.apache.http.HttpEntity entity = response.getEntity();
File desc = new File(dest_file+File.separator+fileName);
File folder = desc.getParentFile();
folder.mkdirs();
try (InputStream is = entity.getContent(); //
OutputStream os = new FileOutputStream(desc)) {
StreamUtils.copy(is, os);
}
}catch(Throwable e){
throw new Throwable("文件下载失败......", e);
}
}
return dest_file+File.separator+fileName;
}

另外:添加header代码如下:httpget.addHeader("X-Auth-Token",token);

2、使用curl:

windows系统中使用需要下载CURL,下载地址:https://curl.haxx.se/download.html 选择windows版;

使用命令行下载文件java代码:

package com.test.download;

import java.io.IOException;

public class TestDownload {

    public static void main(String[] args) {

        String curlPath = "D:\\curl\\I386\\CURL.EXE";
String destPath = "D:\\2.jpg";
String fileUrl = "http://i0.hdslb.com/bfs/archive/5a08e413f479508ab78bb562ac81f40ad28a4245.jpg";
dowloadFile(curlPath,destPath,fileUrl); } private static void dowloadFile(String curlPath ,String filePath, String url) { long start = System.currentTimeMillis();
String token = "12345678901234567890";
System.out.println("执行命令==="+curlPath + " -o "+ filePath +" \"" + url +"\""
+ " -H \"X-Auth-Token:"+token+"\" -X GET");
try {
Runtime.getRuntime().exec(curlPath + " -o "+ filePath +" \"" + url +"\""
+ " -H \"X-Auth-Token:"+token+"\" -X GET");
} catch (IOException e) {
e.printStackTrace();
}
System.out.println("下载成功,耗时(ms):"+(System.currentTimeMillis()-start)); } }

具体的CURL命令行使用可以看帮助:curl -h

3、Servlet文件下载:

public void downloadNet(HttpServletResponse response) throws MalformedURLException {
int bytesum = 0;
int byteread = 0; URL url = new URL("http://img.baidu.com/logo.gif"); try {
URLConnection conn = url.openConnection();
InputStream inStream = conn.getInputStream();
FileOutputStream fs = new FileOutputStream("c:/abc.gif"); byte[] buffer = new byte[1204];
int length;
while ((byteread = inStream.read(buffer)) != -1) {
bytesum += byteread;
System.out.println(bytesum);
fs.write(buffer, 0, byteread);
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
} public void downLoad(String filePath, HttpServletResponse response, boolean isOnLine) throws Exception {
File f = new File(filePath);
if (!f.exists()) {
response.sendError(404, "File not found!");
return;
}
BufferedInputStream br = new BufferedInputStream(new FileInputStream(f));
byte[] buf = new byte[1024];
int len = 0; response.reset(); // 非常重要
if (isOnLine) { // 在线打开方式
URL u = new URL("file:///" + filePath);
response.setContentType(u.openConnection().getContentType());
response.setHeader("Content-Disposition", "inline; filename=" + f.getName());
// 文件名应该编码成UTF-8
} else { // 纯下载方式
response.setContentType("application/x-msdownload");
response.setHeader("Content-Disposition", "attachment; filename=" + f.getName());
}
OutputStream out = response.getOutputStream();
while ((len = br.read(buf)) > 0)
out.write(buf, 0, len);
br.close();
out.close();
}

download

4、添加两个文件复制的代码:

private static void nioTransferCopy(File source, File target) {
FileChannel in = null;
FileChannel out = null;
FileInputStream inStream = null;
FileOutputStream outStream = null;
try {
inStream = new FileInputStream(source);
outStream = new FileOutputStream(target);
in = inStream.getChannel();
out = outStream.getChannel();
in.transferTo(0, in.size(), out);
} catch (IOException e) {
e.printStackTrace();
} finally {
close(inStream);
close(in);
close(outStream);
close(out);
}
} private static void nioBufferCopy(File source, File target) {
FileChannel in = null;
FileChannel out = null;
FileInputStream inStream = null;
FileOutputStream outStream = null;
try {
inStream = new FileInputStream(source);
outStream = new FileOutputStream(target);
in = inStream.getChannel();
out = outStream.getChannel();
ByteBuffer buffer = ByteBuffer.allocate(4096);
while (in.read(buffer) != -1) {
buffer.flip();
out.write(buffer);
buffer.clear();
}
} catch (IOException e) {
e.printStackTrace();
} finally {
close(inStream);
close(in);
close(outStream);
close(out);
}
}

添加一个文件下载的RestTemplate的实现:

public void downloadLittleFileToPath(String url, String target) {
Instant now = Instant.now();
RestTemplate template = new RestTemplate();
ClientHttpRequestFactory clientFactory = new HttpComponentsClientHttpRequestFactory();
template.setRequestFactory(clientFactory);
HttpHeaders header = new HttpHeaders();
List<MediaType> list = new ArrayList<MediaType>();
// 指定下载文件类型
list.add(MediaType.APPLICATION_OCTET_STREAM);
header.setAccept(list);
HttpEntity<byte[]> request = new HttpEntity<byte[]>(header);
ResponseEntity<byte[]> rsp = template.exchange(url, HttpMethod.GET, request, byte[].class);
logger.info("[下载文件] [状态码] code:{}", rsp.getStatusCode());
try {
Files.write(Paths.get(target), Objects.requireNonNull(rsp.getBody(), "未获取到下载文件"));
} catch (IOException e) {
logger.error("[下载文件] 写入失败:", e);
}
logger.info("[下载文件] 完成,耗时:{}", ChronoUnit.MILLIS.between(now, Instant.now()));
} public void downloadBigFileToPath(String url, String target) {
Instant now = Instant.now();
try {
RestTemplate template = new RestTemplate();
ClientHttpRequestFactory clientFactory = new HttpComponentsClientHttpRequestFactory();
template.setRequestFactory(clientFactory);
//定义请求头的接收类型
RequestCallback requestCallback = request -> request.getHeaders()
.setAccept(Arrays.asList(MediaType.APPLICATION_OCTET_STREAM, MediaType.ALL));
// getForObject会将所有返回直接放到内存中,使用流来替代这个操作
ResponseExtractor<Void> responseExtractor = response -> {
// Here I write the response to a file but do what you like
Files.copy(response.getBody(), Paths.get(target));
return null;
};
template.execute(url, HttpMethod.GET, requestCallback, responseExtractor);
} catch (Throwable e) {
logger.error("[下载文件] 写入失败:", e);
}
logger.info("[下载文件] 完成,耗时:{}", ChronoUnit.MILLIS.between(now, Instant.now()));
}

RestTemplate下载文件

HTTP文件下载JAVA后台的实现的更多相关文章

  1. Java 后台创建word 文档

    ---恢复内容开始--- Java 后台创建 word 文档 自己总结  网上查阅的文档 分享POI 教程地址:http://www.tuicool.com/articles/emqaEf6 方式一. ...

  2. Java后台处理框架之struts2学习总结

    Java后台处理框架之struts2学习总结 最近我在网上了解到,在实际的开发项目中struts2的使用率在不断降低,取而代之的是springMVC.可能有很多的朋友看到这里就会说,那还不如不学str ...

  3. pagebean pagetag java 后台代码实现分页 demo 前台标签分页 后台java分页

    java 后台代码实现分页 demo 实力 自己写的 标签分页 package com.cszoc.sockstore.util; import java.util.HashMap;import ja ...

  4. ajax提交数据到java后台,并且返回json格式数据前台接收处理值

    1.前台html页面.有一段代码如下: 账  户:  <input type="text" name="userName" id="userN& ...

  5. java后台对前端输入的特殊字符进行转义

    转自:http://www.cnblogs.com/yangzhilong/p/5667165.html java后台对前端输入的特殊字符进行转义 HTML: 常见的帮助类有2个:一个是spring的 ...

  6. java后台获取Access_token的工具方法

    本方法主要通过java后台控制来获取Access_token,需要你已经知道自己的ID跟密码 因为微信的权限设置大概每天可以获取两千条,每条有效时间为2小时 /** * 输入自己的id跟密码,获取微信 ...

  7. js前台加密,java后台解密实现

    参考资料: JS前台加密,java后台解密实现

  8. java后台异步任务执行器TaskManager

    java后台异步任务执行器TaskManager 此方式基于MVC方式: 一,使用任务: @Resource private TaskManager taskManager; public strin ...

  9. fastJson java后台转换json格式数据

    什么事JSON? JSON(JavaScript Object Notation) 是一种轻量级的数据交换格式. 易于人阅读和编写.同时也易于机器解析和生成. 它基于JavaScript Progra ...

随机推荐

  1. 如何用VS进行程序调试

    VS是一个强大的IDE,如果你现在只会简单地用它查看一下执行效果,那就太大材小用了. 1. CRT函数报错 首先来说说最常见的一个编译错误.微信里常常收到这个错误的截图提问. CRT(C Runtim ...

  2. 《Python编程从入门到实践》第三章_列表简介

    什么是列表呢? 官方说明就是由一些列按特点顺序排列的元素组成.其实可以看出很多个字符串的有序组合吧,里面的内容可以随时的删除,增加,修改. 下面这个就是一个列表,python打印列表的时候会将中括号和 ...

  3. 第一个CGI程序-----完全就是普通的c语言嘛‘(*∩_∩*)′

    第一个CGI程序 ----完全就是普通的C语言嘛  '(*∩_∩*)′ PainterQ 2017年5月14日 上一篇博文里面叙述了Apache的安装和配置方法,恍恍惚惚我就拥有了自己的第一个http ...

  4. 在Caffe添加Python layer详细步骤

    本文主要讨论的是在caffe中添加python layer的一般流程,自己设计的test_python_layer.py层只是起到演示作用,没有实际的功能. 1) Python layer 在caff ...

  5. JQuery浮动层Loading页面加载特效

    之前做项目,经常需要一些浮动层加载Loading. 现在好多前端框架都能实现了,最常用的就是 artDialog 下面记录下当时的代码. <!DOCTYPE html PUBLIC " ...

  6. Ubuntu下的iptux和Windows下的飞秋互传文件

    1.问题 当Linux下的iptux是安装源里的版本时,存在下面的问题:Windows下的飞秋可以向Linux下的iptux发送文件,iptux接受正常Linux下的iputx给Windows下的飞秋 ...

  7. Easyui设置动态表格,动态导出数据实例,附Dome

    最近碰到一个需求,需要提供一个弹出页面选择列表页面需要显示的列,页面确认之后需要修改列表页面显示的表格,导出的数据也需要同步变化. 下面直接上代码 1.设置需要显示的列columus为全局对象,用于子 ...

  8. 关于MATLAB处理大数据坐标文件201762

    经过头脑风暴法想出了很多特征,目前经过筛选已经提交了两次数据,数据提交结果不尽如人意,但是收获很大. 接下来继续提取特征,特征数达到27时筛选出20条特征,并找出最佳搭配

  9. group by和count联合使用问题

    要根据用户发布的产品数量来排序做分页,使用group ) FROM( SELECT uid,COU 工作中要根据用户发布的产品数量来排序做分页,使用group by uid 用count(uid) 来 ...

  10. iOS 输入限制之 InputKit

    前言 最近接手了两个 O2O 的老项目,其中的 Bug 也不言而喻,单看项目中的布局就有 n 种不同的方式,有用纯代码的,有用 Masonry 的,有用 VFL 的,也有用 Xib 的,更有用代码约束 ...