HttpClient上传下载文件

java
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));
}

http://stackoverflow.com/questions/10960409/how-do-i-save-a-file-downloaded-with-httpclient-into-a-specific-folder

HttpClient上传下载文件的更多相关文章

  1. HttpClient 上传/下载文件计算文件传输进度

    1.使用ProgressMessageHandler 获取进度 using namespace System.Net.Http; HttpClientHandler hand = new HttpCl ...

  2. rz和sz上传下载文件工具lrzsz

    ######################### rz和sz上传下载文件工具lrzsz ####################################################### ...

  3. linux上很方便的上传下载文件工具rz和sz

    linux上很方便的上传下载文件工具rz和sz(本文适合linux入门的朋友) ##########################################################&l ...

  4. shell通过ftp实现上传/下载文件

    直接代码,shell文件名为testFtptool.sh: #!/bin/bash ########################################################## ...

  5. SFTP远程连接服务器上传下载文件-qt4.8.0-vs2010编译器-项目实例

    本项目仅测试远程连接服务器,支持上传,下载文件,更多功能开发请看API自行开发. 环境:win7系统,Qt4.8.0版本,vs2010编译器 qt4.8.0-vs2010编译器项目实例下载地址:CSD ...

  6. linux下常用FTP命令 上传下载文件【转】

    1. 连接ftp服务器 格式:ftp [hostname| ip-address]a)在linux命令行下输入: ftp 192.168.1.1 b)服务器询问你用户名和密码,分别输入用户名和相应密码 ...

  7. C#实现http协议支持上传下载文件的GET、POST请求

    C#实现http协议支持上传下载文件的GET.POST请求using System; using System.Collections.Generic; using System.Text; usin ...

  8. 初级版python登录验证,上传下载文件加MD5文件校验

    服务器端程序 import socket import json import struct import hashlib import os def md5_code(usr, pwd): ret ...

  9. 如何利用京东云的对象存储(OSS)上传下载文件

    作者:刘冀 在公有云厂商里都有对象存储,京东云也不例外,而且也兼容S3的标准因此可以利用相关的工具去上传下载文件,本文主要记录一下利用CloudBerry Explorer for Amazon S3 ...

随机推荐

  1. Ubuntu:替换DASH图标

    替换DASH图标 替换ubuntu搜索的图标 默认图标位置 备份 sudo mv /usr/share/unity/icons/launcher_bfb.png /usr/share/unity/ic ...

  2. SWIFT中使用AFNetwroking访问网络数据

    AFNetworking 是 iOS 一个使用很方便的第三方网络开发框架,它可以很轻松的从一个URL地址内获取JSON数据. 在使用它时我用到包管理器Cocoapods 不懂的请移步: Cocoapo ...

  3. MySQLzip压缩文件格式安装教程

    MySQL是一个小巧玲珑但功能强大的数据库,目前十分流行.但是官网给出的安装包有两种格式,一个是msi格式,一个是zip格式的.很多人下了zip格式的解压发现没有setup.exe,面对一堆文件一头雾 ...

  4. css怎么让li水平排列和div居中

    让li向左浮动即可 给div定一个宽度,然后margin:0 auto;即可:

  5. 广播中receiver配置需要注意data的配置

    1.sd卡的转载和卸载 这个需要配置好android:scheme=“file” 要不然是检测不到的 2.在安装应用或者卸载应用都要有一个约束,要不然是不会执行的.而这个约束条件为package. 但 ...

  6. linux学习——sed工具

    命令格式: sed [-nefr] [动作] 1.sed可以分析标准输入(STDIN)的数据,然后将数据处理后,再将他输出到标准输出(STDOUT),他有替换.删除.新增.选定特定行等处理功能.sed ...

  7. php empty详解

    判断字符串是否为空,可以这么判断: if ($value=="") ...    * 格式:bool empty ( mixed var )    * 功能:检查一个变量是否为空  ...

  8. opencart安装和使用PHPMailer

    一.安装PHPMailer 1)先给opencart项目安装vqmod 下载最新版本: http://code.google.com/p/vqmod (目前最新版本是vqmod-2.5.1-stand ...

  9. ThinkPHP5 控制器中怎么实现 where id = 2 or id = 3 这个查询语句?

    使用 whereOr whereIn();  (来自 ★C̶r̶a̶y̶o̶n-杭州 ) 为什么不用数组啊,array('eq', array(1,2),'or') (来自 supler)

  10. tomcat源码阅读之Server和Service接口解析

    tomcat中的服务器组件接口是Server接口,服务接口是Service,Server接口表示Catalina的整个servlet引擎,囊括了所有的组件,提供了一种优雅的方式来启动/关闭Catali ...