javaweb学习总结二十(http响应)

时间:2021-08-23 09:56:39

一:http响应

1:http响应的组成部分

状态行、响应头、空行、响应数据

javaweb学习总结二十(http响应)

2:状态行

javaweb学习总结二十(http响应)

常用状态码:

200:请求成功

302:请求路径已经转移,请访问别的地址

307或者304: 请访问缓存信息

404:访问资源不存在

403:资源存在,但是没有访问权限

500:服务器内部错误

二:HTTP协议响应头

1:常用响应头

javaweb学习总结二十(http响应)

2:常用响应头分析演示

1):location:http://www.it315.org/index.jsp   和403搭配使用,告诉浏览器重定向到其他的页面

代码如下:

 public class ServletDemo extends HttpServlet {

     public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doPost(request, response);
} public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setStatus(302); // 302状态码代表资源路径转移,重定向到新的资源路径
response.setHeader("location", "/servletDemo/1.html"); } }

web.xml配置:

 <?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.5"
xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
<servlet>
<description>This is the description of my J2EE component</description>
<display-name>This is the display name of my J2EE component</display-name>
<servlet-name>ServletDemo</servlet-name>
<servlet-class>com.hlcui.servlet.ServletDemo</servlet-class>
</servlet> <servlet-mapping>
<servlet-name>ServletDemo</servlet-name>
<url-pattern>/servlet/ServletDemo</url-pattern>
</servlet-mapping> <welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
</web-app>

tomcat服务器启动后,访问路径:http://localhost:8080/servletDemo/servlet/ServletDemo

javaweb学习总结二十(http响应)

2):Server  Apache tomcat  告诉浏览器服务器的类型信息

3):Content-Encoding:gzip  告诉浏览器服务器回送数据的压缩类型

4):Content-Length: 80   告诉浏览器呢服务器回送数据大小

演示代码如下:

 public class ServletDemo extends HttpServlet {

     public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doPost(request, response);
} public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
String content = "wertyuiopdfghjkl;dfghjklertyuiodfghjkcvbnmcvb"
+ "wertyuiopdfghjkl;dfghjklertyuiodfghjkcvbnmcvbtyuiopvbhnjk"
+ "wertyuiopdfghjkl;dfghjklertyuiodfghjkcvbnmcvbtyuiopvbhnjk"
+ "wertyuiopdfghjkl;dfghjklertyuiodfghjkcvbnmcvbtyuiopvbhnjk"
+ "wertyuiopdfghjkl;dfghjklertyuiodfghjkcvbnmcvbtyuiopvbhnjk"
+ "wertyuiopdfghjkl;dfghjklertyuiodfghjkcvbnmcvbtyuiopvbhnjk"
+ "wertyuiopdfghjkl;dfghjklertyuiodfghjkcvbnmcvbtyuiopvbhnjk"; System.out.println("压缩前数据大小:" + content.getBytes().length);
ByteArrayOutputStream array = new ByteArrayOutputStream();
GZIPOutputStream gzip = new GZIPOutputStream(array);
gzip.write(content.getBytes()); // 将内容进行压缩
gzip.close(); System.out.println("压缩后数据大小:" + array.size());
// 告诉浏览器数据压缩格式以及大小
response.setHeader("Content-Encoding", "gzip");
response.setHeader("Content-Length", array.size() + "");
// 将内容写到浏览器
response.getOutputStream().write(array.toByteArray()); } }

启动tomcat服务器,访问路径:http://localhost:8080/servletDemo/servlet/ServletDemo

浏览器显示压缩后的数据:

javaweb学习总结二十(http响应)

javaweb学习总结二十(http响应)

5):Content-Language:zh-cn  告诉浏览器服务器的语言环境

6):Content-Type:text/html ; charset=utf-8 告诉浏览器服务器回送数据的内容类型

代码如下:

 public class ServletDemo extends HttpServlet {

     public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doPost(request, response);
} public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
// 告诉浏览器显示内容格式
//response.setContentType("image/jpeg");
// 或者设置响应头的方式
response.setHeader("Content-Type", "image/jpeg");
// 读取图片文件
InputStream in = this.getServletContext().getResourceAsStream("/1.jpg");
int len = 0;
byte[] buf = new byte[1024];
while ((len = in.read(buf)) > 0) {
response.getOutputStream().write(buf, 0, len);
} } }

