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 ...
随机推荐
- L2-003. 月饼(贪心)
L2-003. 月饼 简单的结构体和排序应用题 #include<iostream> #include<stdio.h> #include<algorithm> u ...
- Ubuntu 18.04 搜狗输入法无法切换到英文输入
不知道改了个什么东西,Ubuntu 中Ctrl+Space不能切换输入法了,因此不能输入英文,shell就更是没法工作,最后找到方法了: 在终端键入fcitx-config-gtk3,这时候如果直接在 ...
- HPU 1166: 阶乘问题(一)
1166: 阶乘问题(一) [数学] 时间限制: 1 Sec 内存限制: 128 MB提交: 58 解决: 24 统计 题目描述 小H对阶乘!很感兴趣.现在他想知道N!N!的位数,由于NN太大了,所以 ...
- PAT天梯:L1-019. 谁先倒
L1-019. 谁先倒 时间限制 400 ms 内存限制 65536 kB 代码长度限制 8000 B 判题程序 Standard 作者 陈越 划拳是古老中国酒文化的一个有趣的组成部分.酒桌上两人划拳 ...
- 《DSP using MATLAB》Problem 4.21
快到龙抬头,居然下雪了,天空飘起了雪花,温度下降了近20°. 代码: %% -------------------------------------------------------------- ...
- 利用GPU改善程序性能的一点心得
1. 硬件方面 a. 流处理器个数 Gpu内部的计算单元个数,决定分析模块实时性的关键因素. 实测效果: gtx760 1152个 Gtx960 1024个 单路1080p运动 ...
- leetcode:Pascal's Triangle【Python版】
1.这道题一次提交就AC了: 2.以前用C语言实现的话,初始化二维数组全部为0,然后每行第一个元素为1,只需要用a[i][j] = a[i-1][j]+a[i-1][j-1]就可以了: 3.在Pyth ...
- lets encrypt 申请nginx 泛域名
1. 安装certbot工具 wget https://dl.eff.org/certbot-auto chmod a+x ./certbot-auto 2. 申请通配符域名 ./certbot-au ...
- 使用VBS发邮件
NameSpace = "http://schemas.microsoft.com/cdo/configuration/"set Email = CreateObject(&quo ...
- ZooKeeper 知识点
zookeeper 命令: 命令 说明 ./zkServer.sh start 启动ZooKeeper(终端执行) ./zkServer.sh stop 停止ZooKeeper(终端执行) ./zkC ...