深刻理解Http协议

1、Http协议html

1.1 什么是http协议前端

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

  http无状态协议:客户端向服务器端发送请求,没有事物管理。web

2、查看http协议的工具ajax

2.1 浏览器F12,进入开发者模式,点击Network,刷新页面便可查看请求apache

2.2 http协议格式分类json

请求(httpservletrequest对象)后端

  请求行跨域

    Request URL:https://www.baidu.com/img/baidu_jgylogo3.gif 请求地址浏览器

    Request Method:GET      请求方式

  请求头

    Accept:image/webp,image/apng,image/*,*/*;q=0.8 请求类型

    Accept-Encoding:gzip, deflate, br                                  压缩类型

    Accept-Language:zh-CN,zh;q=0.9         请求编码

    Connection:keep-alive

    Cookie:BAIDUID=3C5DBABB2234714F1860A4B6C35266D9:FG=1; PSTM=1554862563  cookie信息

    Host:www.baidu.com  域名地址

    Referer:https://www.baidu.com/  代理类型

    User-Agent:Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/63.0.3239.132 Safari/537.36   浏览器版本信息

  请求内容  testMethod.html?name=eric&password=123456

  请求体(post)name=eric&password=123456

        

响应(httpservletresponse对象)

  请求行

  响应内容

  响应体(html查看元素)

2.3 请求行

2.3 .1协议版本

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

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

2.3 .2 请求资源

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

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

2.3.3 请求方式

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

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

  表单提交:

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

    <form>

  GET和POST的区别:

    1)GET方式提交

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

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

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

      d)注意:浏览器直接访问的请求,默认提交方式是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

    2)POST方式提交

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

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

      c)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

2.4 请求头

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

2.5 实体内容

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

2.6 HttpServletRequest对象

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

     核心的API:

      请求行:

        request.getMethod(); 请求方式

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

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

      请求头:

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

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

       实体内容:

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

2.7 service和 doXX方法区别

  先进入service方法,判断req.getMethod(),在进入相近的doxxx方法

protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { String method = req.getMethod(); long lastModified; if (method.equals("GET")) { lastModified = this.getLastModified(req); if (lastModified == -1L) { this.doGet(req, resp); } else { long ifModifiedSince; try { ifModifiedSince = req.getDateHeader("If-Modified-Since"); } catch (IllegalArgumentException var9) { ifModifiedSince = -1L; } if (ifModifiedSince < lastModified / 1000L * 1000L) { this.maybeSetLastModified(resp, lastModified); this.doGet(req, resp); } else { resp.setStatus(304); } } } else if (method.equals("HEAD")) { lastModified = this.getLastModified(req); this.maybeSetLastModified(resp, lastModified); this.doHead(req, resp); } else if (method.equals("POST")) { this.doPost(req, resp); } else if (method.equals("PUT")) { this.doPut(req, resp); } else if (method.equals("DELETE")) { this.doDelete(req, resp); } else if (method.equals("OPTIONS")) { this.doOptions(req, resp); } else if (method.equals("TRACE")) { this.doTrace(req, resp); } else { String errMsg = lStrings.getString("http.method_not_implemented"); Object[] errArgs = new Object[]{method}; errMsg = MessageFormat.format(errMsg, errArgs); resp.sendError(501, errMsg); } }

2.8 时间戳

  不少网站在发布版本以前,都会在URL请求地址后面加上一个时间戳进行版本更新。

  做用:防止缓存

2.9 防止非法连接(referer),防止盗链

  网站的资源访问时进行过滤,根据referer来判断请求源头决定是否给予访问

  配置web.xml

