第5篇:HTTP典型会话

2018-01-05  本文已影响8人  大厂offer

在client-server模式的协议中,比如HTTP,会话的过程包含三个阶段:

在HTTP/1.1中,第三阶段完成后连接不再关闭并且客户端允许更深层次的请求,这意味着第二阶段和第三阶段可以被反复使用。

第一步:Establishing a connection 建立连接

在client-server模式的协议中,由客户端建立连接,在HTTP中打开的连接一般而言是基于TCP协议的。

TCP协议的默认端口是80,也可以使用其他的端口,比如8000或8080,一个URL包括了域名和端口,但假如端口就是80的话,则可以省略。更多可参考Identifying resources on the Web.

Note: 在client-server模式的协议下不允许发送一个不明确的请求到客户端,要解决这一问题,Web开发人员可以使用的几种技术:定期通过XMLHttpRequest ping服务器,获取API,使用HTML WebSockets API,或其他类似的协议。

第二步:Sending a client request

一旦连接建立之后,浏览器就可以发送请求。一个客户端请求包含了文本指令,被CRLF分离开,主要被分成三块内容:

请求例子

访问developer.mozilla.org,并且告诉服务器优先返回法语:

GET / HTTP/1.1
Host: developer.mozilla.org
Accept-Language: fr

上面这个例子就是没有第三个区块存在.

使用表单提交的例子:

POST /contact_form.php HTTP/1.1
Host: developer.mozilla.org
Content-Length: 64
Content-Type: application/x-www-form-urlencoded

name=Joe%20User&request=Send%20me%20one%20of%20your%20catalogue

服务端响应的结构

网页请求成功的响应:

HTTP/1.1 200 OK
Date: Sat, 09 Oct 2010 14:28:02 GMT
Server: Apache
Last-Modified: Tue, 01 Dec 2009 20:18:22 GMT
ETag: "51142bc1-7449-479b075b2891b"
Accept-Ranges: bytes
Content-Length: 29769
Content-Type: text/html

<!DOCTYPE html... (here comes the 29769 bytes of the requested web page)

请求的资源已永久移除的通知:

HTTP/1.1 301 Moved Permanently
Server: Apache/2.2.3 (Red Hat)
Content-Type: text/html; charset=iso-8859-1
Date: Sat, 09 Oct 2010 14:30:24 GMT
Location: https://developer.mozilla.org/ (this is the new link to the resource; it is expected that the user-agent will fetch it)
Keep-Alive: timeout=15, max=98
Accept-Ranges: bytes
Via: Moz-Cache-zlb05
Connection: Keep-Alive
X-Cache-Info: caching
X-Cache-Info: caching
Content-Length: 325 (the content contains a default page to display if the user-agent is not able to follow the link)

<!DOCTYPE HTML PUBLIC "-//IETF//DTD HTML 2.0//EN">
<html><head>
<title>301 Moved Permanently</title>
</head><body>
<h1>Moved Permanently</h1>
<p>The document has moved <a href="https://developer.mozilla.org/">here</a>.</p>



<address>Apache/2.2.3 (Red Hat) Server at developer.mozilla.org Port 80</address>
</body></html>

通知所请求的资源不存在:

HTTP/1.1 404 Not Found
Date: Sat, 09 Oct 2010 14:33:02 GMT
Server: Apache
Last-Modified: Tue, 01 May 2007 14:24:39 GMT
ETag: "499fd34e-29ec-42f695ca96761;48fe7523cfcc1"
Accept-Ranges: bytes
Content-Length: 10732
Content-Type: text/html

<!DOCTYPE html... (contains a site-customized page helping the user to find the missing resource)

响应码

HTTP响应状态代码反应服务端是否完成了HTTP的请求。反应分为五类:informational responses, successful responses, redirects, client errors, 和servers errors.

上一篇 下一篇

猜你喜欢

热点阅读