package unit;

 import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors; import org.apache.http.HttpEntity;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.mime.MultipartEntityBuilder;
import org.apache.http.entity.mime.content.FileBody;
import org.apache.http.entity.mime.content.StringBody;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils; /**
* @web http://www.mobctrl.net
* @Description: 文件下载 POST GET
*/
public class HttpClientUtils {
public static void main(String[] args) {
HttpClientUtils.getInstance().download("http://h30318.www3.hp.com/pub/softlib/software13/COL60943/al-146795-2/DJ1110_Full_WebPack_40.11.1124.exe", "D:/down/DJ1110_Full_WebPack_40.11.1124.exe", new HttpClientDownLoadProgress() {
@Override
public void onProgress(int progress) {
System.out.println("download progress = " + progress+"%");
}
}); /* // POST 同步方法
Map<String, String> params = new HashMap<String, String>();
params.put("username", "admin");
params.put("password", "admin");
HttpClientUtils.getInstance().httpPost(
"http://h30318.www3.hp.com/pub/softlib/software13/COL60943/al-146795-2/DJ1110_Full_WebPack_40.11.1124.exe", params); // GET 同步方法
HttpClientUtils.getInstance().httpGet(
"http://wthrcdn.etouch.cn/weather_mini?city=北京"); // 上传文件 POST 同步方法
try {
Map<String,String> uploadParams = new LinkedHashMap<String, String>();
uploadParams.put("userImageContentType", "image");
uploadParams.put("userImageFileName", "testaa.png");
HttpClientUtils.getInstance().uploadFileImpl(
"http://192.168.31.183:8080/SSHMySql/upload", "android_bug_1.png",
"userImage", uploadParams);
} catch (Exception e) {
e.printStackTrace();
}*/ } /**
* 最大线程池
*/
public static final int THREAD_POOL_SIZE = 5; public interface HttpClientDownLoadProgress {
public void onProgress(int progress);
} private static HttpClientUtils httpClientDownload; private ExecutorService downloadExcutorService; private HttpClientUtils() {
downloadExcutorService = Executors.newFixedThreadPool(THREAD_POOL_SIZE);
} public static HttpClientUtils getInstance() {
if (httpClientDownload == null) {
httpClientDownload = new HttpClientUtils();
}
return httpClientDownload;
} /**
* 下载文件
*
* @param url
* @param filePath
*/
public void download(final String url, final String filePath) {
downloadExcutorService.execute(new Runnable() {
@Override
public void run() {
httpDownloadFile(url, filePath, null, null);
}
});
} /**
* 下载文件
*
* @param url
* @param filePath
* @param progress
* 进度回调
*/
public void download(final String url, final String filePath, final HttpClientDownLoadProgress progress) {
downloadExcutorService.execute(new Runnable() {
@Override
public void run() {
httpDownloadFile(url, filePath, progress, null);
}
});
} /**
* 下载文件
* @param url
* @param filePath
*/
private void httpDownloadFile(String url, String filePath,
HttpClientDownLoadProgress progress, Map<String, String> headMap) {
CloseableHttpClient httpclient = HttpClients.createDefault();
try {
HttpGet httpGet = new HttpGet(url);
setGetHead(httpGet, headMap);
CloseableHttpResponse response1 = httpclient.execute(httpGet);
try {
System.out.println(response1.getStatusLine());
HttpEntity httpEntity = response1.getEntity();
long contentLength = httpEntity.getContentLength();
InputStream is = httpEntity.getContent();
// 根据InputStream 下载文件
ByteArrayOutputStream output = new ByteArrayOutputStream();
byte[] buffer = new byte[4096];
int r = 0;
long totalRead = 0;
while ((r = is.read(buffer)) > 0) {
output.write(buffer, 0, r);
totalRead += r;
if (progress != null) {// 回调进度
progress.onProgress((int) (totalRead * 100 / contentLength));
}
}
FileOutputStream fos = new FileOutputStream(filePath);
output.writeTo(fos);
output.flush();
output.close();
fos.close();
EntityUtils.consume(httpEntity);
} finally {
response1.close();
}
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
httpclient.close();
} catch (IOException e) {
e.printStackTrace();
}
}
} /**
* get请求
*
* @param url
* @return
*/
public String httpGet(String url) {
return httpGet(url, null);
} /**
* http get请求
*
* @param url
* @return
*/
public String httpGet(String url, Map<String, String> headMap) {
String responseContent = null;
CloseableHttpClient httpclient = HttpClients.createDefault();
try {
HttpGet httpGet = new HttpGet(url);
CloseableHttpResponse response1 = httpclient.execute(httpGet);
setGetHead(httpGet, headMap);
try {
System.out.println(response1.getStatusLine());
HttpEntity entity = response1.getEntity();
responseContent = getRespString(entity);
System.out.println("debug:" + responseContent);
EntityUtils.consume(entity);
} finally {
response1.close();
}
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
httpclient.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return responseContent;
} public String httpPost(String url, Map<String, String> paramsMap) {
return httpPost(url, paramsMap, null);
} /**
* http的post请求
*
* @param url
* @param paramsMap
* @return
*/
public String httpPost(String url, Map<String, String> paramsMap,
Map<String, String> headMap) {
String responseContent = null;
CloseableHttpClient httpclient = HttpClients.createDefault();
try {
HttpPost httpPost = new HttpPost(url);
setPostHead(httpPost, headMap);
setPostParams(httpPost, paramsMap);
CloseableHttpResponse response = httpclient.execute(httpPost);
try {
System.out.println(response.getStatusLine());
HttpEntity entity = response.getEntity();
responseContent = getRespString(entity);
EntityUtils.consume(entity);
} finally {
response.close();
}
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
httpclient.close();
} catch (IOException e) {
e.printStackTrace();
}
}
System.out.println("responseContent = " + responseContent);
return responseContent;
} /**
* 设置POST的参数
*
* @param httpPost
* @param paramsMap
* @throws Exception
*/
private void setPostParams(HttpPost httpPost, Map<String, String> paramsMap)
throws Exception {
if (paramsMap != null && paramsMap.size() > 0) {
List<NameValuePair> nvps = new ArrayList<NameValuePair>();
Set<String> keySet = paramsMap.keySet();
for (String key : keySet) {
nvps.add(new BasicNameValuePair(key, paramsMap.get(key)));
}
httpPost.setEntity(new UrlEncodedFormEntity(nvps));
}
} /**
* 设置http的HEAD
*
* @param httpPost
* @param headMap
*/
private void setPostHead(HttpPost httpPost, Map<String, String> headMap) {
if (headMap != null && headMap.size() > 0) {
Set<String> keySet = headMap.keySet();
for (String key : keySet) {
httpPost.addHeader(key, headMap.get(key));
}
}
} /**
* 设置http的HEAD
*
* @param httpGet
* @param headMap
*/
private void setGetHead(HttpGet httpGet, Map<String, String> headMap) {
if (headMap != null && headMap.size() > 0) {
Set<String> keySet = headMap.keySet();
for (String key : keySet) {
httpGet.addHeader(key, headMap.get(key));
}
}
} /**
* 上传文件
*
* @param serverUrl
* 服务器地址
* @param localFilePath
* 本地文件路径
* @param serverFieldName
* @param params
* @return
* @throws Exception
*/
public String uploadFileImpl(String serverUrl, String localFilePath,
String serverFieldName, Map<String, String> params)
throws Exception {
String respStr = null;
CloseableHttpClient httpclient = HttpClients.createDefault();
try {
HttpPost httppost = new HttpPost(serverUrl);
FileBody binFileBody = new FileBody(new File(localFilePath)); MultipartEntityBuilder multipartEntityBuilder = MultipartEntityBuilder
.create();
// add the file params
multipartEntityBuilder.addPart(serverFieldName, binFileBody);
// 设置上传的其他参数
setUploadParams(multipartEntityBuilder, params); HttpEntity reqEntity = multipartEntityBuilder.build();
httppost.setEntity(reqEntity); CloseableHttpResponse response = httpclient.execute(httppost);
try {
System.out.println(response.getStatusLine());
HttpEntity resEntity = response.getEntity();
respStr = getRespString(resEntity);
EntityUtils.consume(resEntity);
} finally {
response.close();
}
} finally {
httpclient.close();
}
System.out.println("resp=" + respStr);
return respStr;
} /**
* 设置上传文件时所附带的其他参数
*
* @param multipartEntityBuilder
* @param params
*/
private void setUploadParams(MultipartEntityBuilder multipartEntityBuilder,
Map<String, String> params) {
if (params != null && params.size() > 0) {
Set<String> keys = params.keySet();
for (String key : keys) {
multipartEntityBuilder
.addPart(key, new StringBody(params.get(key),
ContentType.TEXT_PLAIN));
}
}
} /**
* 将返回结果转化为String
*
* @param entity
* @return
* @throws Exception
*/
private String getRespString(HttpEntity entity) throws Exception {
if (entity == null) {
return null;
}
InputStream is = entity.getContent();
StringBuffer strBuf = new StringBuffer();
byte[] buffer = new byte[4096];
int r = 0;
while ((r = is.read(buffer)) > 0) {
strBuf.append(new String(buffer, 0, r, "UTF-8"));
}
return strBuf.toString();
}
}

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

  1. Struts的文件上传下载

    Struts的文件上传下载 1.文件上传 Struts2的文件上传也是使用fileUpload的组件,这个组默认是集合在框架里面的.且是使用拦截器:<interceptor name=" ...

  2. Android okHttp网络请求之文件上传下载

    前言: 前面介绍了基于okHttp的get.post基本使用(http://www.cnblogs.com/whoislcj/p/5526431.html),今天来实现一下基于okHttp的文件上传. ...

  3. Selenium2学习-039-WebUI自动化实战实例-文件上传下载

    通常在 WebUI 自动化测试过程中必然会涉及到文件上传的自动化测试需求,而开发在进行相应的技术实现是不同的,粗略可划分为两类:input标签类(类型为file)和非input标签类(例如:div.a ...

  4. 艺萌文件上传下载及自动更新系统(基于networkComms开源TCP通信框架)

    1.艺萌文件上传下载及自动更新系统,基于Winform技术,采用CS架构,开发工具为vs2010,.net2.0版本(可以很容易升级为3.5和4.0版本)开发语言c#. 本系统主要帮助客户学习基于TC ...

  5. 艺萌TCP文件上传下载及自动更新系统介绍(TCP文件传输)(一)

    艺萌TCP文件上传下载及自动更新系统介绍(TCP文件传输) 该系统基于开源的networkComms通讯框架,此通讯框架以前是收费的,目前已经免费并开元,作者是英国的,开发时间5年多,框架很稳定. 项 ...

  6. ssh框架文件上传下载

    <!doctype html> <html lang="en"> <head> <meta charset="UTF-8&quo ...

  7. SpringMVC——返回JSON数据&&文件上传下载

    --------------------------------------------返回JSON数据------------------------------------------------ ...

  8. 【FTP】FTP文件上传下载-支持断点续传

    Jar包:apache的commons-net包: 支持断点续传 支持进度监控(有时出不来,搞不清原因) 相关知识点 编码格式: UTF-8等; 文件类型: 包括[BINARY_FILE_TYPE(常 ...

  9. NetworkComms 文件上传下载和客户端自动升级(非开源)

    演示程序下载地址:http://pan.baidu.com/s/1geVfmcr 淘宝地址:https://shop183793329.taobao.com 联系QQ号:3201175853 许可:购 ...

  10. SpringMVC文件上传下载

    在Spring MVC的基础框架搭建起来后,我们测试了spring mvc中的返回值类型,如果你还没有搭建好springmvc的架构请参考博文->http://www.cnblogs.com/q ...

随机推荐

  1. Python之tuple的创建以及使用

    tuple又是一种有序列表,它与list只有两种不同:1.创建后不能更改.2.创建时得用() 在使用tuple的时候我们需要进行那个添加一个“,” 如果不加的话就是一个整数. 但是tuple作为一个不 ...

  2. python操作excel的读写

    1.下载xlrd和xlwt pip install xlwd pip install xlrd pip install xlutils 2.读写操作(已存在的excel) #-*- coding:ut ...

  3. resin容器更改JDK

    更改resin的jdk版本,找到resin的配置文件:Resin\contrib\init.resin文件,找到 JAVA_HOME=@JAVA_HOME@ RESIN_HOME=@resin_hom ...

  4. Serializable 和 parcelable的实现和比较

    首先这个两个接口都是用来序列化对象的 但是两者在性能和应用场合上有区别,parcelable的性能更好,但是在需要保存或者网络传输的时候需要选择Serializable因为parcelable版本在不 ...

  5. PCL—点云滤波(初步处理)

    博客转载自:http://www.cnblogs.com/ironstark/p/4991232.html 点云滤波的概念 点云滤波是点云处理的基本步骤,也是进行 high level 三维图像处理之 ...

  6. 红帽企业版RHEL7.1在研域工控板上,开机没有登陆窗口 -- 编写xorg.conf 简单三行解决Ubuntu分辩率不可调的问题

    红帽企业版RHEL7.1在研域工控板上,开机没有登陆窗口 没有登陆窗口 的原因分析: 没有登陆窗口的原因是因为有多个屏幕在工作,其中一个就是build-in 屏幕(内置的虚拟屏幕)和外接的显示器,并且 ...

  7. Spark 1.4.1中Beeline使用的gc overhead limit exceeded

    最近使用SparkSQL做数据的打平操作,就是把多个表的数据经过关联操作导入到一个表中,这样数据查询的过程中就不需要在多个表中查询了,在数据量大的情况下,这样大大提高了查询效率.   我启动了thri ...

  8. 并没有看起来那么简单leetcode Generate Parentheses

    问题解法参考 它给出了这个问题的探讨. 超时的代码: 这个当n等于7时,已经要很长时间出结果了.这个算法的复杂度是O(n^2). #include<iostream> #include&l ...

  9. 树莓派(Raspberry Pi 3) centos7 扩容内存卡

    在使用Win32DiskImager为一张空白的SD卡刷入新的centos7系统后,发现卡上的可用剩余空间并不大,用df -h查看,根目录下的空间使用率居然是25%,而且总空间也就2G左右.网上查到的 ...

  10. 整理的C#屏幕截图,控件截图程序

    代码基本从网上搜集而来,整理成以下文件: 包括屏幕截图(和屏幕上看到的一致): 以及控件截图(只要该控件在本窗口内显示完全且不被其他控件遮挡就可正确截图) using System; using Sy ...