<filter>
        <filter-name>ImgFilter</filter-name>
        <filter-class>com.itmayiedu.filter.ImgFilter</filter-class>
    </filter>
    <filter-mapping>
        <filter-name>ImgFilter</filter-name>
        <url-pattern>/static/*</url-pattern>
    </filter-mapping>

  后端代码

  publicclass ImgFilter implements Filter {     publicvoid destroy() {   } publicvoid doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException { HttpServletRequest request = (HttpServletRequest) servletRequest; HttpServletResponse response = (HttpServletResponse) servletResponse; // 从请求来获取referer
        String referer = request.getHeader("referer"); System.out.println("refer is" + "" + referer); // 判断是否来自于非法盗链
        if (referer == null || !referer.contains(request.getServerName())) { request.getRequestDispatcher("/static/error.png").forward(request, response); } else { filterChain.doFilter(request, response); } } publicvoid init(FilterConfig arg0) throws ServletException { } } 

2.10 传递的请求参数如何获取

  GET方式:参数放在URI后面

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

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

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

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

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

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

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

3、Http 响应

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!!!                  --实体内容

3.1 响应行

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

    常见的状态:

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

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

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

  3.1.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.2 HttpServletResponse对象

  HttpServletResponse对象修改响应信息:

   响应行:

    response.setStatus()  设置状态码

  响应头:

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

  实体内容:

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

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

3.3 请求重定向(Location)

resp.setStatus(302); resp.setHeader("Location", "OtherServlet");

4、Https与Http

4.1 https与http区别

  a、https 协议须要到 ca 申请证书,通常免费证书较少,于是须要必定费用。

  b、http 是超文本传输协议,信息是明文传输,https 则是具备安全性的 ssl 加密传输协议。

  c、http 和 https 使用的是彻底不一样的链接方式,用的端口也不同,前者是 80,后者是 443。

  d、http 的链接很简单,是无状态的;HTTPS 协议是由 SSL+HTTP 协议构建的可进行加密传输、身份认证的网络协议,比 http 协议安全。

4.2 https工做原理

  HTTPS 可以加密信息,以避免敏感信息被第三方获取,因此不少银行网站或电子邮箱等等安全级别较高的服务都会采用 HTTPS 协议。

  客户端在使用 HTTPS 方式与 Web 服务器通讯时有如下几个步骤,如图所示。

  (1)客户使用 https 的 URL 访问 Web 服务器,要求与 Web 服务器创建 SSL 链接。

  (2)Web 服务器收到客户端请求后,会将网站的证书信息(证书中包含公钥)传送一份给客户端。

  (3)客户端的浏览器与 Web 服务器开始协商 SSL 链接的安全等级,也就是信息加密的等级。

  (4)客户端的浏览器根据双方赞成的安全等级,创建会话密钥,而后利用网站的公钥将会话密钥加密,并传送给网站。

  (5)Web 服务器利用本身的私钥解密出会话密钥。

  (6)Web 服务器利用会话密钥加密与客户端之间的通讯。  

  

4.3 https优缺点

   优势:

  HTTPS 可以加密信息,以避免敏感信息被第三方获取

 缺点:

  (1)HTTPS 协议握手阶段比较费时,会使页面的加载时间延长近 50%,增长 10% 到 20% 的耗电;

  (2)HTTPS 链接缓存不如 HTTP 高效,会增长数据开销和功耗,甚至已有的安全措施也会所以而受到影响;

  (3)SSL 证书须要钱,功能越强大的证书费用越高,我的网站、小网站没有必要通常不会用。

  (4)SSL 证书一般须要绑定 IP,不能在同一 IP 上绑定多个域名,IPv4 资源不可能支撑这个消耗。

  (5)HTTPS 协议的加密范围也比较有限,在黑客攻击、拒绝服务攻击、服务器劫持等方面几乎起不到什么做用。最关键的,SSL 证书的信用链体系并不安全,特别是在某些国家能够控制 CA 根证书的状况下,中间人攻击同样可行。

4.4 web安全与防攻击

  一、  什么是xxs

    实际上是脚本注入,使用过滤器将全部提交的参数的value值,转换成html代码执行

    if (!StringUtils.isEmpty(value)) {

                 // 转换Html

                 value = StringEscapeUtils.escapeHtml4(value);

          }

  二、  CSRF(模拟Http请求) 企业当中会有白名单和黑名单,底层是判断请求源头

  三、  上传漏洞

  四、  SQL注入

  五、  用一些HTTPS请求, 安全性高,走的ssl+证书,加密传输,非明文,可是效率低

 5、http请求工具

5.1 客户端模拟http请求工具

  Postmen(谷歌插件)、RestClient

 5.2 服务器端模拟http请求工具

  httpclient、HttpURLConnection

  httpCient请求代码:

/** * 发送 post请求访问本地应用并根据传递参数不一样返回不一样结果 */ publicvoid post() { // 建立默认的httpClient实例.
        CloseableHttpClient httpclient = HttpClients.createDefault(); // 建立httppost
        HttpPost httppost = new HttpPost("http://localhost:8080/myDemo/Ajax/serivceJ.action"); // 建立参数队列
        List<NameValuePair>formparams = new ArrayList<NameValuePair>(); formparams.add(new BasicNameValuePair("type", "house")); UrlEncodedFormEntity uefEntity; try { uefEntity = new UrlEncodedFormEntity(formparams, "UTF-8"); httppost.setEntity(uefEntity); System.out.println("executing request " + httppost.getURI()); CloseableHttpResponse response = httpclient.execute(httppost); try { HttpEntity entity = response.getEntity(); if (entity != null) { System.out.println("--------------------------------------"); System.out.println("Response content: " + EntityUtils.toString(entity, "UTF-8")); System.out.println("--------------------------------------"); } } finally { response.close(); } } catch (ClientProtocolException e) { e.printStackTrace(); } catch (UnsupportedEncodingException e1) { e1.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } finally { // 关闭链接,释放资源
            try { httpclient.close(); } catch (IOException e) { e.printStackTrace(); } } } /** * 发送 get请求 */ publicvoid get() { CloseableHttpClient httpclient = HttpClients.createDefault(); try { // 建立httpget.
            HttpGet httpget = new HttpGet("http://www.baidu.com/"); System.out.println("executing request " + httpget.getURI()); // 执行get请求.
            CloseableHttpResponse response = httpclient.execute(httpget); try { // 获取响应实体
                HttpEntity entity = response.getEntity(); System.out.println("--------------------------------------"); // 打印响应状态
 System.out.println(response.getStatusLine()); if (entity != null) { // 打印响应内容长度
                    System.out.println("Response content length: " + entity.getContentLength()); // 打印响应内容
                    System.out.println("Response content: " + EntityUtils.toString(entity)); } System.out.println("------------------------------------"); } finally { response.close(); } } catch (ClientProtocolException e) { e.printStackTrace(); } catch (ParseException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } finally { // 关闭链接,释放资源
            try { httpclient.close(); } catch (IOException e) { e.printStackTrace(); } } }

