什么是http协议

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

查看http协议的工具

  • 使用火狐的firebug插件(右键->firebug->网络)
  • 使用谷歌的“审查元素”
  • 使用系统自带的telnet工具(远程访问工具)
    • telnet localhost 8080 访问tomcat服务器
    • ctrl+] 回车 可以看到回显
    • 输入请求内容
  1. GET /day09/hello HTTP/1.1
  2. Host: localhost:8080
* 回车,即可查看到服务器响应信息。

http协议内容

  1. 请求(浏览器-》服务器)
  2. GET /day09/hello HTTP/1.1
  3. Host: localhost:8080
  4. User-Agent: Mozilla/5.0 (Windows NT 6.1; WOW64; rv:35.0) Gecko/20100101 Firefox/35.0
  5. Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
  6. Accept-Language: zh-cn,en-us;q=0.8,zh;q=0.5,en;q=0.3
  7. Accept-Encoding: gzip, deflate
  8. Connection: keep-alive
  1. 响应(服务器-》浏览器)
  2. HTTP/1.1 200 OK
  3. Server: Apache-Coyote/1.1
  4. Content-Length: 24
  5. Date: Fri, 30 Jan 2015 01:54:57 GMT
  6. this is hello servlet!!!

Http请求

  1. GET /day09/hello HTTP/1.1 -请求行
  2. Host: localhost:8080 --请求头(多个key-value对象)
  3. User-Agent: Mozilla/5.0 (Windows NT 6.1; WOW64; rv:35.0) Gecko/20100101 Firefox/35.0
  4. Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
  5. Accept-Language: zh-cn,en-us;q=0.8,zh;q=0.5,en;q=0.3
  6. Accept-Encoding: gzip, deflate
  7. Connection: keep-alive
  8. --一个空行
  9. name=eric&password=123456 --(可选)实体内容

请求行

GET /day09/hello HTTP/1.1

http协议版本

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

请求资源

  • URL: 统一资源定位符。http://localhost:8080/day09/testImg.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> GET vs POST 区别

GET方式提交

  • 地址栏(URI)会跟上参数数据。以?开头,多个参数之间以&分割。
  1. GET /day09/testMethod.html?name=eric&password=123456 HTTP/1.1
  2. Host: localhost:8080
  3. User-Agent: Mozilla/5.0 (Windows NT 6.1; WOW64; rv:35.0) Gecko/20100101 Firefox/35.0
  4. Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
  5. Accept-Language: zh-cn,en-us;q=0.8,zh;q=0.5,en;q=0.3
  6. Accept-Encoding: gzip, deflate
  7. Referer: http://localhost:8080/day09/testMethod.html
  8. Connection: keep-alive
  • GET提交参数数据有限制,不超过1KB。
  • GET方式不适合提交敏感密码。
  • 注意: 浏览器直接访问的请求,默认提交方式是GET方式

POST方式提交

  • 参数不会跟着URI后面。参数而是跟在请求的实体内容中。没有?开头,多个参数之间以&分割。
  1. POST /day09/testMethod.html HTTP/1.1
  2. Host: localhost:8080
  3. User-Agent: Mozilla/5.0 (Windows NT 6.1; WOW64; rv:35.0) Gecko/20100101 Firefox/35.0
  4. Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
  5. Accept-Language: zh-cn,en-us;q=0.8,zh;q=0.5,en;q=0.3
  6. Accept-Encoding: gzip, deflate
  7. Referer: http://localhost:8080/day09/testMethod.html
  8. Connection: keep-alive
  9. name=eric&password=123456
  • POST提交的参数数据没有限制。
  • POST方式提交敏感数据。

请求头

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

3.3 实体内容

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

3.4 HttpServletRequest对象

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

核心的API:

请求行:

request.getMethod(); 请求方式

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

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

请求头:

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

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

实体内容:

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

浏览器默认的提交方式是GET

但是这并不是通用方法,通用的使用API:

  • request.getParameterNames():获取一个集合,里面存放参数名称
  • request.getParameter(String):获取指定参数名称的参数值
  • request.getParameterValues(String):返回指定参数集合的值

Demo:

1.新建Html,输出数据:

  1. <!DOCTYPE html>
  2. <html>
  3. <head>
  4. <title>参数提交</title>
  5. </head>
  6. <meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
  7. <meta http-equiv="description" content="this is my page">
  8. <meta http-equiv="content-type" content="text/html; charset=UTF-8">
  9. <body>
  10. <h3>GET方式提交</h3>
  11. <form action="/WebDemo1/RequsetDemo5" method="GET">
  12. 用户名:<input type="text" name="name"/><br/>
  13. 密码:<input type="password" name="password"/><br/>
  14. <input type="submit" value="提交"/>
  15. </form>
  16. <hr/>
  17. <h3>POST方式提交</h3>
  18. <form action="/WebDemo1/RequsetDemo5" method="POST">
  19. 用户名:<input type="text" name="name"/><br/>
  20. 密码:<input type="password" name="password"/><br/>
  21. <input type="submit" value="提交"/>
  22. </form>
  23. </body>
  24. </html>

