Java进阶学习第三天(HTTP协议、HTTP请求、HTTP响应)

一、HTTP协议

1、http协议:对浏览器客户端和服务器端之间数据传输的格式规范

2、查看http协议的工具
① 使用火狐的firebug插件(右键 > firebug > 网络)
② 使用谷歌的“审查元素”
③ 使用系统自带的telnet工具(远程访问工具)
◆ telnet localhost 8080:访问tomcat服务器(telnet 主机地址 端口)
◆ ctrl+],然后回车:可以看到回显
◆ 输入请求内容

GET /day09/hello HTTP/1.1
Host: localhost:8080

◆ 回车,即可查看到服务器响应信息

3、http协议内容
① 请求头信息(浏览器 > 服务器)

GET /day09/hello 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
Connection: keep-alive

② 响应头信息(服务器 > 浏览器)

HTTP/1.1 200 OK
Server: Apache-Coyote/1.1
Content-Length: 24
Date: Fri, 30 Jan 2015 01:54:57 GMT

二、HTTP请求(request)

固定格式:

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              --(可选)实体内容

1、请求行:GET /day09/hello HTTP/1.1(从右往左)
① #http协议版本
◆ http1.0:当前浏览器客户端与服务器端建立连接之后,只能发送一次请求,一次请求之后连接关闭。
◆ http1.1:当前浏览器客户端与服务器端建立连接之后,可以在一次连接中发送多次请求(基本都使用1.1)
② #请求资源
◆ URL:统一资源定位符。http://localhost:8080/day09/index.html。只能定位互联网资源。是URI的子集。
◆ URI: 统一资源标记符。/day09/hello。用于标记任何资源。可以是本地文件系统,局域网的资源(//192.168.14.10/myweb/index.html),或者是互联网。
③ #请求方式
◆ 常见的请求方式: GET 、POST、HEAD、TRACE、PUT、CONNECT、DELETE
◆ 常用的请求方式: GET 和 POST
◆ 应用:表单提交

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

2、GET和POST的区别
① GET方式提交

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

◆ 地址栏(URI)会跟上参数数据,以?开头,多个参数之间以&分割
◆ GET提交参数数据有限制,不超过1KB
◆ GET方式不适合提交敏感密码
◆ 注意: 浏览器直接访问的请求的默认提交方式是GET方式
② POST方式提交

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

◆ 参数不会跟着URI后面,参数而是跟在请求的实体内容中,没有?开头,多个参数之间以&分割
◆ POST提交的参数数据没有限制
◆ POST方式提交敏感数据

3、请求头

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     -- 请求发出的时间

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

5、HttpServletRequest对象:作用是用于获取请求数据
① Tomcat服务器接收到浏览器发送的请求数据,然后封装到HttpServetRequest对象
② Tomcat服务器调用doGet方法,然后把request对象传入到servlet中

public class RequestDemo1 extends HttpServlet {
    public void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        //从request对象取出请求数据。
        //t1(request);
        //t2(request);  
    }

    // 为了接收POST方式提交的请求
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse resp)
            throws ServletException, IOException {
        //得到实体内容
        InputStream 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);
        }
    }

    //请求头
    private void t2(HttpServletRequest request) {
        String host = request.getHeader("Host"); //根据头名称的到头的内容
        System.out.println(host);

        //遍历所有请求头
        Enumeration<String> enums = request.getHeaderNames(); //得到所有的请求头名称列表,返回值相当于迭代器
        while(enums.hasMoreElements()){//判断是否有下一个元素
            String headerName = enums.nextElement(); //取出下一个元素
            String headerValue = request.getHeader(headerName);
            System.out.println(headerName+":"+headerValue);
        }
    }

    //请求行
    private void t1(HttpServletRequest request) {
        System.out.println("请求方式:"+request.getMethod());//请求方式
        System.out.println("URI:"+request.getRequestURI());//请求资源
        System.out.println("URL:"+request.getRequestURL());
        System.out.println("http协议版本:"+request.getProtocol());//http协议
    }
}

③ 核心的API
◆ 请求行:

request.getMethod();    -- 请求方式
request.getRequetURI() / request.getRequetURL()   -- 请求资源
request.getProtocol();  -- 请求http协议版本

◆ 请求头:

request.getHeader("头名称");    -- 根据请求头获取请求值
request.getHeaderNames();      -- 获取所有的请求头名称

◆ 实体内容:

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

6、service 和 doXX方法的区别

