java后台调用下载文件接口获取文件名文件流并且下载文件
发布时间
阅读量:
阅读量
JSONObject datatokenJson = new JSONObject();//data域
datatokenJson.put("gridFsId", "607f90ab0e72467a7bd1328b");
String jsonStr = JSONObject.toJSONString(datatokenJson);
CloseableHttpClient httpClient = HttpClients.createDefault();
HttpPost post = new HttpPost("http://192.168.28.130:8080/supportingPlatformTygn/unstructured/download/gridFsId");
StringEntity postEntity = new StringEntity(jsonStr, "UTF-8");
post.setEntity(postEntity);
//设置消息头
post.setHeader(new BasicHeader("Content-Type", "application/json"));
post.setHeader(new BasicHeader("Accept", "application/json"));
post.setHeader(new BasicHeader("apptoken", "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJqdGkiOiI1ODQ0NTIxYy0xZjA5LTRkODctODA0Mi0zMWI2ODc5YzQyY2MiLCJpYXQiOjE2MTc3ODM0MjgsImlzcyI6InVzZXIiLCJ1c2VySWQiOiI0MDI4ODMzMTc1NGEyYTc1MDE3NTRhYTZhYzY1MDAyNCJ9.RMZ59r9XFeUpRGQ48_bZlivnHFyOfj20zEG2KcDBOy0"));
HttpResponse response = null;
try {
response = httpClient.execute(post);
// 获取header中文件名称
String fileName = "";int x=0;
try {
Header[] headers = response.getAllHeaders();
for(int i=0;i<headers.length;i++) {
System.out.println(response.getAllHeaders()[i].getValue());
if(response.getAllHeaders()[i].getValue().indexOf("filename")!=-1) {
x=i;
}
}
fileName = response.getAllHeaders()[x].getValue().split(";")[1].split("=")[1];
if (httpServletRequest.getHeader("User-Agent").toUpperCase().indexOf("MSIE") < 0){
fileName = new String(fileName.getBytes("ISO8859-1"),"GBK");
httpServletResponse.setHeader("Content-Disposition", "attachment; filename="+ fileName);
} else{
fileName = URLDecoder.decode(fileName, "UTF-8");
fileName = new String(fileName.getBytes("ISO8859-1"),"UTF-8");
httpServletResponse.setHeader("Content-Disposition", "attachment; filename="+ fileName);//IE浏览器
}
httpServletResponse.setContentType("application/octet-stream");
System.out.println(fileName);
} catch (Exception e) {
}
// 后去接口返回的文件流
HttpEntity entity1 = response.getEntity();
BufferedInputStream br = new BufferedInputStream(entity1.getContent());
byte[] buf = new byte[1024];
int len = 0;
// 要写入本地的文件
// FileOutputStream fileOutputStream = new FileOutputStream("D:/WorkFile/xinchuang/" + fileName);
OutputStream fileOutputStream = httpServletResponse.getOutputStream();
while ((len = br.read(buf)) != -1) {
fileOutputStream.write(buf, 0, len);
}
fileOutputStream.close();
br.close();
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
httpClient.close();
// response.close();
} catch (IOException e) {
e.printStackTrace();
}
}
全部评论 (0)
还没有任何评论哟~