2.创建一个Servlet接收数据

  1. package per.liyue.code.getparam;
  2. import java.io.BufferedReader;
  3. import java.io.IOException;
  4. import java.io.InputStreamReader;
  5. import java.io.PrintWriter;
  6. import javax.servlet.ServletException;
  7. import javax.servlet.http.HttpServlet;
  8. import javax.servlet.http.HttpServletRequest;
  9. import javax.servlet.http.HttpServletResponse;
  10. public class RequsetDemo5 extends HttpServlet {
  11. /**
  12. * The doGet method of the servlet. <br>
  13. *
  14. * This method is called when a form has its tag value method equals to get.
  15. *
  16. * @param request the request send by the client to the server
  17. * @param response the response send by the server to the client
  18. * @throws ServletException if an error occurred
  19. * @throws IOException if an error occurred
  20. */
  21. public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
  22. System.out.println("get方式接收参数:");
  23. //
  24. String value = request.getQueryString();
  25. System.out.println(value);
  26. }
  27. /**
  28. * The doPost method of the servlet. <br>
  29. *
  30. * This method is called when a form has its tag value method equals to post.
  31. *
  32. * @param request the request send by the client to the server
  33. * @param response the response send by the server to the client
  34. * @throws ServletException if an error occurred
  35. * @throws IOException if an error occurred
  36. */
  37. public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
  38. System.out.println("使用Post接收参数");
  39. BufferedReader read = new BufferedReader(
  40. new InputStreamReader(
  41. request.getInputStream()));
  42. String lineRead = null;
  43. while (null != (lineRead=read.readLine())) {
  44. System.out.println(lineRead);
  45. }
  46. }
  47. }

但是二者读取参数方法不一致, 实际使用时候,有统一方法调用:

  1. package per.liyue.code.getparam;
  2. import java.io.BufferedReader;
  3. import java.io.IOException;
  4. import java.io.InputStreamReader;
  5. import java.io.PrintWriter;
  6. import java.util.Enumeration;
  7. import javax.servlet.ServletException;
  8. import javax.servlet.http.HttpServlet;
  9. import javax.servlet.http.HttpServletRequest;
  10. import javax.servlet.http.HttpServletResponse;
  11. public class RequsetDemo5 extends HttpServlet {
  12. /**
  13. * The doGet method of the servlet. <br>
  14. *
  15. * This method is called when a form has its tag value method equals to get.
  16. *
  17. * @param request the request send by the client to the server
  18. * @param response the response send by the server to the client
  19. * @throws ServletException if an error occurred
  20. * @throws IOException if an error occurred
  21. */
  22. public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
  23. System.out.println("get方式接收参数-非统一方法:");
  24. //不统一方法
  25. String Query = request.getQueryString();
  26. System.out.println(Query);
  27. System.out.println("get方式接收参数-统一方法:");
  28. Enumeration<String> en = request.getParameterNames();
  29. if (en.hasMoreElements()) {
  30. System.out.print("get到的参数名称:");
  31. //因为html中的编码是utf-8,所以这里要进行转码保证不出错!
  32. String name = new String(en.nextElement().getBytes("iso-8859-1"), "utf-8");
  33. String value = new String(request.getParameter(name).getBytes("iso-8859-1"), "utf-8");
  34. System.out.print("参数名称:" + name + "get到的参数值:" + value);
  35. }
  36. }
  37. /**
  38. * The doPost method of the servlet. <br>
  39. *
  40. * This method is called when a form has its tag value method equals to post.
  41. *
  42. * @param request the request send by the client to the server
  43. * @param response the response send by the server to the client
  44. * @throws ServletException if an error occurred
  45. * @throws IOException if an error occurred
  46. */
  47. public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
  48. System.out.println("使用Post接收参数-非统一方法");
  49. //非统一方法
  50. // BufferedReader read = new BufferedReader(
  51. // new InputStreamReader(
  52. // request.getInputStream()));
  53. // String lineRead = null;
  54. // while (null != (lineRead=read.readLine())) {
  55. // System.out.println(lineRead);
  56. // }
  57. /*
  58. * 使用统一方法后,可以直接调用deGet中已经实现的参数提取
  59. * 并且,post中获取只能一次,也是就上面的非同一方法和下面的方法同时只存在于一个
  60. */
  61. doGet(request, response);
  62. }
  63. }