public class RequestDemo2 extends HttpServlet {
/**
 * 注意:tomcat服务器首先会调用servlet的service方法,然后在service方法中再根据请求方式来分别调用对应的doXX方法
 * (例如,如果是GET请求方式,在service方法中调用doGet方法)
 * 
 *   因为最常的请求方式是GET和POST,所以编写servlet程序只需要覆盖doGet和doPost即可!!!!
 */

    /*@Override
    protected void service(HttpServletRequest req, HttpServletResponse resp)
            throws ServletException, IOException {
        System.out.println(req.getMethod());
        System.out.println("service方法被调用");
    }*/

    //该方法用于接收浏览器的Get方式提交的请求
    public void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        System.out.println("GET方式提交");
    }

    //该方法用于接收浏览器的Post方式提交的请求
    public void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        System.out.println("Post方式提交");
    }
}

7、案例1:获取浏览器的类型(user-agent应用)

public void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        response.setContentType("text/html;charset=utf-8");
        //获取请求头:user-agent
        String userAgent = request.getHeader("user-agent");
        System.out.println(userAgent);
        //判断用户使用的浏览器类型
        if(userAgent.contains("Firefox")){
            response.getWriter().write("你正在使用火狐浏览器");
        }else if(userAgent.contains("Chrome")){
            response.getWriter().write("你正在使用谷歌浏览器");
        }else if(userAgent.contains("Trident")){
            response.getWriter().write("你正在使用IE浏览器");
        }else{
            response.getWriter().write("地球上没有这个浏览器,建议使用火狐浏览器");
        }
    }

8、案例2:防止非法链接(referer应用)

public void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        response.setContentType("text/html;charset=utf-8"); 
        //得到referer头
        String referer = request.getHeader("referer");
        System.out.println("referer="+referer); 
        /**
         * 判断非法链接:
         *  1)直接访问的话referer=null
         *  2)如果当前请求不是来自广告   
         */
        if(referer==null || !referer.contains("/day09/adv.html")){
            response.getWriter().write("当前是非法链接,请回到首页。<a href='/day09/adv.html'>首页</a>");
        }else{
            //正确的链接
            response.getWriter().write("资源正在下载...");
        }
    }

① 第1次:CSDN/51CTO > 页面(点击下载) > 弹出广告页面(点击此处下载) > 开始下载
② 第2次:直接点击此处下载 > 转回广告页面 > 开始下载
③ 非法链接:
◆ 直接访问下载的资源
◆ 不是从广告页面过来的链接
④ referer:当前请求来自于哪里

9、传递的请求参数如何获取
GET方式: 参数放在URI后面,获取GET方式参数:request.getQueryString();
POST方式: 参数放在实体内容中,获取POST方式参数:request.getInputStream();
问题:但是以上两种不通用,而且获取到的参数还需要进一步地解析,所以可以使用统一方便的获取参数的方式,核心的API:

request.getParameter("参数名");//根据参数名获取参数值(注意,只能获取一个值的参数)
request.getParameterValue("参数名");//根据参数名获取参数值(可以获取多个值的参数)
request.getParameterNames();//获取所有参数名称列表  
public class RequestDemo5 extends HttpServlet {
    public void doGet(HttpServletRequest request, HttpServletResponse response)throws ServletException,IOException{
          request.setCharacterEncoding("utf-8");//全局设置编码
         //设置参数查询的编码,该方法只能对请求实体内容的数据编码起作用,POST提交的数据在实体内容中,所以该方法对POST方法有效!GET方法的参数放在URI后面,所以对GET方法无效!!!所以对GET方法只能用手动解码。

        System.out.println("GET方式");
        //接收GET方式提交的参数
        String value = request.getQueryString();
        System.out.println(value);

        /**
         * 统一方便地获取请求参数的方法
         */
        System.out.println("==getParameter(name):根据参数名得到参数值(只能获取一个值的参数)==");
        System.out.println(request.getMethod()+"方式");
        String name = request.getParameter("name");
        String password = request.getParameter("password");
        //手动重新解码(把iso-8859-1字符串转换成utf-8字符串)
        if("GET".equals(request.getMethod())){
            name = new String(name.getBytes("iso-8859-1"),"utf-8");
        }
        if("GET".equals(request.getMethod())){
            password = new String(password.getBytes("iso-8859-1"),"utf-8");
        }
        System.out.println(name+"="+password);

        System.out.println("==获取全部参数名称=="); 
        Enumeration<String> enums = request.getParameterNames();
        while( enums.hasMoreElements() ){
            String paramName = enums.nextElement();
            //如果参数名是hobit,则调用getParameterValues(name): 根据参数名获取参数值(可以获取多个值的同名参数)
            if("hobit".equals(paramName)){//针对多选框而言
                System.out.println(paramName+":");
                String[] hobits = request.getParameterValues("hobit");
                for(String h: hobits){
                if("GET".equals(request.getMethod())){
                        h = new String(h.getBytes("iso-8859-1"),"utf-8");
                    }
                    System.out.print(h+",");
                }
                System.out.println();
                //如果不是hobit,则调用getParameter
            }else{
                String paramValue = request.getParameter(paramName);
                if("GET".equals(request.getMethod())){
                    paramValue = new String(paramValue.getBytes("iso-8859-1"),"utf-8");
                }
                System.out.println(paramName+"="+paramValue);
            }
        }
    }

