一、HttpEntity 获取请求
HttpEntity:可以获取请求的内容(包括请求头与请求体)
页面提交数据:
<form action="${ctp}/testHttpEntity" method="post" enctype="multipart/form-data">
<input name="username" value="tomcat" />
<input name="password" value="123456" />
<input name="file" type="file">
<input type="submit" />
</form>
控制器方法:
/**
* 如果参数位置写 HttpEntity<String> str,可以获取请求信息
* 不仅可以获取到请求体,可以获取到请求头数据
*
* @RequestHeader("") 根据key获取请求头
* @param str
* @return
*/
@RequestMapping(value = "/testHttpEntity")
public String testHttpEntity(HttpEntity<String> str) {
System.out.println("HttpEntity:" + str);
return "success";
}
输出:
请求体与请求头之间会以 逗号 进行分割。
二、ResponseEntity<T> 设置响应
ResponseEntity 用于设置响应头、响应体与响应状态码。
示例:
/**
* ResponseEntity<T>: T 响应体内容的类型
* @return
*/
@RequestMapping(value = "/testResponseEntity")
public ResponseEntity<String> testResponseEntity() {
String body = "<h1>success</h1>";
MultiValueMap<String, String> headers = new HttpHeaders();
headers.add("set-cookie", "username=Tom");
ResponseEntity<String> responseEntity = new ResponseEntity<>(body, headers, HttpStatus.OK);
return responseEntity;
}
浏览器:
利用 ResponseEntity 实现文件下载:
/**
* SpringMVC 文件下载
* @param request
* @return
* @throws Exception
*/
@RequestMapping(value = "/download")
public ResponseEntity<byte[]> fileDown(HttpServletRequest request) throws Exception {
//1.获取下载的文件的流
//获取文件的真实路径
String fileName = "jquery-1.8.2.min.js";
ServletContext servletContext = request.getServletContext();
String realPath = servletContext.getRealPath("/js/jquery-1.8.2.min.js");
FileInputStream fileInputStream = new FileInputStream(realPath);
//将整个文件放入到 byte 数组中, available() 获取输入流所读取的文件的最大字节数
byte[] tmp = new byte[fileInputStream.available()];
fileInputStream.read(tmp);
fileInputStream.close();
//2. 将要下载的文件流返回
//设置请求头
MultiValueMap<String, String> headers = new HttpHeaders();
headers.add("Content-Disposition", "attachment;filename=" + fileName);
//将响应数据到客户端
// ResponseEntity<T>(T body, MultiValueMap<String,String> headers, HttpStatus statusCode)
// body 设置响应体
// headers 设置请求头
// statusCode 设置响应状态
ResponseEntity<byte[]> responseEntity = new ResponseEntity<>(tmp, headers, HttpStatus.OK);
return responseEntity;
}