编码问题在上面代码中已经手动解析,这里还有一个方法:

  1. /*
  2. * 这个方法要在获取参数之前调用才生效,是个全局设定,但是要注意的是:
  3. * 该方法是对实体内容中的数据编码有效,也就是说,post的数据在实体内容中,
  4. * 对post有效。而get的参数在uri后面,所以多get无效!!!
  5. */
  6. request.setCharacterEncoding("utf-8");

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

响应行

http协议版本

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

常见的状态:

  • 200 : 表示请求处理完成并完美返回
  • 302: 表示请求需要进一步细化。
  • 404: 表示客户访问的资源找不到。
  • 500: 表示服务器的资源发送错误。(服务器内部错误)

状态描述

常见的响应头

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:保存连接

HttpServletResponse对象

HttpServletResponse对象修改响应信息:

  • 响应行: response.setStatus() 设置状态码
  • 响应头:response.setHeader(“name”,”value”) 设置响应头
  • 实体内容:
    • response.getWriter().writer(); 发送字符实体内容
    • response.getOutputStream().writer() 发送字节实体内容

Demo

  1. import java.io.IOException;
  2. import java.io.PrintWriter;
  3. import javax.servlet.ServletException;
  4. import javax.servlet.http.HttpServlet;
  5. import javax.servlet.http.HttpServletRequest;
  6. import javax.servlet.http.HttpServletResponse;
  7. public class ResponseDemo1 extends HttpServlet {
  8. /**
  9. * The doGet method of the servlet. <br>
  10. *
  11. * This method is called when a form has its tag value method equals to get.
  12. *
  13. * @param request the request send by the client to the server
  14. * @param response the response send by the server to the client
  15. * @throws ServletException if an error occurred
  16. * @throws IOException if an error occurred
  17. */
  18. public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
  19. /*
  20. * Response响应行
  21. */
  22. //这里返回状态码
  23. response.setStatus(404);
  24. //这里就直接返回了错误码,直接页面报错
  25. response.sendError(404);
  26. /*
  27. * Response响应头
  28. */
  29. response.setHeader("这里是响应头名称", "这里是响应值");
  30. /*
  31. * Response实体内容
  32. */
  33. //字符输出
  34. response.getWriter().write("这里是实体的测试-字符");
  35. //字节输出
  36. response.getOutputStream().write("这里是实体的测试-字节".getBytes());
  37. }
  38. /**
  39. * The doPost method of the servlet. <br>
  40. *
  41. * This method is called when a form has its tag value method equals to post.
  42. *
  43. * @param request the request send by the client to the server
  44. * @param response the response send by the server to the client
  45. * @throws ServletException if an error occurred
  46. * @throws IOException if an error occurred
  47. */
  48. public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
  49. }
  50. }

页面跳转-使用Location头

浏览器识别到302状态码后,会想服务器再发一次请求,请求的地址就是Location的Value值

  1. //发送302状态码
  2. response.setStatus(302);
  3. response.setHeader("Location", "\项目名称\跳转的目标页面.html");
  4. //可以写为,下面这行代码效果等同于上面代码
  5. response.sendRedirect("\项目名称\跳转的目标页面.html");

