HTTP请求头提供了请求、响应或者其他的发送实体的信息,HTTP消息头用来准确描述正在获取的资源、服务器或者客户端的行为,定义了HTTP事务中的具体操作参数。
几个主要头的作用:
(1)Content-Type:当前内容的MIME类型 ,服务器告诉浏览器它发送的的数据属于什么文件类型
例如:response.setContentType("application/octet-stream;charset=UTF-8");用于下载各类文件,application/octet-stream表示二进制数据,text/html表示HTML,text/plain表示普通文本
(2)Content-Disposition:对已知MIME类型资源的描述,浏览器可以根据这个响应头决定是对返回资源的动作,如:将其下载或是打开。
文件名乱码问题
response.setHeader("Content-Disposition", String.format("attachment; filename=\"%s\"",java.net.URLEncoder.encode(filename, "UTF-8")));
(3)Expires:指定一个日期/时间,超过该时间则认为此回应已经过期
response.setHeader("Expires", "0");
(4)Pragma:与具体的实现相关,这些响应头可能在请求/回应链中的不同时候产生不同的效果
response.setHeader("Pragma", "no-cache");
public static void handleDownloadAndDelete(String filePath,
HttpServletRequest request, HttpServletResponse response) {
File file = new File(filePath);
try (FileInputStream fis = new FileInputStream(file);
ServletOutputStream outputStream = response.getOutputStream()) {
String filename = file.getName();
response.setHeader("Content-Disposition", String.format(
"attachment; filename=\"%s\"",
java.net.URLEncoder.encode(filename, "UTF-8")));
response.setContentType("application/octet-stream;charset=UTF-8");
response.setHeader("Pragma", "no-cache");
response.setHeader("Expires", "0");
IOUtils.copy(fis, outputStream);
outputStream.flush();
} catch (IOException e) {
logger.warn("handleDownload-Exception:", e);
}
FileUtils.deleteQuietly(file);
}
public static void handleDownloadNoDelete(String filePath,
HttpServletRequest request, HttpServletResponse response) {
File file = new File(filePath);
try (FileInputStream fis = new FileInputStream(file);
ServletOutputStream outputStream = response.getOutputStream()) {
String filename = file.getName();
response.setHeader("Content-Disposition", String.format(
"attachment; filename=\"%s\"",
java.net.URLEncoder.encode(filename, "UTF-8")));
response.setContentType("application/octet-stream;charset=UTF-8");
response.setHeader("Pragma", "no-cache");
response.setHeader("Expires", "0");
IOUtils.copy(fis, outputStream);
outputStream.flush();
} catch (IOException e) {
logger.warn("handleDownload-Exception:", e);
}
}
public static void handleDownloadfromStream(InputStream inputStream,
String fileName, HttpServletRequest request,
HttpServletResponse response) {
try (ServletOutputStream outputStream = response.getOutputStream()) {
response.setHeader("Content-Disposition", String.format(
"attachment; filename=\"%s\"",
java.net.URLEncoder.encode(fileName, "UTF-8")));
response.setContentType("application/octet-stream;charset=UTF-8");
response.setHeader("Pragma", "no-cache");
response.setHeader("Expires", "0");
IOUtils.copy(inputStream, outputStream);
outputStream.flush();
} catch (IOException e) {
logger.warn("handleDownload-Exception:", e);
}
}