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);// 把文件转换成流对象FileBodyFileBody 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() {@Overridepublic 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 valueRequestConfig 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

转载于:https://www.cnblogs.com/weenix/p/5287271.html

HttpClient上传下载文件相关推荐

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

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

  2. SecureCRT上传下载文件

    2019独角兽企业重金招聘Python工程师标准>>> SecureCRT是一个仿真终端连接工具.它可以方便的连接SSH服务器,远程管理Linux.同时,它还能使用多种协议方便的上传 ...

  3. Linux下支持rz/sz上传下载文件

    )    工具说明 在SecureCRT这样的ssh登录软件里, 通过在Linux界面里输入rz/sz命令来上传/下载文件. 对于RHEL5, rz/sz默认没有安装所以需要手工安装. sz: 将选定 ...

  4. python实现文件下载-python实现上传下载文件功能

    最近刚学python,遇到上传下载文件功能需求,记录下! django web项目,前端上传控件用的是uploadify. 文件上传 - 后台view 的 Python代码如下: @csrf_exem ...

  5. 在Windows上使用终端模拟程序连接操作Linux以及上传下载文件

    在Windows上使用终端模拟程序连接操作Linux以及上传下载文件 [很简单,就是一个工具的使用而已,放这里是做个笔记.] 刚买的云主机,或者是虚拟机里安装的Linux系统,可能会涉及到在windo ...

  6. python文件拷贝并校验_初级版python登录验证,上传下载文件加MD5文件校验

    importosimportjsonimportsocketimportstructimporthashlib#import time deflogin(): usr= input('请输入用户名:' ...

  7. JavaWeb:上传下载文件

    1. 文件上传概述 1.1 文件上传的作用 例如网络硬盘!就是用来上传下载文件的. 在智联招聘上填写一个完整的简历还需要上传照片呢. 1.2 文件上传对页面的要求 上传文件的要求比较多,需要记一下: ...

  8. Linux下scp无密码上传 下载 文件 目录的方法

    这篇文章主要介绍了Linux下scp无密码上传 下载 文件 目录的方法,非常不错,具有参考借鉴价值,需要的朋友可以参考下 在Linux下远程备份的时候,需要配置scp的 无密码复制文件.目录.就把这个 ...

  9. python实现文件上传功能_python实现上传下载文件功能

    最近刚学python,遇到上传下载文件功能需求,记录下! django web项目,前端上传控件用的是uploadify. 文件上传 - 后台view 的 Python代码如下: @csrf_exem ...

最新文章

  1. 第二章 第三节 创建第一个程序
  2. SICP学习笔记(P27-P28)
  3. 自动阈值检测_金融科技讲堂之三|金融企业如何在大数据中进行异常检测(一)...
  4. 2.Java之路(Java语言开发环境搭建)
  5. Netflix:为什么建立专门的媒体数据库?
  6. Jquery常用正则验证
  7. 计算机教授丁三石,一次难忘的计算机课!!
  8. “单口相声”回归!罗永浩要开发布会了:黑科技!不售票!
  9. 如何做到每天都写代码
  10. 计算机教育工作,计算机教育教学工作总结
  11. 小白学前端之:JavaScript null 和 undefined 的区别
  12. 免费正版 Win 10/8/7操作系统虚拟机镜像下载
  13. 【嵌入式】---- 单片机常用单位
  14. 夜幕下的区块链:揭露区块链评级的猫腻
  15. java余弦距离_使用TensorFlow实现余弦距离/欧氏距离(Euclideandistance)以及Attention矩阵的计算...
  16. 最新版!国内IT软件外包公司汇总~
  17. HJ68 成绩排序 ●●
  18. (转载)MFC入门(四)  作者 zhoujiamurong
  19. Win7管理受信任证书 - CA证书 - 系统根证书
  20. slam 常用依赖库CMakeLists.txt 编写

热门文章

  1. 编程语言对比 执行文件
  2. opencv-api adaptiveThreshold
  3. kafka jar包_Kafka系列文章之安装测试-第2篇
  4. 通过bginfo小工具让用户自己查看用户名与IP地址信息
  5. 数据传输服务 DTS > 数据迁移 > 从自建数据库迁移至阿里云 > 源库为MySQL > 从自建MySQL迁移至RDS MySQL
  6. Json学习总结(6)——Fastjson远程代码执行漏洞
  7. Mysql学习总结(57)——MySQL查询当天、本周、本月、上周、本周、上月、距离当前现在6个月数据
  8. element table多选表格_【经验总结】vue + element-ui 踩坑—— table 篇
  9. libsvm2.89在matlab,libsvm-mat-2.89-3工具箱,方便实用
  10. java String.intern();