定时刷新-使用Refresh

  1. /*
  2. * 定时刷新1:
  3. * 浏览器识别refresh,后面的1表示每1秒刷新一次当前页面
  4. */
  5. response.setHeader("refresh", "1");
  6. /*
  7. * 定时刷新2:
  8. * 定时跳转到指定页面:3秒后刷新到指定的url页面
  9. */
  10. response.setHeader("refesh", "3;url=\项目名称\具体页面.html");
  11. ``
  12. ### 设置服务器发送给浏览器数据类型
  13. ```Java
  14. //定义发送数据类型:
  15. //形式1:
  16. response.setHeader("content-type", "text/html");
  17. //形式2:
  18. response.setContentType("text/html");
  19. //其他类型
  20. xml:"text/xml"
  21. jpg:"image/jpg"

这里不同数据类型的写法,在tomcat的配置文件中有。路径为:$\apache-tomcat-8.0.36\conf\下的标签中

定义下载

  1. //下载
  2. File file = new File("");
  3. response.setHeader("Content-Desposition", "attachment; filename=" + file.getName());

项目中的编码问题

在每个Servlet开头定义上:

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

4.HTTP入门的更多相关文章

  1. Angular2入门系列教程7-HTTP(一)-使用Angular2自带的http进行网络请求

    上一篇:Angular2入门系列教程6-路由(二)-使用多层级路由并在在路由中传递复杂参数 感觉这篇不是很好写,因为涉及到网络请求,如果采用真实的网络请求,这个例子大家拿到手估计还要自己写一个web ...

  2. ABP入门系列(1)——学习Abp框架之实操演练

    作为.Net工地搬砖长工一名,一直致力于挖坑(Bug)填坑(Debug),但技术却不见长进.也曾热情于新技术的学习,憧憬过成为技术大拿.从前端到后端,从bootstrap到javascript,从py ...

  3. Oracle分析函数入门

    一.Oracle分析函数入门 分析函数是什么?分析函数是Oracle专门用于解决复杂报表统计需求的功能强大的函数,它可以在数据中进行分组然后计算基于组的某种统计值,并且每一组的每一行都可以返回一个统计 ...

  4. Angular2入门系列教程6-路由(二)-使用多层级路由并在在路由中传递复杂参数

    上一篇:Angular2入门系列教程5-路由(一)-使用简单的路由并在在路由中传递参数 之前介绍了简单的路由以及传参,这篇文章我们将要学习复杂一些的路由以及传递其他附加参数.一个好的路由系统可以使我们 ...

  5. Angular2入门系列教程5-路由(一)-使用简单的路由并在在路由中传递参数

    上一篇:Angular2入门系列教程-服务 上一篇文章我们将Angular2的数据服务分离出来,学习了Angular2的依赖注入,这篇文章我们将要学习Angualr2的路由 为了编写样式方便,我们这篇 ...

  6. Angular2入门系列教程4-服务

    上一篇文章 Angular2入门系列教程-多个组件,主从关系 在编程中,我们通常会将数据提供单独分离出来,以免在编写程序的过程中反复复制粘贴数据请求的代码 Angular2中提供了依赖注入的概念,使得 ...

  7. wepack+sass+vue 入门教程(三)

    十一.安装sass文件转换为css需要的相关依赖包 npm install --save-dev sass-loader style-loader css-loader loader的作用是辅助web ...

  8. wepack+sass+vue 入门教程(二)

    六.新建webpack配置文件 webpack.config.js 文件整体框架内容如下,后续会详细说明每个配置项的配置 webpack.config.js直接放在项目demo目录下 module.e ...

  9. wepack+sass+vue 入门教程(一)

    一.安装node.js node.js是基础,必须先安装.而且最新版的node.js,已经集成了npm. 下载地址 node安装,一路按默认即可. 二.全局安装webpack npm install ...

  10. js学习笔记:webpack基础入门(一)

    之前听说过webpack,今天想正式的接触一下,先跟着webpack的官方用户指南走: 在这里有: 如何安装webpack 如何使用webpack 如何使用loader 如何使用webpack的开发者 ...

随机推荐

  1. 如何给Qlabel添加clicked属性(覆盖mousePressEvent,处理QMouseEvent消息,反正是软绘制,想怎么样就怎么样)

    clickedLabel.h #ifndef CLICKLABEL_H #define CLICKLABEL_H #include <QLabel> #include <QMouse ...

  2. 对依赖倒置原则(DIP)及Ioc、DI、Ioc容器的一些理解(转)

    所谓依赖倒置原则(Dependence Inversion Principle)就是要依赖于抽象,不要依赖于具体.简单的说就是要求对抽象进行编程,不要对实现进行编程,这样就降低了客户与实现模块间的耦合 ...

  3. 【HDOJ】3459 Rubik 2×2×2

    模拟+DFS. /* 3459 */ #include <cstdio> #include <cstring> #include <cstdlib> #define ...

  4. 安装zabbix2.2.3

    系统版本:CentOS 6.3_x86_64 zabbix版本:zabbix-2.2.3 zabbix服务端IP:172.16.10.72 1.yum安装LAMP环境 # yum -y install ...

  5. 网络流(最大流):COGS 28 [NOI2006] 最大获利

    28. [NOI2006] 最大获利 ★★★☆   输入文件:profit.in   输出文件:profit.out   简单对比 时间限制:2 s   内存限制:512 MB [问题描述] 新的技术 ...

  6. Eclipse中处理图片引包问题

    在Eclipse中处理图片,需要引入两个包:import com.sun.image.codec.jpeg.JPEGCodec;import com.sun.image.codec.jpeg.JPEG ...

  7. Python修饰器

    Python的修饰器的英文名叫Decorator,当你看到这个英文名的时候,你可能会把其跟Design Pattern里的Decorator搞混了,其实这是完全不同的两个东西.虽然好像,他们要干的事都 ...

  8. JavaScript中的运动数学函数(持续更新)

    经常需要实现JS的动画效果,就会用到如下的一些数学的东西. 二次方运动,从0开始加速: var f=function(t,orgvalue,changevalue,runtime){ var t=t/ ...

  9. #345 div2 D. Image Preview

    Vasya's telephone contains n photos. Photo number 1 is currently opened on the phone. It is allowed ...

  10. 【最短路】埃雷萨拉斯寻宝(eldrethalas) 解题报告

    问题来源 BYVoid魔兽世界模拟赛 [问题描述] 一万两千年前,当精灵还是在艾萨拉女王的统治下的时候,辛德拉就是是女王手下一名很有地位的法师了.他受任建造了一座城市,来保存女王的法师们进行魔法研究的 ...