http笔记
来源:互联网 发布:知无涯者 台词 编辑:程序博客网 时间:2024/06/05 07:10
1、什么是http协议
http协议: 对浏览器客户端 和 服务器端 之间数据传输的格式规范
2、查看http协议的工具
1)使用火狐的firebug插件(右键->firebug->网络)2)使用谷歌的“审查元素”3)使用系统自带的telnet工具(远程访问工具)a)telnet localhost 8080 访问tomcat服务器b)ctrl+] 回车 可以看到回显c)输入请求内容
3 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.0Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8Accept-Language: zh-cn,en-us;q=0.8,zh;q=0.5,en;q=0.3Accept-Encoding: gzip, deflateConnection: keep-alive --一个空行name=eric&password=123456 --(可选)实体内容
3.1 请求行
GET /day09/hello HTTP/1.1 #http协议版本 (1.1)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 区别
1)GET方式提交 a)地址栏(URI)会跟上参数数据。以?开头,多个参数之间以&分割。GET /day09/testMethod.html?name=eric&password=123456 HTTP/1.1Host: localhost:8080User-Agent: Mozilla/5.0 (Windows NT 6.1; WOW64; rv:35.0) Gecko/20100101 Firefox/35.0Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8Accept-Language: zh-cn,en-us;q=0.8,zh;q=0.5,en;q=0.3Accept-Encoding: gzip, deflateReferer: http://localhost:8080/day09/testMethod.htmlConnection: keep-alive b)GET提交参数数据有限制,不超过1KB。 c)GET方式不适合提交敏感密码。 d)注意: 浏览器直接访问的请求,默认提交方式是GET方式2)POST方式提交 a)参数不会跟着URI后面。参数而是跟在请求的实体内容中。没有?开头,多个参数之间以&分割。POST /day09/testMethod.html HTTP/1.1Host: localhost:8080User-Agent: Mozilla/5.0 (Windows NT 6.1; WOW64; rv:35.0) Gecko/20100101 Firefox/35.0Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8Accept-Language: zh-cn,en-us;q=0.8,zh;q=0.5,en;q=0.3Accept-Encoding: gzip, deflateReferer: http://localhost:8080/day09/testMethod.htmlConnection: keep-alivename=eric&password=123456 b)POST提交的参数数据没有限制。 c)POST方式提交敏感数据。
3.2请求头
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 -- 请求发出的时间
3.3 实体内容
只有POST提交的参数会放到实体内容中
3.4 HttpServletRequest对象HttpServletRequest对象作用是用于获取请求数据。(全部的请求都封装到这里HttpServletRequest)核心的API:请求行: request.getMethod(); 请求方式request.getRequetURI() / request.getRequetURL() 请求资源request.getProtocol() 请求http协议版本请求头:request.getHeader("名称") 根据请求头获取请求值request.getHeaderNames() 获取所有的请求头名称实体内容:request.getInputStream() 获取实体内容数据RequestDeom1.java 输出请求的方式,请求的资源,http协议
public void doGet(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException {System.out.println("请求方式:"+request.getMethod());//请求方式System.out.println("URI:"+request.getRequestURI());//请求资源System.out.println("URL:"+request.getRequestURL());System.out.println("http协议版本:"+request.getProtocol());//http协议}
输出:请求方式:GET //浏览器默认的提交方式就是get方式URI:/day10/RequestDeom1URL:http://localhost:8080/day10/RequestDeom1http协议版本:HTTP/1.1
3.2 请求头String host = request.getHeader("Host"); //根据头名称的到头的内容System.out.println(host);
boolean hasMoreElements() 测试此枚举是否包含更多的元素。 E nextElement() 如果此枚举对象至少还有一个可提供的元素,则返回此枚举的下一个元素。
得到所有的请求头:
//遍历所有请求头Enumeration<String> enums = request.getHeaderNames(); //得到所有的请求头名称列表while(enums.hasMoreElements()){//判断是否有下一个元素String headerName = enums.nextElement(); //取出下一个元素String headerValue = request.getHeader(headerName);System.out.println(headerName+":"+headerValue);}}
输出:host:localhost:8080user-agent:Mozilla/5.0 (Windows NT 6.1; WOW64; rv:57.0) Gecko/20100101 Firefox/57.0accept:text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8accept-language:zh-CN,zh;q=0.8,zh-TW;q=0.7,zh-HK;q=0.5,en-US;q=0.3,en;q=0.2accept-encoding:gzip, deflateconnection:keep-aliveupgrade-insecure-requests:1请求的实体内容使用doPost接收post发送的内容,post接收实体内容:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"><html> <head> <title>测试请求方式</title> <meta http-equiv="keywords" content="keyword1,keyword2,keyword3"> <meta http-equiv="description" content="this is my page"> <meta http-equiv="content-type" content="text/html; charset=UTF-8"> </head> <body> <h3>POST方式提交</h3> <form action="/day10/RequestDeom1" method="POST"> <!-- 请求名称加地址 :action="/day10/RequestDeom1"--> 用户名:<input type="text" name="name"/><br/> 密码:<input type="password" name="password"/><br/> <input type="submit" value="提交"/> </form> </body></html>为了接收POST方式提交的请求:
protected void doPost(HttpServletRequest request, HttpServletResponse resp)throws ServletException, IOException {/** * 3.3 请求的实体内容 */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);}}
执行http://localhost:8080/day10/RequestDeom1输入:eric 123456输出:name=eric&password=123456
传递的请求参数如何获取 GET方式: 参数放在URI后面 POST方式: 参数放在实体内容中获取GET方式参数:request.getQueryString();获取POST方式参数:request.getInputStream();------分别使用doPost和doGet方式获得:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"><html> <head> <title>测试请求方式</title> <meta http-equiv="keywords" content="keyword1,keyword2,keyword3"> <meta http-equiv="description" content="this is my page"> <meta http-equiv="content-type" content="text/html; charset=UTF-8"> </head> <body> <h3>GET方式提交</h3> <form action="/day10/RequestDeom5" method="GET"> 用户名:<input type="text" name="name"/><br/> 密码:<input type="password" name="password"/><br/> <input type="submit" value="提交"/> </form> <hr/> <h3>POST方式提交</h3> <form action="/day10/RequestDeom5" method="POST"> <!-- 请求名称加地址 :action="/day10/RequestDeom5"--> 用户名:<input type="text" name="name"/><br/> 密码:<input type="password" name="password"/><br/> <input type="submit" value="提交"/> </form> </body></html>
public class RequestDeom5 extends HttpServlet {public void doGet(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException {System.out.println("GET方式"); String value = request.getQueryString();System.out.println(value);}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));}}}
执行http://localhost:8080/day10/RequestDeom5输入:eric 123456 eric 123456输出:GET方式name=eric&password=123456POST方式name=eric&password=123456
问题:但是以上两种不通用,而且获取到的参数还需要进一步地解析。 所以可以使用统一方便的获取参数的方式: 核心的API:request.getParameter("参数名"); 根据参数名获取参数值(注意,只能获取一个值的参数)request.getParameterValue("参数名“);根据参数名获取参数值(可以获取多个值的参数)request.getParameterNames(); 获取所有参数名称列表
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();if("hobit".equals(paramName)){System.out.print(paramName+": ");String[] hobits = request.getParameterValues("hobit");for(String h: hobits){System.out.print(h+",");}System.out.println();}else{String paramValue = request.getParameter(paramName);System.out.println(paramName+"="+paramValue);}}
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"><html> <head> <title>请求参数传递和接收问题</title> <meta http-equiv="keywords" content="keyword1,keyword2,keyword3"> <meta http-equiv="description" content="this is my page"> <meta http-equiv="content-type" content="text/html; charset=UTF-8"> <!-- 编码格式为utf-8 --> <!--<link rel="stylesheet" type="text/css" href="./styles.css">--> </head> <body> <h3>GET方式提交</h3> <form action="/day10/RequestDeom5" method="GET"> 用户名:<input type="text" name="name"/><br/> 密码:<input type="password" name="password"/><br/> 性别: <input type="radio" name="gender" value="男"/>男 <input type="radio" name="gender" value="女"/>女<br/> 籍贯: <select name="jiguan"> <option value="广东">广东</option> <option value="广西">广西</option> <option value="湖南">湖南</option> </select> <br/> 爱好: <input type="checkbox" name="hobit" value="篮球"/>篮球 <input type="checkbox" name="hobit" value="足球"/>足球 <input type="checkbox" name="hobit" value="羽毛球"/>羽毛球<br/> 个人简介: <textarea rows="5" cols="10" name="info"></textarea><br/> <!-- 隐藏域 --> <input type="hidden" name="id" value="001"/> <input type="submit" value="提交"/> </form> <hr/> <h3>POST方式提交</h3> <form action="/day10/RequestDeom5" method="POST"> 用户名:<input type="text" name="name"/><br/> 密码:<input type="password" name="password"/><br/> 性别: <input type="radio" name="gender" value="男"/>男 <input type="radio" name="gender" value="女"/>女<br/> 籍贯: <select name="jiguan"> <option value="广东">广东</option> <option value="广西">广西</option> <option value="湖南">湖南</option> </select> <br/> 爱好: <input type="checkbox" name="hobit" value="篮球"/>篮球 <input type="checkbox" name="hobit" value="足球"/>足球 <input type="checkbox" name="hobit" value="羽毛球"/>羽毛球<br/> 个人简介: <textarea rows="5" cols="10" name="info"></textarea><br/> <!-- 隐藏域 --> <input type="hidden" name="id" value="001"/> <input type="submit" value="提交"/> </form> </body></html>
输出:eric=123465=============================id=001jiguan=??????name=ericgender=??·hobit: ??????,è?????,?????????,password=123465info=aaaaaa但是存在乱码的问题:
请求参数编码问题 修改POST方式参数编码:request.setCharacterEncoding("utf-8");修改GET方式参数编码:手动解码:String name = new String(name.getBytes("iso-8859-1"),"utf-8");
public class RequestDeom5 extends HttpServlet {public void doGet(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException {request.setCharacterEncoding("utf-8"); //适用于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();if("hobit".equals(paramName)){System.out.print(paramName+": ");String[] hobits = request.getParameterValues("hobit");for(String h: hobits){System.out.print(h+",");}System.out.println();}else{String paramValue = request.getParameter(paramName);System.out.println(paramName+"="+paramValue);}}}public void doPost(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException {System.out.println("POST方式");doGet(request,response);}}输出:POST方式aaa=11111=============================id=001jiguan=广东name=aaagender=男hobit: 篮球,足球,羽毛球,password=11111info=aaaaa
该方法只能对请求实体内容的数据编码起作用。POST提交的数据在实体内容中,所以该方法对POST方法有效!GET方法的参数放在URI后面,所以对GET方式无效!!!所以对于GET只能用于手动解码:String name = new String(name.getBytes("iso-8859-1"),"utf-8");
获取GET方式和Post方式提交的参数:public class RequestDeom5 extends HttpServlet {public void doGet(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException {request.setCharacterEncoding("utf-8");//统一方便的获取请求参数的方法//根据参数名得到参数值String name = request.getParameter("name");if("GET".equals(request.getMethod())){name = new String(name.getBytes("iso-8859-1"),"utf-8");}String password = request.getParameter("password");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();if("hobit".equals(paramName)){System.out.print(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();}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方式");doGet(request,response);}}
(更改配置文件改编码)(不建议使用)打来tomcat里面cof文件夹里面的servlet.xml文件更改: <Connector executor="tomcatThreadPool" port="8080" protocol="HTTP/1.1" connectionTimeout="20000" redirectPort="8443" URIEncoding="utf-8"/>添加:URIEncoding="utf-8"再重新启动
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"><html> <head> <title>请求参数传递和接收问题</title> <meta http-equiv="keywords" content="keyword1,keyword2,keyword3"> <meta http-equiv="description" content="this is my page"> <meta http-equiv="content-type" content="text/html; charset=UTF-8"> <!--<link rel="stylesheet" type="text/css" href="./styles.css">--> </head> <body> <h3>GET方式提交</h3> <form action="/day10/RequestDeom5" method="GET"> 用户名:<input type="text" name="name"/><br/> 密码:<input type="password" name="password"/><br/> 性别: <input type="radio" name="gender" value="男"/>男 <input type="radio" name="gender" value="女"/>女<br/> 籍贯: <select name="jiguan"> <option value="广东">广东</option> <option value="广西">广西</option> <option value="湖南">湖南</option> </select> <br/> 爱好: <input type="checkbox" name="hobit" value="篮球"/>篮球 <input type="checkbox" name="hobit" value="足球"/>足球 <input type="checkbox" name="hobit" value="羽毛球"/>羽毛球<br/> 个人简介: <textarea rows="5" cols="10" name="info"></textarea><br/> <!-- 隐藏域 --> <input type="hidden" name="id" value="001"/> <input type="submit" value="提交"/> </form> <hr/> <h3>POST方式提交</h3> <form action="/day10/RequestDeom5" method="POST"> 用户名:<input type="text" name="name"/><br/> 密码:<input type="password" name="password"/><br/> 性别: <input type="radio" name="gender" value="男"/>男 <input type="radio" name="gender" value="女"/>女<br/> 籍贯: <select name="jiguan"> <option value="广东">广东</option> <option value="广西">广西</option> <option value="湖南">湖南</option> </select> <br/> 爱好: <input type="checkbox" name="hobit" value="篮球"/>篮球 <input type="checkbox" name="hobit" value="足球"/>足球 <input type="checkbox" name="hobit" value="羽毛球"/>羽毛球<br/> 个人简介: <textarea rows="5" cols="10" name="info"></textarea><br/> <!-- 隐藏域 --> <input type="hidden" name="id" value="001"/> <input type="submit" value="提交"/> </form> </body></html>判断非法链接:
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("/day10/adv.html")){response.getWriter().write("当前是非法链接,请回到首页。<a href='/day10/adv.html'>首页</a>");}else{//正确的链接response.getWriter().write("资源正在下载...");}}
<body> 广告内容,请猛戳这里。<br/> <a href="/day10/RespunseDemo2">点击此处下载</a> </body>输出:referer=null
referer=http://localhost:8080/day10/adv.html
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: chunkedSet-Cookie:SS=Q0=5Lb_nQ; path=/search --表示服务器发送给浏览器的cookie信息(会话管理用到)Expires: -1 --表示通知浏览器不进行缓存Cache-Control: no-cachePragma: no-cacheConnection: close/Keep-Alive --表示服务器和浏览器的连接状态。close:关闭连接 keep-alive:保存连接
服务器向浏览器发送不同的响应信息,浏览器执行不同的行为开发者需要设置响应信息通过servlet然后服务器吧信息发送给浏览器服务器提供了另外一个对象:HttpServletResponse对象,通过servlet改变里面的内容,再把数据发送给浏览器tomcat服务器把请求信息封装到HttpServletRequest对象,且把响应信息封装到HttpServletResponse1)tomcat服务器把请求信息封装到HttpServletRequest对象,且把响应信息封装到HttpServletResponse2)tomcat服务器调用doGet方法,传入request,和response对象3)通过response对象改变响应信息4)tomcat服务器把response对象的内容转换成响应格式内容,再发送给浏览器解析。
response.setStatus(404);//修改状态码response.sendError(404); // 发送404的状态码+404的错误页面
//实体内容(浏览器直接能够看到的内容就是实体内容) response.getWriter().write("01.hello world"); //字符内容。 response.getOutputStream().write("02.hello world".getBytes());//字节内容getWriter()和getOutputStream()方法再同一个Response对象中不能同时调用。
因为这两个一个是字节流一个是字符流!!若先使用字节流,那么在客户端则会有对应得编码表来解析出字符,而同时使用字符流就会出现编码表不一致,导致冲突!
请求重定向(Location):302:表示请求需要进一步细化。需求: 跳转到adv.html 使用请求重定向: 发送一个302状态码+location的响应头response.setStatus(302);//发送一个302状态码response.setHeader("location", "/day10/testMehted.html"); //location的响应头请求重定向简化写法response.sendRedirect("/day09/adv.html");
定时刷新(refresh) 原理:浏览器认识refresh头,得到refresh头之后重新请求当前资源 response.setHeader("refresh", "1"); //每隔1秒刷新次页面 隔n秒之后跳转另外的资源 response.setHeader("refresh", "3;url=/day09/adv.html");//隔3秒之后跳转到adv.html
content-Type作用 --表示服务器发送给浏览器的数据类型及内容编码
下载图片:
response.setContentType("image/jpg");response.setHeader("Content-Disposition", "attachment; filename="+file.getName());FileInputStream in = new FileInputStream(file);byte[] buf = new byte[1024];int len = 0;//把图片内容写出到浏览器while( (len=in.read(buf))!=-1 ){response.getOutputStream().write(buf, 0, len);}response.setHeader("content-type", "text/html");
response.setContentType("text/html;charset=utf-8");//和上面代码等价。推荐使用此方法
response.setContentType("text/html;charset=utf-8");//发送的类型为html类型,并设置编码格式
response.getWriter().write("<html><head><title>this is tilte</title></head><body>中国</body></html>");
***********添加响应数据编码.png
服务器以utf-8编码 浏览器以utf-8解码
response.getOutputStream().write("<html><head><title>this is tilte</title></head><body>中国</body></html>".getBytes("utf-8"));
字节流不存在编码问题
阅读全文
0 0
- Http 笔记
- HTTP笔记.
- http:笔记
- HTTP笔记
- HTTP笔记
- http笔记
- HTTP笔记
- HTTP笔记
- http笔记
- HTTP笔记
- HTTP笔记
- HTTP学习笔记:HTTP报文
- HTTP笔记(五)HTTP报文
- HTTP学习笔记:HTTP报文
- HTTP协议学习笔记
- 《HTTP协议详解》笔记
- Http学习笔记一
- HTTP Referer笔记
- 青否云
- Intel-gpu-tools
- 如何使用register_shutdown_function()捕获PHP致命错误?
- Android SystemServer的创建过程
- matlab之自定义和保存Colorbar
- http笔记
- 安装composer.phar
- 微信公众帐号开发-自定义菜单的创建及菜单事件响应的实例
- TextView只显示一行文字并将多余文字显示为省略号...
- poi操作表格table
- 整理了一些t-sql技巧
- 设计模式(二十一)——中介者模式
- oracle中 sum() over()使用方法
- 全表扫描却产生大量db file sequential read一例