    public void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        /**
        System.out.println("POST方式");
        InputStream in = request.getInputStream();
        byte[] buf = new byte[1024];
        int len = 0;
        while(  (len=in.read(buf))!=-1 ){
            System.out.println(new String(buf,0,len));
        }
        System.out.println("POST方式");
        //根据参数名得到参数值
        String name = request.getParameter("name");
        String password = request.getParameter("password");
        System.out.println(name+"="+password);
        System.out.println("=============================");
        Enumeration<String> enums = request.getParameterNames();
        while( enums.hasMoreElements() ){
            String paramName = enums.nextElement();
            String paramValue = request.getParameter(paramName);
            System.out.println(paramName+"="+paramValue);
        }
        **/

        //一定调用doGet方式
        this.doGet(request, response);
    }
}

10、请求参数编码问题
① 修改POST方式参数编码:request.setCharacterEncoding("utf-8");
② 修改GET方式参数编码:(手动解码)String name = new String(name.getBytes("iso-8859-1"),"utf-8");
③ 修改Tomcat服务器的配置文件(不建议)

三、HTTP响应(response)

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、响应行(从左到右)
① #http协议版本
② #状态码:服务器处理请求的结果(状态)
常见的状态:
◆ 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对象:可以修改响应信息
① 响应行:

response.setStatus(404);  //设置状态码404
response.sendError(404);  //发送状态码404+404错误页面

② 响应头:response.setHeader("name","value"); //设置响应头
③ 实体内容(浏览器直接能够看到的内容就是实体内容):

response.getWriter().writer("");//发送字符实体内容
response.getOutputStream().writer("");//发送字节实体内容 

4、案例1:请求重定向(Location应用)相当于超链接跳转页面

public void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        /**
         * 需求:跳转到adv.html
         * 使用请求重定向:发送一个302状态码+location的响应头
         */

        response.setStatus(302);//发送一个302状态码
        response.setHeader("location", "/day09/adv.html"); //location的响应头       

        //请求重定向的简化写法
        response.sendRedirect("/day09/adv.html");
    }

5、案例2:定时刷新(refresh应用)

public void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        /**
         * 定时刷新
         * 原理:浏览器认识refresh头,得到refresh头之后重新请求当前资源
         */

        //response.setHeader("refresh", "1"); //每隔1秒刷新次页面

        //隔n秒之后跳转另外的资源
        response.setHeader("refresh", "3;url=/day09/adv.html");//隔3秒之后跳转到adv.html
    }

6、案例3:content-Type应用

public void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {  
        //response.setCharacterEncoding("utf-8");//设置响应实体内容编码

        //服务器发送给浏览器的数据类型和内容编码
        //response.setHeader("content-type", "text/html");
        response.setContentType("text/html;charset=utf-8");//和上面代码等价,推荐使用此方法
        //response.setContentType("text/xml");//xml格式
        //response.setContentType("image/jpg");//图片格式

        //response.getWriter().write("<html><head><title>this is tilte</title></head><body>中国</body></html>");
        response.getOutputStream().write("<html><head><title>this is tilte</title></head><body>中国</body></html>".getBytes("utf-8"));

        File file = new File("e:/1.jpg");
        //设置以下载方式打开文件
        response.setHeader("Content-Disposition", "attachment; filename="+file.getName());

        //发送图片、下载图片
        FileInputStream in = new FileInputStream("e:/1.jpg");
        byte[] buf = new byte[1024];
        int len = 0;
        //把图片内容写出到浏览器
        while( (len=in.read(buf))!=-1 ){
            response.getOutputStream().write(buf, 0, len);
        }
    }

7、完美解决项目编码问题
在每个servlet开头写:

request.setCharacterEncoding("utf-8");
response.setContentType("text/html;charset=utf-8");

猜你喜欢

转载自blog.csdn.net/Mr_GaoYang/article/details/81808341