2.HTTP响应

2.1 响应行
2.2.1 状态码
| 100-199 | 服务器成功接收客户请求,不过需要让客户机继续发送请求完成整个请求过程 |
| 200-299 | 200 成功处理 |
| 300-399 | 302 : 找别人,在响应头中需要有location属性; 304、307:找缓存,即缓存中存在页面 |
| 400-499 | 403:存在页面,但是用户没有权限访问; 404:无此页面 |
| 500-599 | 500 : 服务器内部错误 |
2.2 响应头
| Server | 服务器信息 |
| Content-Length | 响应内容的长度 |
| Content-Encoding | 服务器内容的压缩格式 |
| Content-Type | 服务器内容的格式,比如text/html ; image/jpeg |
| location |
用于状态码为302,表示别人的地址 |
| Content-disposition | 下载返回的数据 |
| Transfer-Encoding | 以块传输还是以字节传输 |
| Date | 时间 |
| refresh | 定时刷新或重定向 |
| Last-Modified | 最后改变的时间 |
| Expires | -1或0 表示无缓存 |
| ETag | 每个web资源都有一个标示符,只要web资源内容改动,标示符就会改变; |
应用1:location重定向
- response.setStatus(302);
- response.setHeader("location","http://localhost:8080/a/1.html");
response.setStatus(302);
response.setHeader("location",http://localhost:8080/a/1.html);
应用2:content-Encoding 压缩数据
- response.setHeader("content-encoding","gzip");
- ByteArrayOutputStream bout = new ByteArrayOutputStream();
- GZIPOutputStream out = new GZIPOutputStream(bout);
- out.write("Hello".getBytes());
- out.close();
- byte[] b = bout.toByteArray();
- response.getOutputStream().write(b);
电信对于网站的收费是按照出口流量收费的,因此需要压缩数据,减少费用;
应用3:content-disposition
response.setHeader("content-disposition","attachment;filename=1.jpg");
应用4:refresh
response.setHeader("refresh","3"); 定时更新 用于实时软件
response.setHeader("refresh","3;url='http://localhost:8080/1.html'"); 注册登录
应用5:content-type 返回的数据类型;
- public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
- response.setHeader("content-type", "image/ipeg");
- InputStream in = this.getServletContext().getResourceAsStream("/1.jpg");
- Java.io.OutputStream out = response.getOutputStream();
- byte[]b = new byte[1024];
- int length = 0;
- while((length=in.read(b))>0){
- out.write(b, 0, length);
- }
- out.close();
- }
