• http协议


    一.请求报文: 

    1.http协议内容:

    GET /day09/hello HTTP/1.1               -请求行
    Host: localhost:8080                    --请求头(多个key-value对象)
    User-Agent: Mozilla/5.0 (Windows NT 6.1; WOW64; rv:35.0) Gecko/20100101 Firefox/35.0
    Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
    Accept-Language: zh-cn,en-us;q=0.8,zh;q=0.5,en;q=0.3
    Accept-Encoding: gzip, deflate
    Connection: keep-alive
                                        --一个空行
    name=eric&password=123456             --(可选)实体内容
    响应(服务器-》浏览器)
    HTTP/1.1 200 OK
    Server: Apache-Coyote/1.1
    Content-Length: 24
    Date: Fri, 30 Jan 2015 01:54:57 GMT
    
    this is hello servlet!!!

    2.http协议版本

    http1.0:当前浏览器客户端与服务器端建立连接之后,只能发送一次请求,一次请求之后连接关闭。

    http1.1:当前浏览器客户端与服务器端建立连接之后,可以在一次连接中发送多次请求。(基本都使用1.1

    3.请求资源

    URL:  统一资源定位符。http://localhost:8080/day09/testImg.html。只能定位互联网资源。是URI 的子集。

    URI: 统一资源标记符。/day09/hello。用于标记任何资源。可以是本地文件系统,局域网的资源(//192.168.14.10/myweb/index.html), 可以是互联网。

    4.请求方式

    常见的请求方式: GET POSTHEADTRACEPUTCONNECT DELETE

    常用的请求方式: GET  POST

    表单提交:

    <form action="提交地址" method="GET/POST">

    <form>

    5.GET   vs  POST 区别

    1GET方式提交

    a)地址栏(URI)会跟上参数数据。以?开头,多个参数之间以&分割。

    GET /day09/testMethod.html?name=eric&password=123456 HTTP/1.1
    Host: localhost:8080
    User-Agent: Mozilla/5.0 (Windows NT 6.1; WOW64; rv:35.0) Gecko/20100101 Firefox/35.0
    Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
    Accept-Language: zh-cn,en-us;q=0.8,zh;q=0.5,en;q=0.3
    Accept-Encoding: gzip, deflate
    Referer: http://localhost:8080/day09/testMethod.html
    Connection: keep-alive

    bGET提交参数数据有限制,不超过1KB

    cGET方式不适合提交敏感密码。

    d)注意: 浏览器直接访问的请求,默认提交方式是GET方式

    2POST方式提交

    a)参数不会跟着URI后面。参数而是跟在请求的实体内容中。没有?开头,多个参数之间以&分割。

    bPOST提交的参数数据没有限制。

    cPOST方式提交敏感数据。

    POST /day09/testMethod.html HTTP/1.1
    Host: localhost:8080
    User-Agent: Mozilla/5.0 (Windows NT 6.1; WOW64; rv:35.0) Gecko/20100101 Firefox/35.0
    Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
    Accept-Language: zh-cn,en-us;q=0.8,zh;q=0.5,en;q=0.3
    Accept-Encoding: gzip, deflate
    Referer: http://localhost:8080/day09/testMethod.html
    Connection: keep-alive
    
    name=eric&password=123456

     6.请求头

    Accept: text/html,image/*      -- 浏览器接受的数据类型
    Accept-Charset: ISO-8859-1     -- 浏览器接受的编码格式
    Accept-Encoding: gzip,compress  --浏览器接受的数据压缩格式
    Accept-Language: en-us,zh-       --浏览器接受的语言
    Host: www.it315.org:80          --(必须的)当前请求访问的目标地址(主机:端口)
    If-Modified-Since: Tue, 11 Jul 2000 18:23:51 GMT  --浏览器最后的缓存时间
    Referer: http://www.it315.org/index.jsp      -- 当前请求来自于哪里
    User-Agent: Mozilla/4.0 (compatible; MSIE 5.5; Windows NT 5.0)  --浏览器类型
    Cookie:name=eric                     -- 浏览器保存的cookie信息
    Connection: close/Keep-Alive            -- 浏览器跟服务器连接状态。close: 连接关闭  keep-alive:保存连接。
    Date: Tue, 11 Jul 2000 18:23:51 GMT      -- 请求发出的时间

    7. 实体内容

    只有POST提交的参数会放到实体内容中

    8.HttpServletRequest对象

    HttpServletRequest对象作用是用于获取请求数据。

       核心的API

    请求行:

    request.getMethod();   请求方式

    request.getRequetURI()   / request.getRequetURL()   请求资源

    request.getProtocol()   请求http协议版本

    请求头:

    request.getHeader("名称")   根据请求头获取请求值

    request.getHeaderNames()    获取所有的请求头名称

    实体内容:

    request.getInputStream()   获取实体内容数据

    9.传递的请求参数如何获取

     GET方式: 参数放在URI后面

     POST方式: 参数放在实体内容中

    获取GET方式参数:

    request.getQueryString();

    获取POST方式参数:

    request.getInputStream();

    问题:但是以上两种不通用,而且获取到的参数还需要进一步地解析。

    所以可以使用统一方便的获取参数的方式:

      核心的API

    request.getParameter("参数名");  根据参数名获取参数值(注意,只能获取一个值的参数)

    request.getParameterValue("参数名“);根据参数名获取参数值(可以获取多个值的参数)

    request.getParameterNames();   获取所有参数名称列表  

     10.请求参数编码问题

    修改POST方式参数编码:

    request.setCharacterEncoding("utf-8");

    修改GET方式参数编码:

    手动解码:String name = new String(name.getBytes("iso-8859-1"),"utf-8");

     11.请求报文的代码练习:

    package com.http.requst;
    
    import java.io.IOException;
    import java.io.PrintWriter;
    import java.util.Enumeration;
    
    import javax.servlet.ServletException;
    import javax.servlet.ServletInputStream;
    import javax.servlet.http.HttpServlet;
    import javax.servlet.http.HttpServletRequest;
    import javax.servlet.http.HttpServletResponse;
    
    public class RequstExercise extends HttpServlet {
    
        /**
         * Constructor of the object.
         */
        public RequstExercise() {
            super();
        }
    
        /**
         * Destruction of the servlet. <br>
         */
        public void destroy() {
            super.destroy(); // Just puts "destroy" string in log
            // Put your code here
        }
    
        /**
         * The doGet method of the servlet. <br>
         *
         * This method is called when a form has its tag value method equals to get.
         * 
         * @param request the request send by the client to the server
         * @param response the response send by the server to the client
         * @throws ServletException if an error occurred
         * @throws IOException if an error occurred
         */
        public void doGet(HttpServletRequest request, HttpServletResponse response)
                throws ServletException, IOException {
            request.setCharacterEncoding("gb2312");
    //        System.out.println("GET方式");
    //        String value = request.getQueryString();
    //        System.out.println(value);
            //t1(request);
            //t2(request);
            //--直接获取指定名称的值
            /*
            String name = request.getParameter("user");
            String pwd = request.getParameter("pwd");
            System.out.println("用户名: " + name);
            System.out.println("密码: " + pwd);
            */
            //访问所有的
            Enumeration<String> enums = request.getParameterNames();
            while(enums.hasMoreElements()){
                String name = enums.nextElement();
                if("GET".equals(request.getMethod())){
                    name = new String(name.getBytes("iso-8859-1"), "gb2312");
                }
                //System.out.println(name + " 是: " + request.getParameter(name));//不能处理多个值
                System.out.print(name + "是: ");
                String[] values = request.getParameterValues(name);
                for(String value : values){
                    if("GET".equals(request.getMethod())){
                        value = new String(value.getBytes("iso-8859-1"), "gb2312");
                    }
                    System.out.print(value + "	");
                }
                System.out.println();
                
            }
        }
    
        private void t2(HttpServletRequest request) {
            System.out.println("Host : " + request.getHeader("Host"));
            Enumeration<String> enums = request.getHeaderNames();
            while(enums.hasMoreElements()){
                String headerName = enums.nextElement();
                System.out.println(headerName + " : " + request.getHeader(headerName));
            }
        }
    
        private void t1(HttpServletRequest request) {
            System.out.println("请求方式是:" + request.getMethod());
            System.out.println("HTTP版本:" + request.getProtocol());
            System.out.println("URI:" + request.getRequestURI());
            System.out.println("URL" + request.getRequestURL());
        }
    
        /**
         * The doPost method of the servlet. <br>
         *
         * This method is called when a form has its tag value method equals to post.
         * 
         * @param request the request send by the client to the server
         * @param response the response send by the server to the client
         * @throws ServletException if an error occurred
         * @throws IOException if an error occurred
         */
        public void doPost(HttpServletRequest request, HttpServletResponse response)
                throws ServletException, IOException {
    
    //        ServletInputStream in = request.getInputStream();
    //        byte[] buf = new byte[1024];
    //        int len = 0;
    //        while( (len=in.read(buf))!=-1 ){
    //            String str = new String(buf, 0, len);
    //            System.out.println(str);
    //        }
            doGet(request, response);
            
            
        }
    
        /**
         * Initialization of the servlet. <br>
         *
         * @throws ServletException if an error occurs
         */
        public void init() throws ServletException {
            // Put your code here
        }
    
    }

    二.响应报文

    HTTP/1.1 200 OK                --响应行
    Server: Apache-Coyote/1.1         --响应头(key-vaule)
    Content-Length: 24 
    Date: Fri, 30 Jan 2015 01:54:57 GMT
                                       --一个空行
    this is hello servlet!!!                  --实体内容

    1.状态码: 服务器处理请求的结果(状态)

    常见的状态:

    200 :  表示请求处理完成并完美返回

    302:   表示请求需要进一步细化。 404:   表示客户访问的资源找不到。

    500:   表示服务器的资源发送错误。(服务器内部错误)

    2 常见的响应头

    Location: http://www.it315.org/index.jsp   -表示重定向的地址,该头和302的状态码一起使用。
    Server:apache tomcat                 ---表示服务器的类型
    Content-Encoding: gzip                 -- 表示服务器发送给浏览器的数据压缩类型
    Content-Length: 80                    --表示服务器发送给浏览器的数据长度
    Content-Language: zh-cn               --表示服务器支持的语言
    Content-Type: text/html; charset=GB2312   --表示服务器发送给浏览器的数据类型及内容编码
    Last-Modified: Tue, 11 Jul 2000 18:23:51 GMT  --表示服务器资源的最后修改时间
    Refresh: 1;url=http://www.it315.org     --表示定时刷新
    Content-Disposition: attachment; filename=aaa.zip --表示告诉浏览器以下载方式打开资源(下载文件时用到)
    Transfer-Encoding: chunked
    Set-Cookie:SS=Q0=5Lb_nQ; path=/search   --表示服务器发送给浏览器的cookie信息(会话管理用到)
    Expires: -1                           --表示通知浏览器不进行缓存
    Cache-Control: no-cache
    Pragma: no-cache
    Connection: close/Keep-Alive           --表示服务器和浏览器的连接状态。close:关闭连接 keep-alive:保存连接

    3 HttpServletResponse对象

    HttpServletResponse对象修改响应信息:

    响应行:

    response.setStatus()  设置状态码

    响应头:

    response.setHeader("name","value")  设置响应头

    实体内容:

    response.getWriter().writer();   发送字符实体内容

    response.getOutputStream().writer()  发送字节实体内容

    4 案例- 请求重定向(Location

    5 案例- 定时刷新(refresh)

    6 案例-content-Type作用

    7.响应报文代码练习:

    package com.http.response;
    
    import java.io.File;
    import java.io.FileInputStream;
    import java.io.IOException;
    import java.io.InputStreamReader;
    import java.io.PrintWriter;
    
    import javax.servlet.ServletException;
    import javax.servlet.http.HttpServlet;
    import javax.servlet.http.HttpServletRequest;
    import javax.servlet.http.HttpServletResponse;
    
    public class ResponseExercise extends HttpServlet {
    
        /**
         * The doGet method of the servlet. <br>
         *
         * This method is called when a form has its tag value method equals to get.
         * 
         * @param request the request send by the client to the server
         * @param response the response send by the server to the client
         * @throws ServletException if an error occurred
         * @throws IOException if an error occurred
         */
        public void doGet(HttpServletRequest request, HttpServletResponse response)
                throws ServletException, IOException {
            response.setCharacterEncoding("gb2312");
            //func_response1(response);
            //refresh(response);
            //response.setHeader("content-type", "text/html");
            //response.setContentType("text/xml");
            //response.getWriter().write("<html><head><title>handsomcui</title></head><body>hello everyone</body></html>");
            response.setContentType("image/jpg");
            FileInputStream file = new FileInputStream(new File("E:/我的java程序/code/MyWeb/WebRoot/img/15.JPG"));
            int len;
            byte[] buf = new byte[1024];
            while( (len = file.read(buf)) != -1){
                response.getOutputStream().write(buf, 0, len);
            }
            file.close();
        }
    
        private void refresh(HttpServletResponse response) throws IOException {
            response.setStatus(302);
            response.setHeader("location", "/MyWeb/adv.html");
            response.sendRedirect("/MyWeb/adv.html");
            response.setHeader("refresh", "1");
            response.setHeader("refresh", "3;url=/MyWeb/adv.html");
        }
    
        private void func_response1(HttpServletResponse response)
                throws IOException {
            response.setStatus(404);
            response.sendError(404);
            response.getWriter().write("I'm handsomecui");
            response.getOutputStream().write("I'm a doubi".getBytes());
            response.setHeader("server", "handsomecui");
            response.setHeader("author", "cuigege");
            response.setHeader("Date", "2006.1.1");
        }
    
        /**
         * The doPost method of the servlet. <br>
         *
         * This method is called when a form has its tag value method equals to post.
         * 
         * @param request the request send by the client to the server
         * @param response the response send by the server to the client
         * @throws ServletException if an error occurred
         * @throws IOException if an error occurred
         */
        public void doPost(HttpServletRequest request, HttpServletResponse response)
                throws ServletException, IOException {
    
            
        }
    
    }

    三.总结:

    http协议: 浏览器和服务器之间数据传输的格式规范

    1http请求:

    格式:

    请求行

    请求头

    空行

    实体内容(POST提交的数据在实体内容中)

    重点:

    使用HttpServletRequest对象: 获取请求数据

    2http响应;

    格式:

    响应行

    响应头

    空行

    实体内容(浏览器看到的内容)

    重点:

    使用HttpServletResponse对象: 设置响应数据

  • 相关阅读:
    Xtreme ToolkitPro 初使用
    VC 播放WAV文件
    Socket Select IO模型
    SpringBoot AOP 记录操作日志、异常日志
    基于 SpringBoot + Vue3.2 + Element Plus 的后台管理系统
    一个无限级树结构配合FlyTreeView的例子
    类似百度搜索的输入框自动完成功能
    PyQuery的安装
    CreateRemoteThread的调试问题
    OD中的自定义函数
  • 原文地址:https://www.cnblogs.com/handsomecui/p/6061874.html
Copyright © 2020-2023  润新知