HTTP协议:(1)HTTP请求和相关API

一、HTTP请求的知识

TCP/IP协议,关注的是客户端与服务器端之间数据是否传输成功!html

HTTP协议,是在TCP/IP协议之上封装的一层协议,关注的是数据传输的格式是否规范。java

1.一、HTTP请求的示例

HTTP请求由四部分组成:请求行、请求头、一个空行和实体内容(可选)。web

HTTP请求的组成:浏览器

|--请求行缓存

|--请求头tomcat

|--(一个空行)服务器

|--实体内容(只有POST请求时才有)cookie


HTTP请求的一个示例:app

GET /myweb/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=rk&password=123456               --(可选)实体内容


1.二、请求行

GET /myweb/hello HTTP/1.1               --请求行

#http协议版本less

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

http1.1:当前浏览器客户端与服务器端创建链接以后,能够在一次链接中发送屡次请求。(如今基本上都使用1.1)

#请求资源

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

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

#请求方式

常见的请求方式: GET 、 POST、 HEAD、 TRACE、 PUT、 CONNECT 、DELETE

经常使用的请求方式: GET  和 POST

表单提交:

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

</form>

GET   vs  POST 区别
GET方式 POST方式

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

b)GET提交参数数据有限制,不超过1KB。

c)GET方式不适合提交敏感密码。

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

a)参数不会跟着URI后面。参数而是跟在请求的实体内容中。

b)POST提交的参数数据没有限制。

c)POST方式提交敏感数据。

1.三、请求头

    Accept: text/html,p_w_picpath/*      -- 浏览器接受的数据类型
    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=rk                          -- 浏览器保存的cookie信息
    Connection: close/Keep-Alive            -- 浏览器跟服务器链接状态。close: 链接关闭  keep-alive:保存链接。
    Date: Tue, 11 Jul 2000 18:23:51 GMT      -- 请求发出的时间


1.四、实体内容

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


二、HttpServletRequest对象

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

2.一、HttpServletRequest对象核心API

HttpServletRequest对象核心API
类别 API
请求行

request.getMethod();   请求方式

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

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

请求头

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

request.getHeaderNames()    获取全部的请求头名称

实体内容

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

2.二、service和doXXX之间的关系

Servlet继承关系以下:

|-javax.servlet.Servlet接口

|-javax.servlet.GenericServlet抽象类

|-javax.servlet.http.HttpServlet抽象类


在javax.servlet.Servlet接口中有一个service方法,以下:

public void service(ServletRequest req, ServletResponse res)

在javax.servlet.http.HttpServlet类当中除了覆写public的service方法以外,还定义了本身的protected的service方法。

public void service(ServletRequest req, ServletResponse res)实现以下:

//Dispatches client requests to the protected service method.
//There's no need to override this method.
public void service(ServletRequest req, ServletResponse res)
    throws ServletException, IOException {

    HttpServletRequest  request;
    HttpServletResponse response;

    try {
        request = (HttpServletRequest) req;
        response = (HttpServletResponse) res;
    } catch (ClassCastException e) {
        throw new ServletException("non-HTTP request or response");
    }
    service(request, response);
}

protected void service(HttpServletRequest req, HttpServletResponse resp)实现以下:

//Receives standard HTTP requests from the public service method and
// dispatches them to the doXXX methods defined in this class.
//This method is an HTTP-specific version of the javax.servlet.Servlet.service method.
//There's no need to override this method.
protected void service(HttpServletRequest req, HttpServletResponse resp)
    throws ServletException, IOException {

    String method = req.getMethod();

    if (method.equals(METHOD_GET)) {
        long lastModified = getLastModified(req);
        if (lastModified == -1) {
            // servlet doesn't support if-modified-since, no reason
            // to go through further expensive logic
            doGet(req, resp);
        } else {
            long ifModifiedSince;
            try {
                ifModifiedSince = req.getDateHeader(HEADER_IFMODSINCE);
            } catch (IllegalArgumentException iae) {
                // Invalid date header - proceed as if none was set
                ifModifiedSince = -1;
            }
            if (ifModifiedSince < (lastModified / 1000 * 1000)) {
                // If the servlet mod time is later, call doGet()
                // Round down to the nearest second for a proper compare
                // A ifModifiedSince of -1 will always be less
                maybeSetLastModified(resp, lastModified);
                doGet(req, resp);
            } else {
                resp.setStatus(HttpServletResponse.SC_NOT_MODIFIED);
            }
        }

    } else if (method.equals(METHOD_HEAD)) {
        long lastModified = getLastModified(req);
        maybeSetLastModified(resp, lastModified);
        doHead(req, resp);

    } else if (method.equals(METHOD_POST)) {
        doPost(req, resp);

    } else if (method.equals(METHOD_PUT)) {
        doPut(req, resp);

    } else if (method.equals(METHOD_DELETE)) {
        doDelete(req, resp);

    } else if (method.equals(METHOD_OPTIONS)) {
        doOptions(req,resp);

    } else if (method.equals(METHOD_TRACE)) {
        doTrace(req,resp);

    } else {
        //
        // Note that this means NO servlet supports whatever
        // method was requested, anywhere on this server.
        //

        String errMsg = lStrings.getString("http.method_not_implemented");
        Object[] errArgs = new Object[1];
        errArgs[0] = method;
        errMsg = MessageFormat.format(errMsg, errArgs);

        resp.sendError(HttpServletResponse.SC_NOT_IMPLEMENTED, errMsg);
    }
}


tomcat服务器首先会调用servlet的service方法,而后在service方法中再根据请求方式来分别调用对应的doXX方法。




2.三、传递的请求参数如何获取

在浏览器发送HTTP协议的时候,GET方式是将参数放在URI的后面,POST方式是将参数放在实体内容中。

获取请求参数的API

获取GET方式参数:request.getQueryString();

获取POST方式参数:request.getInputStream();

问题:可是以上两种不通用,并且获取到的参数还须要进一步地解析。因此可使用统一方便的获取参数的方式:


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

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

request.getParameterNames();   获取全部参数名称列表


2.四、请求参数编码问题

修改POST方式参数编码(这种方式只对POST请求的实体内容有效):

request.setCharacterEncoding("utf-8");

修改GET方式参数编码:

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

相关文章
相关标签/搜索