5.3 前段ajax请求,ajax 异步操做,局部刷新。相似于后端的多线程技术

$.ajax({ type : 'post', dataType : "text", url : "http://a.a.com/a/FromUserServlet", data : "userName=张三&userAge=19", success : function(msg) { alert(msg); } });

5.4 跨域解决方案

  跨域缘由产生:在当前域名请求网站中,默认不容许经过ajax请求发送其余域名。

  XMLHttpRequest cannot load跨域问题解决办法

5.4.1 使用后台response添加header

  后台response添加header,response.setHeader("Access-Control-Allow-Origin", "*");支持全部网站

  写到过滤器中,跨域问题统一处理

5.4.2 使用JSONP,(只支持get请求不支持post请求,开发较为麻烦)

  前端代码:

$.ajax({ type : "POST", async : false, url : "http://a.a.com/a/FromUserServlet?userName=张三", dataType : "jsonp",//数据类型为jsonp jsonp : "jsonpCallback",//服务端用于接收callback调用的function名的参数 success : function(data) { alert(data.result); }, error : function() { alert('fail'); } });

  后端代码:

@WebServlet("/FromUserServlet") publicclassFromUserServletextends HttpServlet { protectedvoid doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { doPost(req, resp); } protectedvoid doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { resp.setCharacterEncoding("UTF-8"); // resp.setHeader("Access-Control-Allow-Origin", "*");
         String userName = req.getParameter("userName"); String userAge = req.getParameter("userAge"); System.out.println(userName + "----" + userAge+"---"+req.getMethod()); // JSONObject JSONObject1 = new JSONObject(); // JSONObject1.put("success", "添加成功!"); // resp.getWriter().write("callbackparam(" + JSONObject1.toJSONString() // + ")");

        try { resp.setContentType("text/plain"); resp.setHeader("Pragma", "No-cache"); resp.setHeader("Cache-Control", "no-cache"); resp.setDateHeader("Expires", 0); PrintWriter out = resp.getWriter(); JSONObject resultJSON = new JSONObject(); // 根据须要拼装json
            resultJSON.put("result", "content"); String jsonpCallback = req.getParameter("jsonpCallback");// 客户端请求参数
            out.println(jsonpCallback + "(" + resultJSON.toJSONString() + ")");// 返回jsonp格式数据
 out.flush(); out.close(); } catch (Exception e) {
 } } }

  jsonp会在浏览器生成一个get请求,带上参数。

5.4.3 使用接口网关,使用nginx转发

5.4.4 使用后台服务转发(不建议,占用大量宽带)