HttpClient上传下载文件
HttpClient上传下载文件
Maven依赖
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
<version>4.5.1</version>
</dependency>
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpmime</artifactId>
<version>4.5.1</version>
</dependency>
<dependency>
<groupId>eu.medsea.mimeutil</groupId>
<artifactId>mime-util</artifactId>
<version>2.1.3</version>
</dependency>
<dependency>
<groupId>javax</groupId>
<artifactId>javaee-api</artifactId>
<version>7.0</version>
</dependency>
上传文件
/**
* 上传文件
*
* @param url
* 上传路径
* @param file
* 文件路径
* @param stringBody
* 附带的文本信息
* @return 响应结果
*/
public static String upload(String url, String file, String stringBody) {
String result = "";
CloseableHttpClient httpclient = null;
CloseableHttpResponse response = null;
HttpEntity resEntity = null;
try {
httpclient = buildHttpClient();
HttpPost httppost = new HttpPost(url);
// 把文件转换成流对象FileBody
FileBody bin = new FileBody(new File(file));
StringBody comment = new StringBody(stringBody, ContentType.create(
"text/plain", Consts.UTF_8));
// 以浏览器兼容模式运行,防止文件名乱码。
HttpEntity reqEntity = MultipartEntityBuilder.create()
.setMode(HttpMultipartMode.BROWSER_COMPATIBLE)
.addPart("bin", bin).addPart("comment", comment)
.setCharset(Consts.UTF_8).build();
httppost.setEntity(reqEntity);
log.info("executing request " + httppost.getRequestLine());
response = httpclient.execute(httppost);
log.info(response.getStatusLine());
resEntity = response.getEntity();
if (resEntity != null) {
log.info("Response content length: "
+ resEntity.getContentLength());
result = EntityUtils.toString(resEntity, Consts.UTF_8);
}
} catch (Exception e) {
log.error("executing request " + url + " occursing some error.");
log.error(e);
} finally {
try {
EntityUtils.consume(resEntity);
response.close();
httpclient.close();
} catch (IOException e) {
log.error(e);
}
}
return result;
}
下载文件
/**
* 下载文件
* @param url 下载url
* @param fileName 保存的文件名(可以为null)
*/
public static void download(String url, String fileName) {
String path = "G:/download/";
CloseableHttpClient httpclient = null;
CloseableHttpResponse response = null;
HttpEntity entity = null;
try {
httpclient = buildHttpClient();
HttpGet httpget = new HttpGet(url);
response = httpclient.execute(httpget);
entity = response.getEntity();
// 下载
if (entity.isStreaming()) {
String destFileName = "data";
if (!isBlank(fileName)) {
destFileName = fileName;
} else if (response.containsHeader("Content-Disposition")) {
String dstStr = response.getLastHeader(
"Content-Disposition").getValue();
dstStr = decodeHeader(dstStr);
//使用正则截取
Pattern p = Pattern.compile("filename=\"?(.+?)\"?$");
Matcher m = p.matcher(dstStr);
if (m.find()) {
destFileName = m.group(1);
}
} else {
destFileName = url.substring(url.lastIndexOf("/") + 1);
}
log.info("downloading file: " + destFileName);
FileOutputStream fos = null;
try {
fos = new FileOutputStream(path + destFileName);
entity.writeTo(fos);
} finally {
fos.close();
}
log.info("download complete");
} else {
log.error("Not Found");
log.info(EntityUtils.toString(entity));
}
} catch (Exception e) {
log.error("downloading file from " + url + " occursing some error.");
log.error(e);
} finally {
try {
EntityUtils.consume(entity);
response.close();
httpclient.close();
} catch (IOException e) {
log.error(e);
}
}
}
可信任的SSL的HttpClient构建方法
/**
* 构建可信任的https的HttpClient
*
* @return
* @throws Exception
*/
public static CloseableHttpClient buildHttpClient() throws Exception {
SSLContext sslContext = new SSLContextBuilder().loadTrustMaterial(null,
new TrustStrategy() {
@Override
public boolean isTrusted(X509Certificate[] arg0, String arg1)
throws CertificateException {
return true;
}
}).build();
SSLConnectionSocketFactory sslSocketFactory = new SSLConnectionSocketFactory(
sslContext, new NoopHostnameVerifier());
Registry<ConnectionSocketFactory> socketFactoryRegistry = RegistryBuilder
.<ConnectionSocketFactory> create()
.register("http",
PlainConnectionSocketFactory.getSocketFactory())
.register("https", sslSocketFactory).build();
PoolingHttpClientConnectionManager connectionManager = new PoolingHttpClientConnectionManager(
socketFactoryRegistry);
// set longer timeout value
RequestConfig requestConfig = RequestConfig.custom()
.setSocketTimeout(DEFAULT_TIMEOUT)
.setConnectTimeout(DEFAULT_TIMEOUT)
.setConnectionRequestTimeout(DEFAULT_TIMEOUT).build();
CloseableHttpClient httpclient = HttpClients.custom()
.setSSLContext(sslContext)
.setConnectionManager(connectionManager)
.setDefaultRequestConfig(requestConfig).build();
return httpclient;
}
辅助方法
// 判断字符串是否为空
private static boolean isBlank(String str) {
int strLen;
if (str == null || (strLen = str.length()) == 0) {
return true;
}
for (int i = 0; i < strLen; i++) {
if ((Character.isWhitespace(str.charAt(i)) == false)) {
return false;
}
}
return true;
}
// 将header信息按照
// 1,iso-8859-1转utf-8;2,URLDecoder.decode;3,MimeUtility.decodeText;
// 做处理,处理后的string就为编码正确的header信息(包括中文等)
private static String decodeHeader(String header)
throws UnsupportedEncodingException {
return MimeUtility.decodeText(URLDecoder.decode(
new String(header.getBytes(Consts.ISO_8859_1), Consts.UTF_8),
UTF_8));
}
HttpClient上传下载文件的更多相关文章
- HttpClient 上传/下载文件计算文件传输进度
1.使用ProgressMessageHandler 获取进度 using namespace System.Net.Http; HttpClientHandler hand = new HttpCl ...
- rz和sz上传下载文件工具lrzsz
######################### rz和sz上传下载文件工具lrzsz ####################################################### ...
- linux上很方便的上传下载文件工具rz和sz
linux上很方便的上传下载文件工具rz和sz(本文适合linux入门的朋友) ##########################################################&l ...
- shell通过ftp实现上传/下载文件
直接代码,shell文件名为testFtptool.sh: #!/bin/bash ########################################################## ...
- SFTP远程连接服务器上传下载文件-qt4.8.0-vs2010编译器-项目实例
本项目仅测试远程连接服务器,支持上传,下载文件,更多功能开发请看API自行开发. 环境:win7系统,Qt4.8.0版本,vs2010编译器 qt4.8.0-vs2010编译器项目实例下载地址:CSD ...
- linux下常用FTP命令 上传下载文件【转】
1. 连接ftp服务器 格式:ftp [hostname| ip-address]a)在linux命令行下输入: ftp 192.168.1.1 b)服务器询问你用户名和密码,分别输入用户名和相应密码 ...
- C#实现http协议支持上传下载文件的GET、POST请求
C#实现http协议支持上传下载文件的GET.POST请求using System; using System.Collections.Generic; using System.Text; usin ...
- 初级版python登录验证,上传下载文件加MD5文件校验
服务器端程序 import socket import json import struct import hashlib import os def md5_code(usr, pwd): ret ...
- 如何利用京东云的对象存储(OSS)上传下载文件
作者:刘冀 在公有云厂商里都有对象存储,京东云也不例外,而且也兼容S3的标准因此可以利用相关的工具去上传下载文件,本文主要记录一下利用CloudBerry Explorer for Amazon S3 ...
随机推荐
- 解决:编辑一条彩信,附件选择添加音频,返回到编辑界面选择play,不能播放,没有声音
[操作步骤]:编辑一条彩信,附件选择添加音频(外部音频),返回到编辑界面选择play,菜单键选择view slideshow [测试结果]:不能播放,没有声音 [预期结果]:可以播放 根据以往的经验( ...
- GitLab项目迁移到Gerrit
1.在Gerrit上新建项目: 2.Gerrit项目配置权限(此处非代码): Reference:refs/* Push Annotated Tag Push Signed Tag Forge Com ...
- fopen & fcolse & fseek & ftell & fstat 文件操作函数测试
1.文件大小查询file_size.c 方法一:fseek + ftell: 方法二:ftell #include <stdio.h> #include <fcntl.h> # ...
- hadoop之HDFS运行小观察
hadoop 是当前很火的一个 大数据运行框架和平台, 对于这个神奇的大家伙我甚是搞不清楚,前段时间闲来无视便把 HADOOP 运行起来, 看着它的操作记录存储部分(操作日志), IMAGE 记录着 ...
- .NET/C# 项目如何优雅地设置条件编译符号?
条件编译符号指的是 Conditional Compilation Symbols.你可以在 Visual Studio 的项目属性中设置,也可以直接在项目文件中写入 DefineConstants ...
- 【知识笔记】Debugging
一.启动调试出现 无法启动程序 当前状态中是非法 VS工具--选项--调试--常规--启用asp.net的JavaScript调试(chrome和ie)去掉勾选 二.web.config中<cu ...
- 前端css规范
文章整理了Web前端开发中的各种CSS规范,包括文件规范.注释规范.命名规范.书写规范.测试规范等. 一.文件规范 1.文件均归档至约定的目录中(具体要求以豆瓣的CSS规范为例进行讲解): 所有的CS ...
- IBM DS存储存储性能调优
版权声明:本文为博主原创文章,未经博主同意不得转载. https://blog.csdn.net/jaminwm/article/details/26458791 ibm存储适用,其它存储有相似參数. ...
- zmediaboard-Hi3518参数及配置
1.12_13.uboot的烧写和flash分区1_21.12.1.裸机烧录uboot(1)什么叫裸机烧录?设备是空白的,未经烧录的,就叫裸机.(2)裸机烧录一个设备有2种方案:1是用外部烧录器来烧录 ...
- dongle0
*CLI> -- [dongle0] Trying to connect on /dev/ttyUSB2... 插拔dongle[Jan 13 23:42:20] WARNING[3443]: ...