/**
* 上传文件
* @param filePathList 文件路径
* @param filePath 在文件服务器 保存的文件夹名 例:“/poi_thumbnail/”
*/
public static void postFile(List<String> filePathList, String filePath)
throws ParseException, IOException {
CloseableHttpClient httpClient = HttpClients.createDefault();
try {
MultipartEntityBuilder build = MultipartEntityBuilder.create(); // 创建多部分的生成器
build.setMode(HttpMultipartMode.BROWSER_COMPATIBLE); // 浏览器兼容模式
build.setCharset(CharsetUtils.get("UTF-8"));
for (int i = 0; i < filePathList.size(); i++) { //多文件上传
build.addPart("uploadFile" + i,
new FileBody(new File(filePathList.get(i))));
}
//从指定的文本中创建一个StringBody。MIME 类型设置为“text / plain”。使用 {@linkplain Consts#ASCII ASCII} 字符集。
build.addPart("filePath",
new StringBody(filePath, ContentType.create("text/plain",
Consts.UTF_8)));
// 把一个普通参数和文件上传给下面这个地址 是一个 servlet
HttpPost httpPost = new HttpPost(GlobalContract.UPLOAD_URL);
// 以浏览器兼容模式运行,防止文件名乱码。
HttpEntity reqEntity = build.build();
httpPost.setEntity(reqEntity);
// System.out.println("发起请求的页面地址 " + httpPost.getRequestLine());
// 发起请求 并返回请求的响应
CloseableHttpResponse response = httpClient.execute(httpPost);
try {
// 打印响应状态
// System.out.println(response.getStatusLine());
// 获取响应对象
HttpEntity resEntity = response.getEntity();
if (resEntity != null) {
// 打印响应长度
// System.out.println("Response content length: "
// + resEntity.getContentLength());
// 打印响应内容
// System.out.println(EntityUtils.toString(resEntity,
// Charset.forName("UTF-8")));
}
// 销毁
EntityUtils.consume(resEntity);
} finally {
response.close();
}
} finally {
httpClient.close();
}
}
/**
* 下载文件
*
* @param url
* http://www.xxx.com/img/333.jpg
* @param destFileName
* xxx.jpg/xxx.png/xxx.txt
*/
public static void getFile(String url, String destFileName)
throws ClientProtocolException, IOException {
CloseableHttpClient httpclient = HttpClients.createDefault(); //创建 HttpClient 的实例
HttpGet httpget = new HttpGet(url); //创建某种连接方法的实例
HttpResponse response = httpclient.execute(httpget); // 调用第一步中创建好的实例的 execute 方法来执行第二步中创建好的 method 实例
HttpEntity entity = response.getEntity(); //读 response 获取此响应的消息实体(如果有的话)。
InputStream in = entity.getContent(); // 返回实体的内容流。
File file = new File(destFileName);
try {
FileOutputStream fout = new FileOutputStream(file); //创建一个 向指定 File 对象表示的文件中 写入数据的文件输出流。
int l = -1;
byte[] tmp = new byte[1024];
while ((l = in.read(tmp)) != -1) {
fout.write(tmp, 0, l);
// 注意这里如果用OutputStream.write(buff)的话,图片会失真,大家可以试试
}
fout.flush();
fout.close();
} finally {
// 关闭低层流。
in.close();
}
httpclient.close(); //释放连接。无论执行方法是否成功,都必须释放连接
}
HttpClient 实现上传下载
最新推荐文章于 2025-07-11 14:43:47 发布