/**
* 下载文件
*
* @param
* @return
*/
public void downLoad(HttpServletResponse hsr, String fileName, String uniquekey) {
Map<String, String> map = new HashMap();
map.put("uniquekey", uniquekey);
CloseableHttpClient httpClient = HttpClients.createDefault();
InputStream in = null;
OutputStream out = null;
//进行调用
try {
//设置请求时间
RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(35000).
setConnectionRequestTimeout(35000).setSocketTimeout(60000).build();
//构建一个build用来封装请求参数
URIBuilder uriBuilder = new URIBuilder(downloadUrl);
//设置参数
setHttpGetParams(map, uriBuilder);
//构建get请求
HttpGet httpGet = new HttpGet(uriBuilder.build());
httpGet.setConfig(requestConfig);
httpGet.setHeader("DataEncoding", "UTF-8");
CloseableHttpResponse response = httpClient.execute(httpGet);
HttpEntity entity = response.getEntity();
in = entity.getContent();
//获取状态
int statusCode = response.getStatusLine().getStatusCode();
if (statusCode != HttpStatus.SC_OK) {
String content = EntityUtils.toString(entity, StandardCharsets.UTF_8);
}
hsr.setCharacterEncoding("utf-8");
hsr.setContentType("application/msword");
String name = "1111.doc";
hsr.setHeader("Content-Disposition", "attachment;filename=" + java.net.URLEncoder.encode(name, "UTF-8"));
//设置存储路径
out = new BufferedOutputStream(hsr.getOutputStream());
byte[] buffer = new byte[4096];
int len = 0;
while ((len = in.read(buffer)) > 0) {
out.write(buffer, 0, len);
}
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
if (out != null) {
out.flush();
out.close();
}
if (in != null) {
in.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
/**
* 设置参数
*
* @param paramMap
* @param uriBuilder
*/
private static void setHttpGetParams(Map<String, String> paramMap, URIBuilder uriBuilder) {
if (!paramMap.isEmpty()) {
List<NameValuePair> paramList = paramMap.entrySet().stream().map(entry
-> new BasicNameValuePair(entry.getKey(), entry.getValue())).collect(Collectors.toList());
uriBuilder.addParameters(paramList);
}
}