请求流和响应流
一: 使用响应流进行响应文件(数据,图片都可以)
@GetMapping("/test")
public void getRequestMap(HttpServletRequest request, HttpServletResponse response) throws Exception {
//获取响应流
ServletOutputStream os = response.getOutputStream();
//重置响应头
response.reset();
//设置响应头 Content-Disposition 的作用:当Content-Type 的类型为要下载的类型时 , 这个信息头会告诉浏览器这个文件的名字和类型
response.setHeader("Content-disposition","attachment; filename="+"my"+".jpg");
//读取本地图片
BufferedInputStream is = new BufferedInputStream(new FileInputStream(new File("F:\\美图\\4.jpg")));
byte[] bytes = new byte[1024];
int len = 0;
while ((len = is.read(bytes)) != -1) {
os.write(bytes,0,len);
}
is.close();
os.close();
}
二: 使用请求流进行获取POST
请求数据
(一般用于读取json
请求的json
数据最好)
@PostMapping("/test")
public Map getRequestMap(HttpServletRequest request) throws Exception {
// BufferedReader is = request.getReader();
StringBuilder builder = new StringBuilder();
byte[] bytes = new byte[1024*2];
int len = 0;
ServletInputStream inputStream = null;
BufferedInputStream is = null;
try {
inputStream = request.getInputStream();
is = new BufferedInputStream(inputStream);
while ((len = is.read(bytes)) != -1) {
builder.append(new String(bytes));
}
} catch (IOException e) {
e.printStackTrace();
}finally {
IoUtil.close(inputStream);
IoUtil.close(is);
}
System.out.println(builder.toString());
Map map = JSONUtil.toBean(builder.toString(), Map.class);
return map;
}
![8B6RZn.png](https://i-blog.csdnimg.cn/blog_migrate/5d140cd91bb5f6c6cde98dbf2bb946af.png)
如果获取的流里面的数据读取为空,那可能是因为在到达Controller之前就有拦截器或者过滤器读取了一次,所以才为空,因为流只能读取一次,(解决方案看下面)
扩展资料:
MVC
框架获取请求流数据为空(request.getInputStream()
)