查看文件响应头的写法,tomcat服务器到 conf/web.xml

javaweb学习总结二十(http响应)

重新部署服务,访问url:http://localhost:8080/servletDemo/servlet/ServletDemo

javaweb学习总结二十(http响应)

7):Last-Modified:服务器告诉浏览器资源最后的修改时间,如果修改时间和缓存一直,那么就使用缓存时间,如果比缓存时间

更新,那么就重新发送数据到浏览器。

8):Refresh:1;url=http://www.baidu.com  服务器告诉浏览器每隔1秒刷新一次

代码如下:

 public class ServletDemo extends HttpServlet {

     public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doPost(request, response);
} public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
Date date = new Date();
SimpleDateFormat sdf = new SimpleDateFormat("yyyy:MM:dd HH:mm:ss"); response.setHeader("refresh", "1"); // 让日期时间每隔1秒刷新1次
response.getOutputStream().write(sdf.format(date).getBytes());
} }

javaweb学习总结二十(http响应)

refresh请求头还可以实现定时重定向页面的作用,例如注册页面注册成功后跳转到首页:

代码如下:

 public class ServletDemo extends HttpServlet {

     public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doPost(request, response);
} public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
String msg = "页面跳转中...";
response.setHeader("refresh", "5;url='http://www.baidu.com'"); // 让日期时间每隔1秒刷新1次
response.getOutputStream().write(msg.getBytes());
} }

访问页面5秒后进行页面跳转!!!

9):  content-disposition :attachment;filename=""  服务器告诉浏览器以下载的方式处理文件

 public class ServletDemo extends HttpServlet {

     public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doPost(request, response);
} public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
if ("download".equals(request.getParameter("type"))) {
response.setHeader("content-disposition",
"attachment;filename=1.jpg");
InputStream in = this.getServletContext().getResourceAsStream(
"/1.jpg");
OutputStream out = response.getOutputStream();
int len = 0;
byte[] buf = new byte[1024];
while ((len = in.read(buf)) > 0) {
out.write(buf, 0, len);
}
out.flush();
out.close();
in.close();
} else {
response.setCharacterEncoding("utf-8");
response.setContentType("text/html");
PrintWriter pw = response.getWriter();
pw.print("<html>");
pw.print("<head><script type='text/javascript'>"
+"function download(){"
+"window.open('http://localhost:8080/servletDemo/servlet/ServletDemo?type=download')"
+"}"
+"</script>"
+"</head>");
/*pw
.print("<body><a href='http://localhost:8080/servletDemo/servlet/ServletDemo?type=download'>下载</a></body>");*/
pw.print("<body><button onclick='download();'>下载</button></body>");
pw.print("</html>");
pw.close(); } }
}

访问url:http://localhost:8080/servletDemo/servlet/ServletDemo

显示“下载”按钮,点击下载按钮下载文件:

javaweb学习总结二十(http响应)

javaweb学习总结二十(http响应)

10):Cache-control:no-cache  或者 pragma : no-cache 或者 expires :-1都是控制浏览器

是否缓存服务器数据,一般情况下都写上,就不会有浏览器兼容问题。

11):range 断续下载

javaweb学习总结二十(http响应)

如果下载服务器的某个资源,已经下载一半,突然网络断了,下次有网络再下载另一半资源,迅雷下载比较常见:

代码演示:

 /**
*
*/
package com.hlcui.socket; import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL; /**
* @author Administrator 实现断续下载文件
*/
public class DownloadRange { /**
* @param args
* @throws IOException
*/
public static void main(String[] args) throws IOException {
URL url = new URL("http://localhost:8080/servletDemo/111.txt");
HttpURLConnection conn = (HttpURLConnection) url.openConnection(); // 设置断续下载,从第4个字符开始下载
conn.addRequestProperty("range", "bytes=4-");
InputStream in = conn.getInputStream();
FileOutputStream out = new FileOutputStream("F:\\111.txt",true); //追加到内容的末尾
int len = 0;
byte[] buf = new byte[1024];
while ((len = in.read(buf)) > 0) {
out.write(buf, 0, len);
}
in.close();
out.close(); } }

代码均已经验证!