您的位置:首页 > 理论基础 > 计算机网络

HttpClient 实现文件上传

2016-03-17 10:06 573 查看
其实搜索可以找到很多例子 但是基本没有超时设置和编码设置。

我主要也是添加代码做一个完整的例子。帮助大家也留给自己

上代码:

import org.apache.http.HttpEntity;

@ResponseBody
@RequestMapping(value = "/uploadRequest.do", produces = "application/json; charset=utf-8")
public String uploadRequest(HttpServletRequest request, MultipartFile file) throws IOException {Map<String, String> reqData = CgtUtil.getParameterMap(request);
String result = "";

String url = "http://***.com";

CloseableHttpClient httpClient = HttpClients.createDefault();
CloseableHttpResponse response = null;

try{
HttpPost httpPost = new HttpPost(url);
//设置超时时间
RequestConfig requestConfig = RequestConfig.custom()
.setConnectTimeout(3000)
.setSocketTimeout(5000).build();
httpPost.setConfig(requestConfig);
MultipartEntityBuilder multipartEntityBuilder = MultipartEntityBuilder.create();

//拼接普通的参数
//设置文本编码
ContentType contentType = ContentType.create("text/plain", "UTF-8");
for (String key : reqData.keySet()) {
multipartEntityBuilder.addTextBody(key, reqData.get(key), contentType);
}
//拼接文件 此处大多少都是用File来添加文件 由于springmvc传递文件到后台只有InputStream
// 所以这里用addBinaryBody方法
// 注意: 一定要添加 ContentType.create(file.getContentType()), file.getOriginalFilename() 否则找不到文件
multipartEntityBuilder.addBinaryBody("file", file.getInputStream(),
ContentType.create(file.getContentType()), file.getOriginalFilename());
HttpEntity httpEntity = multipartEntityBuilder.build();
httpPost.setEntity(httpEntity);

response = httpClient.execute(httpPost);

int status = response.getStatusLine().getStatusCode();
if (status == HttpStatus.SC_OK) {
HttpEntity resEntity = response.getEntity();

//获取响应内容
result = EntityUtils.toString(resEntity, Charset.forName("UTF-8"));

//销毁响应内容
EntityUtils.consume(resEntity);
} else {
logger.info("返回http状态码["+status+"],请检查请求报文或者请求地址是否正确");
}
} catch (Exception e) {
e.printStackTrace();
} finally {
if (null != response) {
response.close();
}
if (null != httpClient) {
httpClient.close();
}
}

return result;
}

jar包
<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>
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  HttpClient Upload 上传