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. TypeScript 编译器源码研究(一)

    TypeScript (以下简称 TS)是一个非常强大的语言,其编译器源码超过 10000 行. 源码在 Github 可以找到:https://github.com/Microsoft/TypeSc ...

  2. liunx用户管理的基本命令

    1.passwd   修改用户密码 2.useradd 用户组名         增加用户组 3.su 用户名     切换用户名 4.usermod   用户更改 5.userdel    用户删除

  3. elastic job简单用法

    public class JobMain { //配置注册中心 private ZookeeperConfiguration zkConfig = new ZookeeperConfiguration ...

  4. django 远程数据库mysql migrate失败报error 1045之 解决方案

    Access denied for user 'root'@'localhost' (using password: YES)       ERROR 1045: Access denied for ...

  5. SQL Server获取指定行的数据

    SQL Server获取指定行(如第二行)的数据   --SQL Server获取指定行(如第二行)的数据-- --法一(对象法)-- select * from ( select * , numbe ...

  6. Bloom Filter(布隆过滤器)的概念和原理

    Bloom filter 适用范围:可以用来实现数据字典,进行数据的判重,或者集合求交集 基本原理及要点: 对于原理来说很简单,位数组+k个独立hash函数.将hash函数对应的值的位数组置1,查找时 ...

  7. ThinkPHP 的一个神秘版本 ThinkPHP 1.2

    ThinkPHP 的一个神秘版本 ThinkPHP 1.2 询问过 ThinkPHP 官网的小伙伴都知道,偶尔 ThinkPHP 故障时会出现 ThinkPHP 1.2(下次看到就截图下来). 但是我 ...

  8. greasemonkey修改网页内指定函数

    greasemonkey replace function? 方法1:编写GM代码 alert("hello2"); var mydiv =document.getElementB ...

  9. 【转】每天一个linux命令(48):watch命令

    原文网址:http://www.cnblogs.com/peida/archive/2012/12/31/2840241.html watch是一个非常实用的命令,基本所有的Linux发行版都带有这个 ...

  10. java 中的 hashcode

    在Java的Object类中有一个方法: public native int hashCode(); 根据这个方法的声明可知,该方法返回一个int类型的数值,并且是本地方法,因此在Object类中并没 ...