`

java http / Cache / Protocol / Client / Session / Cokie / Status / HttpClient

    博客分类:
  • Java
阅读更多

 

HttpSesstion / http session & cokie / Session Manager

http://zhulin902.iteye.com/blog/939051

http://www.cnblogs.com/myparamita/archive/2009/06/03/1495337.html

http://lrysir.iteye.com/blog/1152071
二.Session和Cookies
或许我们比较关心的是session和cookies,Session是服务器端的存储容器,Cookies是客户端存储数据容器,
Session 两种基本实现方式:
1.通过URL回显方式;
2.通过Cookies实现
如果浏览器的Cookies功能被禁止,那么就会使用URL回显方式, 及在每个url后面接jsessionid=...这样来找到服务器给客户端分配的Session来保证这是同一次会话。
服务器给每个Session分配一个唯一的JSESSIONID,并通过Cookie发送给客户端。
Cookies方式:在Cookie头中携带这个JSESSIONID。这样服务器能够找到这个客户端对应的Session。

  Cookie 概述  
    Cookie 是服务器发送给浏览器的体积很小的纯文本信息,用户以后访问同一个 Web 服务器时浏览器会把它们原样发送给服务器。通过让服务器读取它原先保存到客户端的信息,网站能够为浏览者提供一系列的方便,例如在线交易过程中标识用户身份、安全要求不高的场合避免用户重复输入名字和密码、门户网站的主页定制、有针对性地投放广告,等等。  
    Cookie 的目的就是为用户带来方便,为网站带来增值。虽然有着许多误传,事实上 Cookie 并不会造成严重的安全威胁。 Cookie 永远不会以任何方式执行,因此也不会带来病毒或攻击你的系统。另外,由于浏览器一般只允许存放 300 Cookie ,每个站点最多存放 20 Cookie ,每个 Cookie 的大小限制为 4 KB ,因此 Cookie 不会塞满你的硬盘,更不会被用作 拒绝服务 攻击手段。  

我所知道的有以下区别:   
    
  1、session保存在服务器,客户端不知道其中的信息;cookie保存在客户端,服务器能够知道其中的信息。   
    
  2、session中保存的是对象,cookie中保存的是字符串。   
    
  3、session不能区分路径,同一个用户在访问一个网站期间,所有的session在任何一个地方都可以访问到。而cookie中如果设置了路径参数,那么同一个网站中不同路径下的cookie互相是访问不到的。   
    
  4、session需要借助cookie才能正常<nobr oncontextmenu="return false;" onmousemove="kwM(3);" id="key3" onmouseover="kwE(event,3, this);" style="COLOR: #6600ff; BORDER-BOTTOM: 0px dotted; BACKGROUND-COLOR: transparent; TEXT-DECORATION: underline" onclick="return kwC();" onmouseout="kwL(event, this);" target="_blank">工作</nobr>。如果客户端完全禁止cookie,session将失效。

             http是无状态的协议,客户每次读取web页面时,服务器都打开新的会话,而且服务器也不会自动维护客户的上下文信息,那么要怎么才能实现网上商店中的 购物车呢,session就是一种保存上下文信息的机制,它是针对每一个用户的,变量的值保存在服务器端,通过SessionID来区分不同的客 户,session是以cookie或URL重写为基础的,默认使用cookie来实现,系统会创造一个名为JSESSIONID的输出cookie,我 们叫做session cookie,以区别persistent cookies,也就是我们通常所说的cookie,注意session cookie是存储于浏览器内存中的,并不是写到硬盘上的,这也就是我们刚才看到的JSESSIONID,我们通常情是看不到JSESSIONID的,但 是当我们把浏览器的cookie禁止后,web服务器会采用URL重写的方式传递Sessionid,我们就可以在地址栏看到 sessionid=KWJHUG6JJM65HS2K6之类的字符串。
             明白了原理,我们就可以很容易的分辨出persistent cookies和session cookie的区别了,网上那些关于两者安全性的讨论也就一目了然了,session cookie针对某一次会话而言,会话结束session cookie也就随着消失了,而persistent cookie只是存在于客户端硬盘上的一段文本(通常是加密的),而且可能会遭到cookie欺骗以及针对cookie的跨站脚本攻击,自然不如 session cookie安全了。
             通常session cookie是不能跨窗口使用的,当你新开了一个浏览器窗口进入相同页面时,系统会赋予你一个新的sessionid,这样我们信息共享的目的就达不到 了,此时我们可以先把sessionid保存在persistent cookie中,然后在新窗口中读出来,就可以得到上一个窗口SessionID了,这样通过session cookie和persistent cookie的结合我们就实现了跨窗口的session tracking(会话跟踪)。
            在一些web开发的书中,往往只是简单的把Session和cookie作为两种并列的http传送信息的方式,session cookies位于服务器端,persistent cookie位于客户端,可是session又是以cookie为基础的,明白的两者之间的联系和区别,我们就不难选择合适的技术来开发web service了。

 

 

http://hjxia.iteye.com/blog/156429

HttpClient简介  

    HttpClient是Apache Jakarta Common 下的子项目,用来提供高效的、最新的、功能丰富的支持HTTP协议的客户端编程工具包,并且它支持HTTP协议最新的版本和建议。

HttpClient功能介绍

    以下列出的是HttpClient提供的主要的功能:
    1.实现了所有HTTP的方法(GET,POST,PUT,HEAD等)
    2.支持自动转向
    3.支持HTTPS协议
    4.支持代理服务器等
更多功能可参见http://wiki.apache.org/jakartahttpclient/HttpClientPowered

web color

HttpClient简介

    HttpClient是Apache Jakarta Common 下的子项目,用来提供高效的、最新的、功能丰富的支持HTTP协议的客户端编程工具包,并且它支持HTTP协议最新的版本和建议。

HttpClient功能介绍

    以下列出的是HttpClient提供的主要的功能:
    1.实现了所有HTTP的方法(GET,POST,PUT,HEAD等)
    2.支持自动转向
    3.支持HTTPS协议
    4.支持代理服务器等
更多功能可参见http://wiki.apache.org/jakartahttpclient/HttpClientPowered

HttpURLConnection VS HttpClient性能测试

http://wj98127.iteye.com/blog/617014

版本: HttpURLConnection  jdk1.6;HttpClient 3.0.1

在项目中有一个特别小的相关应用,在选择时做了一下测试,之前先对两个类进行下说明:

HttpURLConnection  java的标准类(java.net)

HttpClient Jakarta Commons HttpClient,提供对HTTP协议访问的封装,包括http的请求头,参数,内容体,响应等及多线程的应用。

 

测试代码:

Java代码  收藏代码
  1. import java.io.BufferedReader;  
  2. import java.io.IOException;  
  3. import java.io.InputStream;  
  4. import java.io.InputStreamReader;  
  5. import java.net.HttpURLConnection;  
  6. import java.net.MalformedURLException;  
  7. import java.net.URL;  
  8.   
  9. import org.apache.commons.httpclient.DefaultHttpMethodRetryHandler;  
  10. import org.apache.commons.httpclient.HttpClient;  
  11. import org.apache.commons.httpclient.HttpException;  
  12. import org.apache.commons.httpclient.HttpStatus;  
  13. import org.apache.commons.httpclient.methods.GetMethod;  
  14. import org.apache.commons.httpclient.params.HttpMethodParams;  
  15.   
  16. public class HttpClientTest {  
  17.   
  18.     private static String link = "http://www.baidu.com";  
  19.   
  20.     public static void main(String[] args) {  
  21.         long a = System.currentTimeMillis();  
  22.         useHttpURlConnection();  
  23.         long b = System.currentTimeMillis();  
  24.         System.out.println("use httpurlconnection: "+(b-a));  
  25.         long c = System.currentTimeMillis();  
  26.         useHttpClient();  
  27.         long d = System.currentTimeMillis();  
  28.         System.out.println("use httpclient: "+(d-c));  
  29.     }  
  30.       
  31.     public static void useHttpURlConnection(){  
  32.         HttpURLConnection conn = null;  
  33.         URL url = null;  
  34.         String result = "";  
  35.         try {  
  36.             url = new java.net.URL(link);  
  37.             conn = (HttpURLConnection) url.openConnection();  
  38.             conn.setConnectTimeout(10000);  
  39.             conn.connect();  
  40.   
  41.             InputStream urlStream = conn.getInputStream();  
  42.             BufferedReader reader = new BufferedReader(new InputStreamReader(urlStream));  
  43.             String s = "";  
  44.             while ((s = reader.readLine()) != null) {  
  45.                 result += s;  
  46.             }  
  47.             System.out.println(result);  
  48.             reader.close();  
  49.             urlStream.close();  
  50.             conn.disconnect();  
  51.         } catch (MalformedURLException e) {  
  52.             e.printStackTrace();  
  53.         } catch (IOException e) {  
  54.             e.printStackTrace();  
  55.         } catch(Exception e){  
  56.             e.printStackTrace();  
  57.         }  
  58.     }  
  59.   
  60.     public static void useHttpClient(){  
  61.         HttpClient client = new HttpClient();  
  62.         GetMethod method = new GetMethod(link);  
  63.         method.getParams().setParameter(HttpMethodParams.RETRY_HANDLER,  
  64.                 new DefaultHttpMethodRetryHandler(3false));  
  65.         try {  
  66.             int statusCode = client.executeMethod(method);  
  67.   
  68.             if (statusCode != HttpStatus.SC_OK) {  
  69.                 System.err.println("Method failed: " + method.getStatusLine());  
  70.             }  
  71.             byte[] responseBody = method.getResponseBody();  
  72.             System.out.println(new String(responseBody));  
  73.         } catch (HttpException e) {  
  74.             System.err.println("Fatal protocol violation: " + e.getMessage());  
  75.             e.printStackTrace();  
  76.         } catch (IOException e) {  
  77.             System.err.println("Fatal transport error: " + e.getMessage());  
  78.             e.printStackTrace();  
  79.         } finally {  
  80.             method.releaseConnection();  
  81.         }  
  82.     }  
  83. }  

 

测试结果:

use httpurlconnection: 47

use httpclient: 641

结果很明显示,但是在实际应用中,还是应该根据实际的需求进行取舍。

实际案例应用

<!--[if gte mso 9]><xml> <o:DocumentProperties> <o:Version>14.00</o:Version> </o:DocumentProperties> </xml><![endif]-->

Scenario

Users

TPS

Web cpu

1

WAS cpu

2

DB2 cpu

1

Remark

单截词搜索场景测试

10

200/

10%

5%

35%

代码优化:

截词搜索场景测试

20

400/

15%

10%

55%

Hibernate find改为Hibernate creat query

单截词搜索场景测试

30

600/

20%

15%

75%

调整日志打印级别

输入详细地址+cache场景测试

30

50/

30%

20%

100%

初始代码

输入详细地址+cache场景测试

30

80/

30%

20%

100%

代码优化:

HttpUrlConnection改为HttpClient

输入详细地址+cache场景测试

30

800/

30%

20%

5%

SQL优化

物流地图查询地址场景测试

30

80/

-

-

-

垃圾中的垃圾

 SQL优化
--#优化前 TPS = 80
select addressmat0_.ID as ID3_, addressmat0_.CITY as CITY3_, addressmat0_.DISTRICT as DISTRICT3_, addressmat0_.DETAILADDRESS as DETAILAD4_3_, addressmat0_.AREACODE as AREACODE3_, addressmat0_.X as X3_, addressmat0_.Y as Y3_, addressmat0_.TYPE as TYPE3_ from ADDRESS_MATCH addressmat0_ where addressmat0_.CITY=? and addressmat0_.DISTRICT=? and locate(addressmat0_.DETAILADDRESS, ?)>0
--#优化后 TPS = 800
select addressmat0_.ID as ID3_, addressmat0_.CITY as CITY3_, addressmat0_.DISTRICT as DISTRICT3_, addressmat0_.DETAILADDRESS as DETAILAD4_3_, addressmat0_.AREACODE as AREACODE3_, addressmat0_.X as X3_, addressmat0_.Y as Y3_, addressmat0_.TYPE as TYPE3_ from ADDRESS_MATCH addressmat0_ where addressmat0_.CITY=? and addressmat0_.DISTRICT=? and addressmat0_.DETAILADDRESS =?

 

Apache HttpClient 连接池的使用

http://xiaoa7.iteye.com/blog/1262034

为什么要使用HttpClient池?

都知道如果单纯使用HttpClient去抓取一个网站的内容时,会消耗在请求连接上大部分时间。(P:其实大家都明白数据库连接池的重要性,这个吗,也一样,在服务端需要大批量抓取或大并发抓取其他网站数据时,尤其重要)。

不废话了,说一下怎么用吧。

 

需要下的包:





下面一个代码测试代码,仅供参考。
从测试结果来看,平均每次请求响应都在200毫秒以内。

Java代码  收藏代码
  1. import  java.io.IOException;  
  2. import  java.util.Random;  
  3.   
  4. import  org.apache.commons.logging.Log;  
  5. import  org.apache.commons.logging.LogFactory;  
  6. import  org.apache.http.HttpEntity;  
  7. import  org.apache.http.HttpResponse;  
  8. import  org.apache.http.HttpStatus;  
  9. import  org.apache.http.HttpVersion;  
  10. import  org.apache.http.client.ClientProtocolException;  
  11. import  org.apache.http.client.HttpClient;  
  12. import  org.apache.http.client.methods.HttpGet;  
  13. import  org.apache.http.conn.scheme.PlainSocketFactory;  
  14. import  org.apache.http.conn.scheme.Scheme;  
  15. import  org.apache.http.conn.scheme.SchemeRegistry;  
  16. import  org.apache.http.impl.client.DefaultHttpClient;  
  17. import  org.apache.http.impl.conn.tsccm.ThreadSafeClientConnManager;  
  18. import  org.apache.http.params.BasicHttpParams;  
  19. import  org.apache.http.params.CoreConnectionPNames;  
  20. import  org.apache.http.params.CoreProtocolPNames;  
  21. import  org.apache.http.params.HttpParams;  
  22.   
  23. public   class  HttpClientUtils {  
  24.     private   static   final  Log log = LogFactory.getLog(HttpClientUtils. class );  
  25.     private   static  ThreadSafeClientConnManager cm =  null ;  
  26.     static  {  
  27.         SchemeRegistry schemeRegistry = new  SchemeRegistry();  
  28.         schemeRegistry.register(new  Scheme( "http" 80 , PlainSocketFactory  
  29.                 .getSocketFactory()));  
  30.   
  31.         cm = new  ThreadSafeClientConnManager(schemeRegistry);  
  32.         try  {  
  33.             int  maxTotal =  100 ;  
  34.             cm.setMaxTotal(maxTotal);  
  35.         } catch  (NumberFormatException e) {  
  36.             log.error(  
  37.                     "Key[httpclient.max_total] Not Found in systemConfig.properties" ,  
  38.                     e);  
  39.         }  
  40.         // 每条通道的并发连接数设置(连接池)   
  41.         try  {  
  42.             int  defaultMaxConnection =  50 ;  
  43.             cm.setDefaultMaxPerRoute(defaultMaxConnection);  
  44.         } catch  (NumberFormatException e) {  
  45.             log.error(  
  46.                     "Key[httpclient.default_max_connection] Not Found in systemConfig.properties" ,  
  47.                     e);  
  48.         }  
  49.     }  
  50.   
  51.     public   static  HttpClient getHttpClient() {  
  52.         HttpParams params = new  BasicHttpParams();  
  53.         params.setParameter(CoreProtocolPNames.PROTOCOL_VERSION,  
  54.                 HttpVersion.HTTP_1_1);  
  55.         params.setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, 3000 );  // 3000ms   
  56.         return   new  DefaultHttpClient(cm, params);  
  57.     }  
  58.   
  59.     public   static   void  release() {  
  60.         if  (cm !=  null ) {  
  61.             cm.shutdown();  
  62.         }  
  63.     }  
  64.   
  65.     public   static   void  main(String[] args)  throws  ClientProtocolException,  
  66.             IOException {  
  67.         Random r = new  Random();  
  68.         for  ( int  i =  0 ; i <  10 ; i++) {  
  69.             long  l1 = System.currentTimeMillis();  
  70.             HttpClient client = getHttpClient();  
  71.   
  72.             HttpGet get = new  HttpGet( "http://www.baidu.com/s?wd="   
  73.                     + r.nextInt(5000 ));  
  74.             HttpResponse response = client.execute(get);  
  75.             if  (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {  
  76.                 HttpEntity entity = response.getEntity();  
  77.                 long  l = entity.getContentLength();  
  78.                 System.out.println("回应结果长度:"  + l);  
  79.             }  
  80.             System.out.println("查询耗时"  + (System.currentTimeMillis() - l1));  
  81.         }  
  82.     }  
  83.   
  84. }  

 HelpHttpClient.java

 

package com.s*****.recommend.portal.ui.util;

import java.io.IOException;

import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.HttpVersion;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.conn.ClientConnectionManager;
import org.apache.http.conn.params.ConnManagerParams;
import org.apache.http.conn.params.ConnPerRouteBean;
import org.apache.http.conn.scheme.PlainSocketFactory;
import org.apache.http.conn.scheme.Scheme;
import org.apache.http.conn.scheme.SchemeRegistry;
import org.apache.http.conn.ssl.SSLSocketFactory;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.impl.conn.tsccm.ThreadSafeClientConnManager;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;
import org.apache.http.params.HttpProtocolParams;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;
import org.apache.log4j.Logger;

/**
 * 
 * 
 * 功能描述: http 请求连接
 * @version 1.0.0
 */
public class HelpHttpClient 
{
    private static Logger logger = Logger.getLogger(HttpClientUtil.class);

    private static final String CHARSET = HTTP.UTF_8;
    private static HttpClient client;

    /** 
     * 最大连接数 
     */  
    public final static int MAX_TOTAL_CONNECTIONS = 1500;  //默认20 现改为1500 ,Loadrunner用户并发TPS 由此上升
    /** 
     * 获取连接的最大等待时间 
     */  
    public final static int WAIT_TIMEOUT = 60000;  
    /** 
     * 每个路由最大连接数 
     */  
    public final static int MAX_ROUTE_CONNECTIONS = 1000;  
    /** 
     * 连接超时时间 
     */  
    public final static int CONNECT_TIMEOUT = 3000;  
    /** 
     * 读取超时时间 
     */  
    public final static int READ_TIMEOUT = 10000;  



    /**
     * 私有构造方法
     */
    private HelpHttpClient() 
    {
    }

    /**
     * 
     * 功能描述:发送http 请求获取字符串
     * 输入参数:<按照参数定义顺序> 
     * @param 参数说明  
     * url 请求url
     * charset 转化字符串编码
     * 返回值:  String
     * @return  json 字符串
     * @see 需要参见的其它内容
     */
    public static String getJson(String url, String charset)
    {
        // 获取 url 连接
        HttpClient client = getHttpClient();
        HttpGet getMethod = new HttpGet(url);
        String jsonStr = "";
        try 
        {
            // 执行请求
            HttpResponse response = client.execute(getMethod);
            // 响应结果,如果是200,则响应成功
            if (HttpStatus.SC_OK == response.getStatusLine().getStatusCode())
            {
                // 将响应流转化为字符串
                jsonStr = EntityUtils.toString(response.getEntity(), charset);
            }

        } catch (ClientProtocolException e) 
        {
            logger.debug("httpclient create failure.", e);
        } catch (IOException e) 
        {
            logger.debug("httpclient create failure.", e);
        }

        return jsonStr;
    }


    /**
     * 
     * 功能描述:多线程 http 请求
     * 返回值:  类型 <说明> 
     * @return 返回值 HttpClient
     * @see 需要参见的其它内容
     */
    @SuppressWarnings("deprecation")
    public static synchronized HttpClient getHttpClient()
    {
        if (null == client)
        {
            HttpParams httpParams = new BasicHttpParams();

            // 设置基本参数
            HttpProtocolParams.setVersion(httpParams, HttpVersion.HTTP_1_1);
            HttpProtocolParams.setContentCharset(httpParams, CHARSET);
            HttpProtocolParams.setUseExpectContinue(httpParams, true);

            // 设置最大连接数  
            ConnManagerParams.setMaxTotalConnections(httpParams, MAX_TOTAL_CONNECTIONS);  
            // 设置获取连接的最大等待时间  
            ConnManagerParams.setTimeout(httpParams, WAIT_TIMEOUT);  
            // 设置每个路由最大连接数  
            ConnPerRouteBean connPerRoute = new ConnPerRouteBean(MAX_ROUTE_CONNECTIONS);  
            ConnManagerParams.setMaxConnectionsPerRoute(httpParams,connPerRoute);  
            // 设置连接超时时间  
            HttpConnectionParams.setConnectionTimeout(httpParams, CONNECT_TIMEOUT);  
            // 设置读取超时时间  
            HttpConnectionParams.setSoTimeout(httpParams, READ_TIMEOUT);  

            SchemeRegistry regist = new SchemeRegistry();
            // 设置 http 请求支持http 和 https 两种模式
            regist.register(new Scheme("http", 80,PlainSocketFactory.getSocketFactory()));
            regist.register(new Scheme("https", 443, SSLSocketFactory.getSocketFactory()));

            // 使用线程安全的链接管理创建 HttpClient
            ClientConnectionManager connManager = new ThreadSafeClientConnManager(httpParams, regist);

            client = new DefaultHttpClient(connManager);

        }

        return client;
    }
}
 

 

 

 

http协议学习笔记

http://madbluesky.iteye.com/blog/348637

HTTP协议状态码的含义

http://koda.iteye.com/blog/463840

基于资源的HTTP Cache的实现介绍

http://www.iteye.com/topic/462476

--------------------------------------------------------------------

 

HTTP 1.1与HTTP 1.0的区别

http://wiki.juziku.com/71.htm

http://juziku.iteye.com/blog/906845

      一个WEB站点每天可能要接收到上百万的用户请求,为了提高系统的效率,HTTP 1.0规定浏览器与服务器只保持短暂的连接,浏览器的每次请求都需要 与服务器建立一个TCP连接,服务器完成请求处理后立即断开TCP连接,服务器不跟踪每个客户也不记录过去的请求。但是,这也造成了一些性能上的缺陷,例 如,一个包含有许多图像的网页文件中并没有包含真正的图像数据内容,而只是指明了这些图像的URL地址,当WEB浏览器访问这个网页文件时,浏览器首先要 发出针对该网页文件的请求,当浏览器解析WEB服务器返回的该网页文档中的HTML内容时,发现其中的<img>图像标签后,浏览器将根 据<img>标签中的src属性所指定的URL地址再次向服务器发出下载图像数据的请求,如图下图所示。

http1.0
      显然,访问一个包含有许多图像的网页文件的整个过程包含了多次请求和响应,每次请求和响应都需要建立一个单独的连接,每次连接只是传输一个文档和图像, 上一 次和下一次请求完全分离。即使图像文件都很小,但是客户端和服务器端每次建立和关闭连接却是一个相对比较费时的过程,并且会严重影响客户机和服务器的性 能。当一个网页文件中包含Applet,JavaScript文件,CSS文件等内容时,也会出现类似上述的情况。
      为了克服HTTP 1.0的这个缺陷,HTTP 1.1支持持久连接,在一个TCP连接上可以传送多个HTTP请求和响应,减少了建立和关闭连接的消耗和延迟。一个包含有许多图像的网页文件的多个请求和 应答可以在一个连接中传输,但每个单独的网页文件的请求和应答仍然需要使用各自的连接。HTTP 1.1还允许客户端不用等待上一次请求结果返回,就可以发出下一次请求,但服务器端必须按照接收到客户端请求的先后顺序依次回送响应结果,以保证客户端能 够区分出每次请求的响应内容,这样也显著地减少了整个下载过程所需要的时间。基于HTTP 1.1协议的客户机与服务器的信息交换过程,如图下图所示。




      可见,HTTP 1.1在继承了HTTP 1.0优点的基础上,也克服了HTTP 1.0的性能问题。不仅如此,HTTP 1.1还通过增加更多的请求头和响应头来改进和扩充HTTP 1.0的功能。例如,由于HTTP 1.0不支持Host请求头字段,WEB浏览器无法使用主机头名来明确表示要访问服务器上的哪个WEB站点,这样就无法使用WEB服务器在同一个IP地址 和端口号上配置多个虚拟WEB站点。在HTTP 1.1中增加Host请求头字段后,WEB浏览器可以使用主机头名来明确表示要访问服务器上的哪个WEB站点,这才实现了在一台WEB服务器上可以在同一 个IP地址和端口号上使用不同的主机名来创建多个虚拟WEB站点。HTTP 1.1的持续连接,也需要增加新的请求头来帮助实现,例如,Connection请求头的值为Keep-Alive时,客户端通知服务器返回本次请求结果 后保持连接;Connection请求头的值为close时,客户端通知服务器返回本次请求结果后关闭连接。HTTP 1.1还提供了与身份认证、状态管理和Cache缓存等机制相关的请求头和响应头。

http协议学习笔记

http://madbluesky.iteye.com/blog/348637

      http协议(超文本传输协议)是一套计算机通过网络进行通信的规则,使用http协议客户机能够从http服务器请求信息和服务。 http协议采用请求/响应模型,在这一模型中总是客户端向服务器发送请求,服务器根据请求信息,请求实体的权限请求。客户端请求的方式主要有 GET,POST,HEAD等。

GET     请求获取Request-URI所标识的资源
POST    在Request-URI所标识的资源后附加新的数据
HEAD    请求获取由Request-URI所标识的资源的响应消息报头
PUT     请求服务器存储一个资源,并用Request-URI作为其标识
DELETE  请求服务器删除Request-URI所标识的资源
TRACE   请求服务器回送收到的请求信息,主要用于测试或诊断
CONNECT 保留将来使用
OPTIONS 请求查询服务器的性能,或者查询与资源相关的选项和需求

 

 一次完整的http通信过程中,web浏览器与web服务器之间将完成以下七个步骤:

   1。 建立TCP连接。在http连接之前web浏览器首先要通过网络与服务器要建立连接,该连接是通过tcp协议来完成的。http协议是比TCP更高层次的协议,根据规则只有低层次的协议建立好之后才能建立更高层次的连接,所以首先建立tcp连接。

   2。一旦建立了tcp连接,web浏览器就可以向http服务器发送请求命令。

       例如:GET/sample/hello.jsp HTTP/1.1

       GET 表示请求的方式为GET,/sample/hello.jsp 表示请求的资源的uri,HTTP/1.1表示http协议的版本。

  

   3。web浏览器发送请求命令后还要以头信息的形式向向web服务器发送一些别的信息,之后浏览器发送一空白行来通知服务器头信息以发送完毕。

      头信息主要包括:

      Date头域 :Date头域表示消息发送的时间,时间的描述格式由rfc822定义。例如,

                       Date:Mon,31Dec200104:25:57GMT。Date描述的时间表示世界标准时,换算成本地时间,需要知

                       道用户所在的时区。

      Host头域 :Host头域指定请求资源的Intenet主机和端口号,必须表示请求url的原始服务器或网关的位置。

                      HTTP/1.1请求必须包含主机头域,否则系统会以400状态码返回

      

       Referer头域 :Referer 头域允许客户端指定请求uri的源资源地址,这可以允许服务器生成回退链表,可用来登陆、

                          优化cache等。他也允许废除的或错误的连接由于维护的目的被追踪。如果请求的uri没有自己的uri地

                          址,Referer不能被发送。如果指定的是部分uri地址,则此地址应该是一个相对地址。

      pragma头域 :Pragma头域用来包含实现特定的指令,最常用的是Pragma:no-cache

 

      Range头域 :Range头域可以请求实体的一个或者多个子范围。例如,
                     表示头500个字节:bytes=0-499
                     表示第二个500字节:bytes=500-999
                     表示最后500个字节:bytes=-500
                     表示500字节以后的范围:bytes=500-
                     第一个和最后一个字节:bytes=0-0,-1
                     同时指定几个范围:bytes=500-600,601-999

                      但是服务器可以忽略此请求头,如果无条件GET包含Range请求头,响应会以状态码206

                        (PartialContent)返回而不是以200 (OK)。

      

      User-agent头域 :User-Agent头域的内容包含发出请求的用户信息。

                                

      Cache-Control头域 :Cache -Control指定请求和响应遵循的缓存机制。在请求消息或响应消

                                 息中设置 Cache-Control并不会修改另一个消息处理过程中的缓存处理过程。请求时的缓存指令

                                 包括no-cache、no-store、max-age、 max-stale、min-fresh、only-if-cached,响应消

                                 息中的指令包括public、private、no-cache、no- store、no-transform、must-

                                 revalidate、proxy-revalidate、max-age。各个消息中的指令含义如 下:

  Public指示响应可被任何缓存区缓存。

  Private指示对于单个用户的整个或部分响应消息,不能被共享缓存处理。这允许服务器仅仅描述当用户的部分响应消

      息,此响应消息对于其他用户的请求无效。

  no-cache指示请求或响应消息不能缓存

  no-store用于防止重要的信息被无意的发布。在请求消息中发送将使得请求和响应消息都不使用缓存。

  max-age指示客户机可以接收生存期不大于指定时间(以秒为单位)的响应。

  min-fresh指示客户机可以接收响应时间小于当前时间加上指定时间的响应。

  max-stale指示客户机可以接收超出超时期间的响应消息。如果指定max-stale消息的值,那么客户机可以接收超出

      超时期指定值之内的响应消息。

 

      …………等等。

     

       消息头以空行表示结束,消息头后面可接消息体(可选的)如:name=xiaoming&sex=1

      

   4。web 服务器应答。客户机发送请求后,服务器将向客户机回送应答。

       例如:HTTP/1.1 200 OK

       HTTP/1.1 表示http协议的版本,200表示响应状态码,ok为响应状态码的文字描述信息。

       响应状态码的第一个数字可 能取5个不同的值:

      1xx:信息响应类,表示接收到请求并且继续处理

      2xx:处理成功响应类,表示动作被成功接收、理解和接受

      3xx:重定向响应类,为了完成指定的动作,必须接受进一步处理

      4xx:客户端错误,客户请求包含语法错误或者是不能正确执行

      5xx:服务端错误,服务器不能正确执行一个正确的请求

   5。web服务器发送应答头信息。

         Location响应头
     Location响应头用于重定向接收者到一个新URI地址。

  Server响应头
  Server响应头包含处理请求的原始服务器的软件信息。此域能包含多个产品标识和注释,产品标识一般按照重要性排

      序。

  实体
  请求消息和响应消息都可以包含实体信息,实体信息一般由实体头域和实体组成。实体头域包含关于实体的原信息,实

      体头包括Allow、Content- Base、Content-Encoding、Content-Language、 Content-Length、Content-

      Location、Content-MD5、Content-Range、Content-Type、 Etag、Expires、Last-Modified、

      extension-header。extension-header允许客户端定义新的实体头,但是这些域可能无法未接受方识别。实体可

      以是一个经过编码的字节流,它的编码方式由Content-Encoding或Content-Type定义,它的长度由Content-

      Length或Content-Range定义。

  Content-Type实体头
  Content-Type实体头用于向接收方指示实体的介质类型,指定HEAD方法送到接收方的实体介质类型,或GET方法发

      送的请求介质类型 Content-Range实体头

  Content-Range 实体头用于指定整个实体中的一部分的插入位置,他也指示了整个实体的长度。在服务器向客户返回

      一个部分响应,它必须描述响应覆盖的范围和整个实体长度。一般格式:

  Content-Range:bytes-unitSPfirst-byte-pos-last-byte-pos/entity-legth

  例如,传送头500个字节次字段的形式:Content-Range:bytes0- 499/1234如果一个http消息包含此节(例如,

      对范围请求的响应或对一系列范围的重叠请求),Content-Range表示传送的范围, Content-Length表示实际传

      送的字节数。

   6。web服务器向客户机发送数据。

   7。web服务器关闭tcp连接。

 HTTP协议的主要特点可概括如下:

1.支持客户/服务器模式。

2.简单快速:客户向服务器请求服务时,只需传送请求方法和路径。请求方法常用的有GET、HEAD、POST。每种方法规定了客户与服务器联系的类型不同。由于HTTP协议简单,使得HTTP服务器的程序规模小,因而通信速度很快。

3.灵活:HTTP允许传输任意类型的数据对象。正在传输的类型由Content-Type加以标记。

4.无连接:无连接的含义是限制每次连接只处理一个请求。服务器处理完客户的请求,并收到客户的应答后,即断开连接。采用这种方式可以节省传输时间。

5.无状态:HTTP协议是无状态协议。无状态是指协议对于事务处理没有记忆能力。缺少状态意味着如果后续处理需要前面的信息,则它必须重传,这样可能导致每次连接传送的数据量增大。另一方面,在服务器不需要先前信息时它的应答就较快。


 

http 状态码含义

http://koda.iteye.com/blog/463840
-----------------------------------------
"100":Continue
"101":witchingProtocols
"200":OK
"201":Created
"202":Accepted
"203":Non-AuthoritativeInformation
"204":NoContent
"205":ResetContent
"206":PartialContent
"300":MultipleChoices
"301":MovedPermanently
"302":Found
"303":SeeOther
"304":NotModified
"305":UseProxy
"307":TemporaryRedirect
"400":BadRequest
"401":Unauthorized
"402":PaymentRequired
"403":Forbidden
"404":NotFound
"405":MethodNotAllowed
"406":NotAcceptable
"407":ProxyAuthenticationRequired
"408":RequestTime-out
"409":Conflict
"410":Gone
"411":LengthRequired
"412":PreconditionFailed
"413":RequestEntityTooLarge
"414":Request-URITooLarge
"415":UnsupportedMediaType
"416":Requestedrangenotsatisfiable
"417":ExpectationFailed
"500":InternalServerError
"501":NotImplemented
"502":BadGateway
"503":ServiceUnavailable
"504":GatewayTime-out
"505":HTTPVersionnotsupported

HTTP状态码

1**:请求收到,继续处理
2**:操作成功收到,分析、接受
3**:完成此请求必须进一步处理
4**:请求包含一个错误语法或不能完成
5**:服务器执行一个完全有效请求失败

100——客户必须继续发出请求
101——客户要求服务器根据请求转换HTTP协议版本

200——交易成功
201——提示知道新文件的URL
202——接受和处理、但处理未完成
203——返回信息不确定或不完整
204——请求收到,但返回信息为空
205——服务器完成了请求,用户代理必须复位当前已经浏览过的文件
206——服务器已经完成了部分用户的GET请求

300——请求的资源可在多处得到
301——永久转移
302——在其他地址发现了请求数据
303——建议客户访问其他URL或访问方式
304——客户端已经执行了GET,但文件未变化
305——请求的资源必须从服务器指定的地址得到
306——前一版本HTTP中使用的代码,现行版本中不再使用
307——申明请求的资源临时性删除

400——错误请求,如语法错误
401——请求授权失败
402——保留有效ChargeTo头响应
403——请求不允许
404——没有发现文件、查询或URl
405——用户在Request-Line字段定义的方法不允许
406——根据用户发送的Accept拖,请求资源不可访问
407——类似401,用户必须首先在代理服务器上得到授权
408——客户端没有在用户指定的饿时间内完成请求
409——对当前资源状态,请求不能完成
410——服务器上不再有此资源且无进一步的参考地址
411——服务器拒绝用户定义的Content-Length属性请求
412——一个或多个请求头字段在当前请求中错误
413——请求的资源大于服务器允许的大小
414——请求的资源URL长于服务器允许的长度
415——请求资源不支持请求项目格式
416——请求中包含Range请求头字段,在当前请求资源范围内没有range指示值,请求也不包含If-Range请求头字段
417——服务器不满足请求Expect头字段指定的期望值,如果是代理服务器,可能是下一级服务器不能满足请求

500——服务器产生内部错误
501——服务器不支持请求的函数
502——服务器暂时不可用,有时是为了防止发生系统过载
503——服务器过载或暂停维修
504——关口过载,服务器使用另一个关口或服务来响应用户,等待时间设定值较长
505——服务器不支持或拒绝支请求头中指定的HTTP版本

 

httpcache  / HttpCache / HTTP Cache 学习

http://wuhua.iteye.com/blog/400368


http协议里控制浏览器缓存的头有三个Cache-Control,Expires,Last-Modified
对于静态页面还有Etag。
一、先来看第一种情况:apache 静态页面
apache发送给客户端的静态页面一般包含Last-Modified和Etag,这两个标签的值来自静态文件的修改时间和inode,
下面是截取得apache返回客户端的头
---------
Last-Modified: Fri, 26 Jan 2007 01:53:34 GMT
ETag: "3f9f640-318-cb9f8380"
---------
搜索引擎之所以喜欢静态文件是因为有这两个标识,可以判断文件是否更新过
二、PHP等动态页面
由于php是动态生成的,它的内容是不能根据php程序的时间来确定最后修改日期,所以默认php返回客户端的时候补包含任何缓存控制,要想利用好缓存就必须了解缓存机制,和理减少b,s的交互,缩减带宽流量,减轻服务器负担...好处多多
三、缓存控制的具体含义
先解释一下本人经过测试理解的这几个标签的含义
Cache-Control:指定请求和响应遵循的缓存机制。在请求消息或响应消息中设置Cache-Control并不会修改另一个消息处理过程中的缓 存处理过程。请求时的缓存指令包括no-cache、no-store、max-age、max-stale、min-fresh、only-if- cached,响应消息中的指令包括public、private、no-cache、no-store、no-transform、must- revalidate、proxy-revalidate、max-age。各个消息中的指令含义如下:
Public指示响应可被任何缓存区缓存。
Private指示对于单个用户的整个或部分响应消息,不能被共享缓存处理。这允许服务器仅仅描述当用户的部分响应消息,此响应消息对于其他用户的请求无效。
no-cache指示请求或响应消息不能缓存
no-store用于防止重要的信息被无意的发布。在请求消息中发送将使得请求和响应消息都不使用缓存。
max-age指示客户机可以接收生存期不大于指定时间(以秒为单位)的响应。
min-fresh指示客户机可以接收响应时间小于当前时间加上指定时间的响应。
max-stale指示客户机可以接收超出超时期间的响应消息。如果指定max-stale消息的值,那么客户机可以接收超出超时期指定值之内的响应消息。
php用法:
在输出之前用header(),(如果使用ob_start()可以将header放在程序任意地方)
header('Cache-Control: max-age=8');
max-age=8表示最大生存期8秒,超过8秒浏览器必须去服务器重新读取,这个时间是以用户的读取页面开始计时的,而Expires是绝对时间。
Expires:缓存过期的绝对时间,如果过了它指定的那个时间点,浏览器就不认缓存了,要去服务器重新请求一份最新的。
Last-Modified:文档的最后修改时间,它的妙用就是:1 如果是静态文件,客户端会发上来它缓存里的时间,apache会来比对,如果发现没有修改就直接返回一个头,状态码是304,字节数非常少,(高级版本还会增加比较Etag来确定文件是否变化)
2 php动态文件: 客户端发上比对时间,php会判断是否修改,如果修改时间相同,就只会返回1024字节,至于为什么返回1024不得而知,如果你 的php生成的文件非常大,它也只返回1024,所以比较省带宽,客户端会根据服务器端发过来的修改时间自动从缓存文件里显示。
注:如果没有Last-Modified头,Cache-Control和Expires也是可以起作用的,但每次请求要返回真实的文件字节数,而不是1024
四、HOW ?
静态页面不用去管它了,如果想更好的控制静态页面的缓存,apache有几个模块可以很好的控制,这里不讨论
php页面:
这里分两种:1 不经常改动的页面,类似新闻发布,这类页面的特点:第一次发布之后会有几次改动,随着时间推移基本不会再修改。控制策略应该是:1第一次 发布之发送Last-Modified,max-age设定1天,修改过之后更新Last-Modified,max-age时间随着修改次数正常。这样 似乎比较繁琐,还要记录修改次数,也可以预计一下下次可能的修改时间用Expires指定到大概时间过期
php代码:
//header('Cache-Control: max-age=86400');//缓存一天
header('Expires: Mon, 29 Jan 2007 08:56:01 GMT');//指定过期时间
header('Last-Modified: '.gmdate('D, d M Y 01:01:01',$time).' GMT');//格林尼治时间,$time是文件添加时候的时间戳
2 经常改动的页面   类似bbs,论坛程序,这种页面更新速度比较快,缓存的主要作用是防止用户频繁刷新列表,导致服务器数据库负担,既要保证更新的及时性,也要保证缓存能被利用
这里一般用Cache-Control来控制,根据论坛的发帖的频率灵活控制max-age。
header('Cache-Control: max-age=60');//缓存一分钟
header('Last-Modified: '.gmdate('D, d M Y 01:01:01',$time).' GMT');//格林尼治时间,$time是帖子的最后更新时间戳
五 额外
1 刷新,转到,强制刷新的区别
浏览器上有刷新和转到按键,有的浏览器支持用ctrl+F5强制刷新页面,它们的区别是什么?
转到:用户点击链接就是转到,它完全使用缓存机制,如果有Last-Modified那么不会和服务器通讯,用抓包工具可以查看到发送字节是0byte,如果缓存过期,那么它会执行F5刷新的动作。
刷新(F5):这种刷新也是根据缓存是否有Last-Modified来决定,如果有会转入304或1024(php),如果没有最后更新时间那么去服务器读取,返回真实文档大小
强制刷新:完全抛弃缓存机制,去服务器读取最新文档,向服务器发送的header如下
Cache-Control: no-cache
2 调试工具
查看浏览器和服务器交互比较好的工具是httpwatch pro,现在的版本4.1,支持ie7
还有别的代理抓包工具可以分析,http debugging。没用过,还有tcp抓包工具,2000自带的network monitor不过不是专门针对http的比较难用
六 声明
本文作者保留所有权力,允许被自由查看和转载,但必须指明作者(Ash)和源网址(www.cosrc.com);不允许商用
 
下面是HTTP 协议 E文原版
 
 Cache-Control
   The general-header field "Cache-Control" is used to specify
   directives that MUST be obeyed by all caches along the request/
   response chain.  The directives specify behavior intended to prevent
   caches from adversely interfering with the request or response.
   Cache directives are unidirectional in that the presence of a
   directive in a request does not imply that the same directive is to
   be given in the response.
      Note that HTTP/1.0 caches might not implement Cache-Control and
      might only implement Pragma: no-cache (see Section 3.4).
   Cache directives MUST be passed through by a proxy or gateway
   application, regardless of their significance to that application,
   since the directives might be applicable to all recipients along the
   request/response chain.  It is not possible to target a directive to
   a specific cache.
Fielding, et al.       Expires September 10, 2009              [Page 17]
Internet-Draft              HTTP/1.1, Part 6                  March 2009
     Cache-Control   = "Cache-Control" ":" OWS Cache-Control-v
     Cache-Control-v = 1#cache-directive
     cache-directive = cache-request-directive
        / cache-response-directive
     cache-extension = token [ "=" ( token / quoted-string ) ]
3.2.1.  Request Cache-Control Directives
     cache-request-directive =
          "no-cache"
        / "no-store"
        / "max-age" "=" delta-seconds
        / "max-stale" [ "=" delta-seconds ]
        / "min-fresh" "=" delta-seconds
        / "no-transform"
        / "only-if-cached"
        / cache-extension
   no-cache
      The no-cache request directive indicates that a stored response
      MUST NOT be used to satisfy the request without successful
      validation on the origin server.
   no-store
      The no-store request directive indicates that a cache MUST NOT
      store any part of either this request or any response to it.  This
      directive applies to both non-shared and shared caches.  "MUST NOT
      store" in this context means that the cache MUST NOT intentionally
      store the information in non-volatile storage, and MUST make a
      best-effort attempt to remove the information from volatile
      storage as promptly as possible after forwarding it.
      This directive is NOT a reliable or sufficient mechanism for
      ensuring privacy.  In particular, malicious or compromised caches
      might not recognize or obey this directive, and communications
      networks may be vulnerable to eavesdropping.
   max-age
      The max-age request directive indicates that the client is willing
      to accept a response whose age is no greater than the specified
      time in seconds.  Unless max-stale directive is also included, the
      client is not willing to accept a stale response.
Fielding, et al.       Expires September 10, 2009              [Page 18]
Internet-Draft              HTTP/1.1, Part 6                  March 2009
   max-stale
      The max-stale request directive indicates that the client is
      willing to accept a response that has exceeded its expiration
      time.  If max-stale is assigned a value, then the client is
      willing to accept a response that has exceeded its expiration time
      by no more than the specified number of seconds.  If no value is
      assigned to max-stale, then the client is willing to accept a
      stale response of any age. [[anchor15: of any staleness? --mnot]]
   min-fresh
      The min-fresh request directive indicates that the client is
      willing to accept a response whose freshness lifetime is no less
      than its current age plus the specified time in seconds.  That is,
      the client wants a response that will still be fresh for at least
      the specified number of seconds.
   no-transform
      The no-transform request directive indicates that an intermediate
      cache or proxy MUST NOT change the Content-Encoding, Content-Range
      or Content-Type request headers, nor the request entity-body.
   only-if-cached
      The only-if-cached request directive indicates that the client
      only wishes to return a stored response.  If it receives this
      directive, a cache SHOULD either respond using a stored response
      that is consistent with the other constraints of the request, or
      respond with a 504 (Gateway Timeout) status.  If a group of caches
      is being operated as a unified system with good internal
      connectivity, such a request MAY be forwarded within that group of
      caches.
Fielding, et al.       Expires September 10, 2009              [Page 19]
Internet-Draft              HTTP/1.1, Part 6                  March 2009
3.2.2.  Response Cache-Control Directives
     cache-response-directive =
          "public"
        / "private" [ "=" DQUOTE 1#field-name DQUOTE ]
        / "no-cache" [ "=" DQUOTE 1#field-name DQUOTE ]
        / "no-store"
        / "no-transform"
        / "must-revalidate"
        / "proxy-revalidate"
        / "max-age" "=" delta-seconds
        / "s-maxage" "=" delta-seconds
        / cache-extension
   public
      The public response directive indicates that the response MAY be
      cached, even if it would normally be non-cacheable or cacheable
      only within a non-shared cache.  (See also Authorization, Section
      3.1 of [Part7], for additional details.)
   private
      The private response directive indicates that the response message
      is intended for a single user and MUST NOT be stored by a shared
      cache.  A private (non-shared) cache MAY store the response.
      If the private response directive specifies one or more field-
      names, this requirement is limited to the field-values associated
      with the listed response headers.  That is, the specified field-
      names(s) MUST NOT be stored by a shared cache, whereas the
      remainder of the response message MAY be.
      Note: This usage of the word private only controls where the
      response may be stored, and cannot ensure the privacy of the
      message content.
   no-cache
      The no-cache response directive indicates that the response MUST
      NOT be used to satisfy a subsequent request without successful
      validation on the origin server.  This allows an origin server to
      prevent caching even by caches that have been configured to return
      stale responses.
      If the no-cache response directive specifies one or more field-
      names, this requirement is limited to the field-values assosicated
      with the listed response headers.  That is, the specified field-
Fielding, et al.       Expires September 10, 2009              [Page 20]
Internet-Draft              HTTP/1.1, Part 6                  March 2009
      name(s) MUST NOT be sent in the response to a subsequent request
      without successful validation on the origin server.  This allows
      an origin server to prevent the re-use of certain header fields in
      a response, while still allowing caching of the rest of the
      response.
      Note: Most HTTP/1.0 caches will not recognize or obey this
      directive.
   no-store
      The no-store response directive indicates that a cache MUST NOT
      store any part of either the immediate request or response.  This
      directive applies to both non-shared and shared caches.  "MUST NOT
      store" in this context means that the cache MUST NOT intentionally
      store the information in non-volatile storage, and MUST make a
      best-effort attempt to remove the information from volatile
      storage as promptly as possible after forwarding it.
      This directive is NOT a reliable or sufficient mechanism for
      ensuring privacy.  In particular, malicious or compromised caches
      might not recognize or obey this directive, and communications
      networks may be vulnerable to eavesdropping.
   must-revalidate
      The must-revalidate response directive indicates that once it has
      become stale, the response MUST NOT be used to satisfy subsequent
      requests without successful validation on the origin server.
      The must-revalidate directive is necessary to support reliable
      operation for certain protocol features.  In all circumstances an
      HTTP/1.1 cache MUST obey the must-revalidate directive; in
      particular, if the cache cannot reach the origin server for any
      reason, it MUST generate a 504 (Gateway Timeout) response.
      Servers SHOULD send the must-revalidate directive if and only if
      failure to validate a request on the entity could result in
      incorrect operation, such as a silently unexecuted financial
      transaction.
   proxy-revalidate
      The proxy-revalidate response directive has the same meaning as
      the must-revalidate response directive, except that it does not
      apply to non-shared caches.
   max-age
Fielding, et al.       Expires September 10, 2009              [Page 21]
Internet-Draft              HTTP/1.1, Part 6                  March 2009
      The max-age response directive indicates that response is to be
      considered stale after its age is greater than the specified
      number of seconds.
   s-maxage
      The s-maxage response directive indicates that, in shared caches,
      the maximum age specified by this directive overrides the maximum
      age specified by either the max-age directive or the Expires
      header.  The s-maxage directive also implies the semantics of the
      proxy-revalidate response directive.
   no-transform
      The no-transform response directive indicates that an intermediate
      cache or proxy MUST NOT change the Content-Encoding, Content-Range
      or Content-Type response headers, nor the response entity-body.
3.2.3.  Cache Control Extensions
   The Cache-Control header field can be extended through the use of one
   or more cache-extension tokens, each with an optional value.
   Informational extensions (those that do not require a change in cache
   behavior) can be added without changing the semantics of other
   directives.  Behavioral extensions are designed to work by acting as
   modifiers to the existing base of cache directives.  Both the new
   directive and the standard directive are supplied, such that
   applications that do not understand the new directive will default to
   the behavior specified by the standard directive, and those that
   understand the new directive will recognize it as modifying the
   requirements associated with the standard directive.  In this way,
   extensions to the cache-control directives can be made without
   requiring changes to the base protocol.
   This extension mechanism depends on an HTTP cache obeying all of the
   cache-control directives defined for its native HTTP-version, obeying
   certain extensions, and ignoring all directives that it does not
   understand.
   For example, consider a hypothetical new response directive called
   "community" that acts as a modifier to the private directive.  We
   define this new directive to mean that, in addition to any non-shared
   cache, any cache that is shared only by members of the community
   named within its value may cache the response.  An origin server
   wishing to allow the UCI community to use an otherwise private
   response in their shared cache(s) could do so by including
     Cache-Control: private, community="UCI"
Fielding, et al.       Expires September 10, 2009              [Page 22]
Internet-Draft              HTTP/1.1, Part 6                  March 2009
   A cache seeing this header field will act correctly even if the cache
   does not understand the community cache-extension, since it will also
   see and understand the private directive and thus default to the safe
   behavior.
   Unrecognized cache directives MUST be ignored; it is assumed that any
   cache directive likely to be unrecognized by an HTTP/1.1 cache will
   be combined with standard directives (or the response's default
   cacheability) such that the cache behavior will remain minimally
   correct even if the cache does not understand the extension(s).
3.3.  Expires
   The entity-header field "Expires" gives the date/time after which the
   response is considered stale.  See Section 2.3 for further discussion
   of the freshness model.
   The presence of an Expires field does not imply that the original
   resource will change or cease to exist at, before, or after that
   time.
   The field-value is an absolute date and time as defined by HTTP-date
   in Section 3.2.1 of [Part1]; it MUST be sent in rfc1123-date format.
     Expires   = "Expires" ":" OWS Expires-v
     Expires-v = HTTP-date
   For example
     Expires: Thu, 01 Dec 1994 16:00:00 GMT
      Note: if a response includes a Cache-Control field with the max-
      age directive (see Section 3.2.2), that directive overrides the
      Expires field.  Likewise, the s-maxage directive overrides Expires
      in shared caches.
   HTTP/1.1 servers SHOULD NOT send Expires dates more than one year in
   the future.
   HTTP/1.1 clients and caches MUST treat other invalid date formats,
   especially including the value "0", as in the past (i.e., "already
   expired").
 
http://www.ietf.org/internet-drafts/draft-ietf-httpbis-p6-cache-06.txt

 

基于资源的HTTP Cache的实现介绍

http://www.iteye.com/topic/462476

我们都知道浏览器会缓存访问过网站的网页,浏览器通过URL地址访问一个网页,显示网页内容的同时会在电脑上面缓存网页内容。如果网页没有更新的话,浏览 器再次访问这个URL地址的时候,就不会再次下载网页,而是直接使用本地缓存的网页。只有当网站明确标识资源已经更新,浏览器才会再次下载网页。



一、什么是HTTP Cache

对于浏览器的这种网页缓存机制大家已经耳熟能详了,举个例子来说,JavaEye的新闻订阅地址:http://www.iteye.com /rss/news , 当浏览器或者订阅程序访问这个URL地址的时候,JavaEye的服务器在response的header里面会发送给浏览器如下状态标识:

C代码 <embed type="application/x-shockwave-flash" width="14" height="15" src="http://www.iteye.com/javascripts/syntaxhighlighter/clipboard_new.swf" flashvars="clipboard=Etag%09%22427fe7b6442f2096dff4f92339305444%22%0ALast-Modified%09Fri%2C%2004%20Sep%202009%2005%3A55%3A43%20GMT" quality="high" allowscriptaccess="always" pluginspage="http://www.macromedia.com/go/getflashplayer"></embed>
  1. Etag     "427fe7b6442f2096dff4f92339305444"   
  2. Last-Modified   Fri, 04 Sep 2009 05:55:43 GMT  
Etag	"427fe7b6442f2096dff4f92339305444"
Last-Modified	Fri, 04 Sep 2009 05:55:43 GMT



这就是告诉浏览器,新闻订阅这个网络资源的最后修改时间和Etag。于是浏览器把这两个状态信息连同网页内容在本地进行缓存,当浏览器再次访问JavaEye新闻订阅地址的时候,浏览器会发送如下两个状态标识给JavaEye服务器:

C代码 <embed type="application/x-shockwave-flash" width="14" height="15" src="http://www.iteye.com/javascripts/syntaxhighlighter/clipboard_new.swf" flashvars="clipboard=If-None-Match%09%22427fe7b6442f2096dff4f92339305444%22%0AIf-Modified-Since%09Fri%2C%2004%20Sep%202009%2005%3A55%3A43%20GMT" quality="high" allowscriptaccess="always" pluginspage="http://www.macromedia.com/go/getflashplayer"></embed>
  1. If-None-Match    "427fe7b6442f2096dff4f92339305444"   
  2. If-Modified-Since   Fri, 04 Sep 2009 05:55:43 GMT  
If-None-Match	"427fe7b6442f2096dff4f92339305444"
If-Modified-Since	Fri, 04 Sep 2009 05:55:43 GMT



就是告诉服务器,我本地缓存的网页最后修改时间和Etag是什么,请问你服务器的资源有没有在我上次访问之后有更新啊?于是JavaEye服务器 会核对一下,如果该用户上次访问之后没有更新过新闻,那么根本就不必生成这个RSS了,直接告诉浏览器:“没什么新东西,你还是看自己缓存的网页吧”,于 是服务器就发送一个304 Not Modified的消息,其他什么都不用干了。

这就是HTTP层的Cache,使用这种基于资源的缓存机制,不但大大节省服务器程序资源,而且还减少了网页下载次数,节约了很多网络带宽。

二、HTTP Cache究竟有什么作用?

我们通常的动态网站编程,服务器端程序根本就不去处理浏览器发送过来的If-None-Match和If-Modified-Since状态标 识,只要有请求就生成网页发送给浏览器。对于一般情况来说,用户不会总是没完没了刷新一个页面,所以大家并不认为这种基于资源的缓存有什么太大的作用,但 实际情况并非如此:

1、像Google这种比较智能的网络爬虫可以有效识别资源的状态信息,如果使用这种缓存机制,可以大大减少爬虫的爬取次数。

比方说Google每天爬JavaEye网站大概15万次左右,但实际上JavaEye每天有更新的内容不会超过1万个网页。因为很多内容更新比 较快,因此Google就会反复不停的爬取,这样本身就造成了很多资源的浪费。如果我们使用HTTP Cache,那么只有当网页内容发生改变的时候,才会真正进行爬取,其他时候我们直接告诉Google的爬虫304 Not Modified就可以了。这样不但降低了服务器本身的负载和爬虫造成的网络带宽消耗,实际上也大大提高了Google爬虫的工作效率,岂不是皆大欢喜?

2、很多内容更新不频繁的网页,尽管用户不会频繁的刷新,但是从一个比较长的时间段来看使用HTTP Cache,仍然可以起到很大的缓存作用。

比方说一些历史讨论帖子,已经过去了几个月了,这些帖子内容很少更新。用户可能通过搜索,收藏链接,文章关联等方式时不时访问到这个页面。那么只要用户访问过一次以后,后续所有访问服务器直接发送304 Not Modified就可以了,不用真正生成页面。

3、对于历史帖子使用HTTP Cache可以避免爬虫反复的爬取。

比方说JavaEye的论坛帖子列表页面,分页到20页后面的帖子已经很少有人直接访问了,但是从服务器日志去看,每天仍然有大量爬虫反复爬取这 些分页到很后面的页面。这些页面由于用户很少去点击,所以基本上没有被应用程序的memcached缓存住,每次访问都会造成很高的资源消耗,爬虫隔一段 时间就爬一次,对服务器是很大的负担。如果使用了HTTP Cache,那么只要爬虫爬过一次以后,以后无论爬虫爬多少次,都可以直接返回304 Not Modified了,极大的节省了服务器的负载。

三、如何在应用程序里面使用HTTP Cache

如果我们要在自己的程序里面实现HTTP Cache,是件非常简单的事情,特别是对Rails来说只需要添加一点点代码,以上面的JavaEye新闻订阅来说,只要添加一行代码:

Ruby代码 <embed type="application/x-shockwave-flash" width="14" height="15" src="http://www.iteye.com/javascripts/syntaxhighlighter/clipboard_new.swf" flashvars="clipboard=def%20news%0A%20%20fresh_when(%3Alast_modified%20%3D%3E%20News.last.created_at%2C%20%3Aetag%20%3D%3E%20News.last)%0Aend" quality="high" allowscriptaccess="always" pluginspage="http://www.macromedia.com/go/getflashplayer"></embed>
  1. def  news  
  2.   fresh_when(:last_modified  => News.last.created_at,  :etag  => News.last)  
  3. end   
def news
  fresh_when(:last_modified => News.last.created_at, :etag => News.last)
end



用最新新闻文章作为Etag,该文章最后修改时间作为资源的最后修改时间,这样就OK了。如果浏览器发送过来的标识和服务器标识一致,说明内容没 有更新,直接发送304 Not Modified;如果不一致,说明内容更新,浏览器本地的缓存太古老了,那么就需要服务器真正生成页面了。

以上只是一个最简单的例子,如果我们需要根据状态做一些更多的工作也是很容易的。比方说JavaEye博客的RSS订阅地址: http://robbin.iteye.com/rss

Ruby代码 <embed type="application/x-shockwave-flash" width="14" height="15" src="http://www.iteye.com/javascripts/syntaxhighlighter/clipboard_new.swf" flashvars="clipboard=%40blogs%20%3D%20%40blog_owner.last_blogs%0A%40hash%20%3D%20%40blogs.collect%7B%7Cb%7C%20%7Bb.id%20%3D%3E%20b.post.modified_at.to_i%20%2B%20b.posts_count%7D%7D.hash%0Aif%20stale%3F(%3Alast_modified%20%3D%3E%20(%40blog_owner.last_blog.post.modified_at%20%7C%7C%20%40blog_owner.last_blog.post.created_at)%2C%20%3Aetag%20%3D%3E%20%40hash)%0A%20%20render%20%3Atemplate%20%3D%3E%20%22rss%2Fblog%22%0Aend" quality="high" allowscriptaccess="always" pluginspage="http://www.macromedia.com/go/getflashplayer"></embed>
  1. @blogs  =  @blog_owner .last_blogs  
  2. @hash  =  @blogs .collect{|b| {b.id => b.post.modified_at.to_i + b.posts_count}}.hash  
  3. if  stale?( :last_modified  => ( @blog_owner .last_blog.post.modified_at ||  @blog_owner .last_blog.post.created_at),  :etag  =>  @hash )  
  4.   render :template  =>  "rss/blog"   
  5. end   
@blogs = @blog_owner.last_blogs
@hash = @blogs.collect{|b| {b.id => b.post.modified_at.to_i + b.posts_count}}.hash
if stale?(:last_modified => (@blog_owner.last_blog.post.modified_at || @blog_owner.last_blog.post.created_at), :etag => @hash)
  render :template => "rss/blog"
end



这个实现稍微复杂一些。我们需要判断博客订阅所有的输出文章是否有更新,所以我们用博客文章内容最后修改时间和博客的评论数量做一个hash,然 后用这个hash值作为资源的Etag,那么只要这些博客文章当中任何文章内容被修改,或者有新评论,都会改变Etag值,从而通知浏览器内容有更新了。

除了RSS订阅之外,JavaEye网站还有很多地方适合使用HTTP Cache,比方说JavaEye论坛的版面列表页面,一些经常喜欢泡论坛的用户,可能时不时会上来刷新一下版面, 看看有没有新的帖子,那么我们就不必每次用户请求的时候都去执行程序,生成页面给他。我们判断一下如果没有新帖子的话,直接告诉他304 Not Modified就可以了,在没有使用HTTP Cache之前的版面Action代码:

Ruby代码 <embed type="application/x-shockwave-flash" width="14" height="15" src="http://www.iteye.com/javascripts/syntaxhighlighter/clipboard_new.swf" flashvars="clipboard=def%20board%0A%20%20%40topics%20%3D%20%40forum.topics.paginate...%0A%20%20%40announcements%20%3D%20(params%5B%3Apage%5D%20%7C%7C%201).to_i%20%3D%3D%201%20%3F%20Topic.find%20%3Aall%2C%20%3Aconditions%20%3D%3E%20...%0A%20%20render%20%3Aaction%20%3D%3E%20'show'%0Aend" quality="high" allowscriptaccess="always" pluginspage="http://www.macromedia.com/go/getflashplayer"></embed>
  1. def  board  
  2.   @topics  =  @forum .topics.paginate...  
  3.   @announcements  = (params[ :page ] || 1).to_i == 1 ? Topic.find  :all :conditions  => ...  
  4.   render :action  =>  'show'   
  5. end   
def board
  @topics = @forum.topics.paginate...
  @announcements = (params[:page] || 1).to_i == 1 ? Topic.find :all, :conditions => ...
  render :action => 'show'
end



添加HTTP Cache以后,代码如下:

Ruby代码 <embed type="application/x-shockwave-flash" width="14" height="15" src="http://www.iteye.com/javascripts/syntaxhighlighter/clipboard_new.swf" flashvars="clipboard=def%20board%0A%20%20%40topics%20%3D%20%40forum.topics.paginate...%0A%20%20if%20logged_in%3F%20%7C%7C%20stale%3F(%3Alast_modified%20%3D%3E%20%40topics%5B0%5D.last_post.created_at%2C%20%3Aetag%20%3D%3E%20%40topics.collect%7B%7Ct%7C%20%7Bt.id%20%3D%3E%20t.posts_count%7D%7D.hash)%0A%20%20%20%20%40announcements%20%3D%20(params%5B%3Apage%5D%20%7C%7C%201).to_i%20%3D%3D%201%20%3F%20Topic.find%20%3Aall%2C%20%3Aconditions...%0A%20%20%20%20render%20%3Aaction%20%3D%3E%20'show'%0A%20%20end%0Aend" quality="high" allowscriptaccess="always" pluginspage="http://www.macromedia.com/go/getflashplayer"></embed>
  1. def  board  
  2.   @topics  =  @forum .topics.paginate...  
  3.   if  logged_in? || stale?( :last_modified  =>  @topics [0].last_post.created_at,  :etag  =>  @topics .collect{|t| {t.id => t.posts_count}}.hash)  
  4.     @announcements  = (params[ :page ] || 1).to_i == 1 ? Topic.find  :all :conditions ...  
  5.     render :action  =>  'show'   
  6.   end   
  7. end   
def board
  @topics = @forum.topics.paginate...
  if logged_in? || stale?(:last_modified => @topics[0].last_post.created_at, :etag => @topics.collect{|t| {t.id => t.posts_count}}.hash)
    @announcements = (params[:page] || 1).to_i == 1 ? Topic.find :all, :conditions...
    render :action => 'show'
  end
end



对于登录用户,不使用HTTP Cache,这是因为登录用户需要实时接收站内短信通知和订阅通知,因此我们只能对匿名用户使用HTTP Cache,然后我们使用当前所有帖子id和回帖数构造hash作Etag,这样只要当前分页列表页面有任何帖子发生改变或者有了新回帖,就更新页面,否 则就不必重新生成页面。

论坛帖子页面实际上也可以使用HTTP Cache,只不过Etag的hash算法稍微复杂一些,需要保证帖子的任何改动都要引起hash值的改变,示例代码如下:

Ruby代码 <embed type="application/x-shockwave-flash" width="14" height="15" src="http://www.iteye.com/javascripts/syntaxhighlighter/clipboard_new.swf" flashvars="clipboard=def%20show%0A%20%20%40topic%20%3D%20Topic.find%20params%5B%3Aid%5D%0A%20%20user_session.update_.......%20%20if%20logged_in%3F%0A%20%20Topic.increment_counter(...)%20if%20......%0A%20%20%40posts%20%3D%20%40topic.post_by_page%20params%5B%3Apage%5D%0A%20%20posts_hash%20%3D%20%40posts.collect%7B%7Cp%7C%20%7Bp.id%20%3D%3E%20p.modified_at%7D%7D.hash%0A%20%20topic_hash%20%3D%20%40topic.forum_id%20%2B%20%40topic.sys_tag_id.to_i%20%2B%20%40topic.title.hash%20%2B%20%40topic.status_flag.hash%0A%20%20ad_hash%20%3D%20...%20%20(%E5%B9%BF%E5%91%8A%E7%9A%84hash%E7%AE%97%E6%B3%95%EF%BC%8C%E7%95%A5)%0A%20%20if%20logged_in%3F%20%7C%7C%20stale%3F(%3Aetag%20%3D%3E%20%5Bposts_hash%2C%20topic_hash%2C%20ad_hash%5D)%0A%20%20%20%20render%0A%20%20end%20%20%0Aend%0A" quality="high" allowscriptaccess="always" pluginspage="http://www.macromedia.com/go/getflashplayer"></embed>
  1. def  show  
  2.   @topic  = Topic.find params[ :id ]  
  3.   user_session.update_.......  if  logged_in?  
  4.   Topic.increment_counter(...) if  ......  
  5.   @posts  =  @topic .post_by_page params[ :page ]  
  6.   posts_hash = @posts .collect{|p| {p.id => p.modified_at}}.hash  
  7.   topic_hash = @topic .forum_id +  @topic .sys_tag_id.to_i +  @topic .title.hash +  @topic .status_flag.hash  
  8.   ad_hash = ...  (广告的hash算法,略)  
  9.   if  logged_in? || stale?( :etag  => [posts_hash, topic_hash, ad_hash])  
  10.     render  
  11.   end     
  12. end   
def show
  @topic = Topic.find params[:id]
  user_session.update_.......  if logged_in?
  Topic.increment_counter(...) if ......
  @posts = @topic.post_by_page params[:page]
  posts_hash = @posts.collect{|p| {p.id => p.modified_at}}.hash
  topic_hash = @topic.forum_id + @topic.sys_tag_id.to_i + @topic.title.hash + @topic.status_flag.hash
  ad_hash = ...  (广告的hash算法,略)
  if logged_in? || stale?(:etag => [posts_hash, topic_hash, ad_hash])
    render
  end  
end



要分别根据主题贴,该分页的所有回帖和帖子页面的广告内容进行hash,计算出来一个唯一的Etag值,保证任何改动都会生成新的Etag,这样 就搞定了,是不是很简单!这种帖子的缓存非常有效,可以避免Rails去render页面和下载页面,极大的减轻了服务器负载和带宽。

再举一个需求比较特殊的例子:对于知识库搜索相关文章的推荐页面,比方说:http://www.iteye.com/wiki/topic /462476,也就是本文的相关文章推荐内容,我们并不希望用户和爬虫每次访问这个页面都实际执行一遍全文检索,然后构造页面内容,在一个相对不长的时 间范围内,这篇文章的相关推荐文章改变的概率不大,因此我们希望比方说5天之内,用户重复访问该页面,就直接返回304 Not Modified,那么Rails没有直接的设施给我们使用,需要我们稍微了解一些Rails的机制,自己编写,代码示例如下:

Ruby代码 <embed type="application/x-shockwave-flash" width="14" height="15" src="http://www.iteye.com/javascripts/syntaxhighlighter/clipboard_new.swf" flashvars="clipboard=def%20topic%0A%20%20%40topic%20%3D%20Topic.find(params%5B%3Aid%5D)%0A%20%20unless%20logged_in%3F%0A%20%20%20%20if%20request.not_modified%3F(5.days.ago)%0A%20%20%20%20%20%20head%20%3Anot_modified%0A%20%20%20%20else%0A%20%20%20%20%20%20response.last_modified%20%3D%20Time.now%0A%20%20%20%20end%0A%20%20end%0Aend" quality="high" allowscriptaccess="always" pluginspage="http://www.macromedia.com/go/getflashplayer"></embed>
  1. def  topic  
  2.   @topic  = Topic.find(params[ :id ])  
  3.   unless  logged_in?  
  4.     if  request.not_modified?(5.days.ago)  
  5.       head :not_modified   
  6.     else   
  7.       response.last_modified = Time .now  
  8.     end   
  9.   end   
  10. end   
def topic
  @topic = Topic.find(params[:id])
  unless logged_in?
    if request.not_modified?(5.days.ago)
      head :not_modified
    else
      response.last_modified = Time.now
    end
  end
end



每次用户请求,我们判断用户是否5天之内访问过该页面,如果访问过,直接返回304 Not Modified,如果没有访问过,或者上次访问已经超过了5天,那么设置最近修改时间为当前时间,然后生成页面给用户。是不是很简单?

在给JavaEye网站所有的RSS订阅输出添加了HTTP Cache以后,通过一天的观察发现,超过一半的RSS订阅请求已经被缓存了,直接返回304 Not Modified,所以效果非常明显,由于JavaEye网站每天RSS订阅的动态请求就超过了10万次,因此添加HTTP Cache可以减轻不少服务器的负担和带宽消耗。除此之外,新闻文章页面,整个论坛频道,知识库相关推荐文章页面都可以添加HTTP Cache,粗粗计算下来,JavaEye这些页面统统使用HTTP Cache以后,网站整体性能至少可以提高10%。

 

浏览器并发连接数

http://blog.csdn.net/phphot/article/details/3210221

作者:老王

这是个老话题了,先总结一下HTTP1.1下主流浏览器在单个主机下的并发连接数:

IE7      2
IE8      6
Firefox2 2
Firefox3 6


看上去巧合的是:老版本的IE和Firefox都使用较低的单个主机并发连接数(2),而新版本的IE和Firefox都使用较高的单个主机并发连接数(6)。说起来老版本的IE和Firefox之所以采用较低的单个主机并发连接数是有道理的,在RFC2616 里明确要求了单个主机并发连接数的数目:

Clients that use persistent connections SHOULD limit the number of simultaneous connections that they maintain to a given server. A single-user client SHOULD NOT maintain more than 2 connections with any server or proxy. A proxy SHOULD use up to 2*N connections to another server or proxy, where N is the number of simultaneously active users. These guidelines are intended to improve HTTP response times and avoid congestion.

不过标准总会落后于现实。在当今的网络环境里再使用较低的单个主机并发连接数已经越来越显得不合时宜了,所以说新版本的IE和Firefox才会不约而同的采用较高的单个主机并发连接数。

不 过很多时候我们为了效率还想得到更高的并发连接数,比如说我们总会看到一些大网站采用独立域名或者二级域名来设置专门的图片服务器,其实有一部分原因就是 为了增加并发连接数。至于使用独立域名还是二级域名的差别在于Cookie的影响,当使用和主站根域名相同的二级域名时,请求的同时也会捎带着传递主站根 域名的Cookie,而使用和主站根域名不同的独立域名时,则不会受主站根域名Cookie的影响,所以带宽占用会更小一些。

不过也不是说并发连接数越大越好,假如新版浏览器得到普及,即使你的网站的平均流量还维持在和以前一样的水平,那么峰值流量也会成倍增加。

顺便说说Firefox下怎么调整单个主机下的并发数:

# about:config
network.http.max-connections                      : 30
network.http.max-connections-per-server           : 15
network.http.max-persistent-connections-per-proxy : 8
network.http.max-persistent-connections-per-server: 6


需 要说明的是HTTP1.1下以network.http.max-persistent-connections-per-server的指为准,这是因 为HTTP1.1下缺省都是持久连接,反之如果是HTTP1.0,则以network.http.max-connections-per-server 为准。

如果你使用TamperData检测一下,就能发现:

HTTP1.1下Connection: Keep-Alive
HTTP1.0下Connection: Close

参考链接:Roundup on Parallel Connections

 

 

HTTP Status list / http 状态码列表 / HTTP状态码对照详解

http://baike.baidu.com/view/1790469.htm

1xx 消息
2xx 成功
3xx 重定向
4xx 请求错误
5xx 服务器错误

HTTP状态码(HTTP Status Code)是用以表示网页服务器HTTP响应状态的3位数字代码。它由 RFC 2616 规范定义的,并得到RFC 2518、RFC 2817、RFC 2295、RFC 2774、RFC 4918等规范扩展。

 

http://www.baidu.com/s?tn=monline_5_dg&ie=utf-8&bs=HTTP+Status+408&f=3&rsv_bp=1&wd=http%E7%8A%B6%E6%80%81%E7%A0%81&rsv_sug3=15&rsv_sug4=12630&rsv_sug1=6&oq=http+%E7%8A%B6%E6%80%81&rsp=0&rsv_sug2=0&inputT=10079

状态码 描述
100 Continue
初始的请求已经接受,客户应当继续发送请求的其余部分
101 Switching Protocols
服务器将遵从客户的请求转换到另外一种协议
200 OK
指示请求成功,且请求的信息包含在响应中。这是最常接收的状态代码
201 Created
指示请求导致在响应被发送前创建新资源
202 Accepted
指示请求已被接受做进一步处理
203 Non-Authoritative Information
指示返回的元信息来自缓存副本而不是原始服务器,因此可能不正确
204 No Content
指示已成功处理请求并且响应已被设定为无内容
205 Reset Content
指示客户端应重置(或重新加载)当前资源
206 Partial Content
指示响应是包括字节范围的 GET 请求所请求的部分响应
207 Multi-Status
226 IM Used
300 Multiple Choices
指示请求的信息有多种表示形式。 默认操作是将此状态视为重定向,并遵循与此响应关联的 Location 头的内容
301 Moved Permanently
指示请求的信息已移到 Location 头中指定的 URI 处。 接收到此状态时的默认操作为遵循与响应关联的 Location 头。 原始请求方法为 POST 时,重定向的请求将使用 GET 方法
302 Found
指示请求的信息位于 Location 头中指定的 URI 处。 接收到此状态时的默认操作为遵循与响应关联的 Location 头。 原始请求方法为 POST 时,重定向的请求将使用 GET 方法
303 See Other
类似于301/302,不同之处在于,如果原来的请求是POST,Location头指定的重定向目标文档应该通过GET提取
304 Not Modified
客户端有缓冲的文档并发出了一个条件性的请求(一般是提供If-Modified-Since头表示客户只想比指定日期更新的文档)。服务器告诉客户,原来缓冲的文档还可以继续使用
305 Use Proxy
客户请求的文档应该通过Location头所指明的代理服务器提取
306 Unused
是未完全指定的 HTTP/1.1 规范的建议扩展
307 Temporary Redirect
和 302(Found)相同。许多浏览器会错误地响应302应答进行重定向,即使原来的请求是POST,即使它实际上只能在POST请求的应答是303时 才能重定向。由于这个原因,HTTP 1.1新增了307,以便更加清除地区分几个状态代码:当出现303应答时,浏览器可以跟随重定向的GET和POST请求;如果是307应答,则浏览器只 能跟随对GET请求的重定向
400 Bad Request
请求出现语法错误
401 Unauthorized
访问被拒绝,客户试图未经授权访问受密码保护的页面。应答中会包含一个WWW-Authenticate头,浏览器据此显示用户名字/密码对话框,然后在 填写合适的Authorization头后再次发出请求。IIS 定义了许多不同的 401 错误,它们指明更为具体的错误原因。这些具体的错误代码在浏览器中显示,但不在 IIS 日志中显示:
401.1 - 登录失败。
401.2 - 服务器配置导致登录失败。
401.3 - 由于 ACL 对资源的限制而未获得授权。
401.4 - 筛选器授权失败。
401.5 - ISAPI/CGI 应用程序授权失败。
401.7 – 访问被 Web 服务器上的 URL 授权策略拒绝。这个错误代码为 IIS 6.0 所专用。
402 Payment Required
保留 PaymentRequired 以供将来使用
403 Forbidden
资源不可用。服务器理解客户的请求,但拒绝处理它。通常由于服务器上文件或目录的权限设置导致。禁止访问:IIS 定义了许多不同的 403 错误,它们指明更为具体的错误原因:
403.1 - 执行访问被禁止。
403.2 - 读访问被禁止。
403.3 - 写访问被禁止。
403.4 - 要求 SSL。
403.5 - 要求 SSL 128。
403.6 - IP 地址被拒绝。
403.7 - 要求客户端证书。
403.8 - 站点访问被拒绝。
403.9 - 用户数过多。
403.10 - 配置无效。
403.11 - 密码更改。
403.12 - 拒绝访问映射表。
403.13 - 客户端证书被吊销。
403.14 - 拒绝目录列表。
403.15 - 超出客户端访问许可。
403.16 - 客户端证书不受信任或无效。
403.17 - 客户端证书已过期或尚未生效。
403.18 - 在当前的应用程序池中不能执行所请求的 URL。这个错误代码为 IIS 6.0 所专用。
403.19 - 不能为这个应用程序池中的客户端执行 CGI。这个错误代码为 IIS 6.0 所专用。
403.20 - Passport 登录失败。这个错误代码为 IIS 6.0 所专用。
404 Not Found
无法找到指定位置的资源。这也是一个常用的应答。 · 404.0 -(无) – 没有找到文件或目录。 · 404.1 - 无法在所请求的端口上访问 Web 站点。 · 404.2 - Web 服务扩展锁定策略阻止本请求。 · 404.3 - MIME 映射策略阻止本请求。
405 Method Not Allowed
请求方法(GET、POST、HEAD、DELETE、PUT、TRACE等)对指定的资源不适用,用来访问本页面的 HTTP 谓词不被允许(方法不被允许)
406 Not Acceptable
指定的资源已经找到,但它的MIME类型和客户在Accpet头中所指定的不兼容,客户端浏览器不接受所请求页面的 MIME 类型
407 Proxy Authentication Required
要求进行代理身份验证,类似于401,表示客户必须先经过代理服务器的授权
408 Request Time-out
在服务器许可的等待时间内,客户一直没有发出任何请求。客户可以在以后重复同一请求
409 Conflict
通常和PUT请求有关。由于请求和资源的当前状态相冲突,因此请求不能成功
410 Gone
所请求的文档已经不再可用,而且服务器不知道应该重定向到哪一个地址。它和404的不同在于,返回407表示文档永久地离开了指定的位置,而404表示由于未知的原因文档不可用
411 Length Required
服务器不能处理请求,除非客户发送一个Content-Length头
412 Precondition Failed
请求头中指定的一些前提条件失败
413 Request Entity Too Large
目标文档的大小超过服务器当前愿意处理的大小。如果服务器认为自己能够稍后再处理该请求,则应该提供一个Retry-After头
414 Request-URI Too Large
指示 URI 太长
415 Unsupported Media Type
不支持的媒体类型
416 Requested range not satisfiable
服务器不能满足客户在请求中指定的Range头
417 Expectation Failed
执行失败
423 Locked
锁定的错误
424 Failed Dependency
425 Unordered Collection
426 Upgrade Required
500 Internal Server Error
服务器遇到了意料不到的情况,不能完成客户的请求:
500.12 - 应用程序正忙于在 Web 服务器上重新启动。
500.13 - Web 服务器太忙。
500.15 - 不允许直接请求 Global.asa。
500.16 – UNC 授权凭据不正确。这个错误代码为 IIS 6.0 所专用。
500.18 – URL 授权存储不能打开。这个错误代码为 IIS 6.0 所专用。
500.100 - 内部 ASP 错误。
501 Not Implemented
服务器不支持实现请求所需要的功能,页眉值指定了未实现的配置。例如,客户发出了一个服务器不支持的PUT请求
502 Bad Gateway
服务器作为网关或者代理时,为了完成请求访问下一个服务器,但该服务器返回了非法的应答。 亦说Web 服务器用作网关或代理服务器时收到了无效响应 · 502.1 - CGI 应用程序超时。 · 502.2 - CGI 应用程序出错。
503 Service Unavailable
服务不可用,服务器由于维护或者负载过重未能应答。例如,Servlet可能在数据库连接池已满的情况下返回503。服务器返回503时可以提供一个 Retry-After头。这个错误代码为 IIS 6.0 所专用
504 Gateway Time-out
网关超时,由作为代理或网关的服务器使用,表示不能及时地从远程服务器获得应答
505 HTTP Version not supported
服务器不支持请求中所指明的HTTP版本
506 Variant Also Negotiates
507 Insufficient Storage
516 Not Extended

 

http://www.cnblogs.com/DeasonGuan/articles/Hanami.html

HTTP Status Code

常见的状态码:

HTTP: Status

 200

 – 服务器成功返回网页
HTTP: Status

 404

 – 请求的网页不存在
HTTP: Status

 503

 – 服务不可用

详解:

复制代码
说明:

HTTP: Status 1xx

  (临时响应)
->表示临时响应并需要请求者继续执行操作的状态代码。

详细代码及说明:
HTTP: Status 100

 (继续)
-> 请求者应当继续提出请求。 服务器返回此代码表示已收到请求的第一部分,正在等待其余部分。
HTTP: Status 101

 (切换协议)
-> 请求者已要求服务器切换协议,服务器已确认并准备切换。
复制代码

 

复制代码
说明:
HTTP Status 2xx

  (成功)
->表示成功处理了请求的状态代码;

详细代码及说明:

HTTP Status 200

 (成功)
-> 服务器已成功处理了请求。 通常,这表示服务器提供了请求的网页。
HTTP Status 201

 (已创建)
-> 请求成功并且服务器创建了新的资源。
HTTP Status 202

 (已接受)
-> 服务器已接受请求,但尚未处理。
HTTP Status 203

 (非授权信息)
-> 服务器已成功处理了请求,但返回的信息可能来自另一来源。
HTTP Status 204

 (无内容)
-> 服务器成功处理了请求,但没有返回任何内容。
HTTP Status 205

 (重置内容)
-> 服务器成功处理了请求,但没有返回任何内容。
HTTP Status 206

 (部分内容)
-> 服务器成功处理了部分 GET 请求。
复制代码

 

复制代码
说明:

HTTP Status 4xx

 (请求错误)
->这些状态代码表示请求可能出错,妨碍了服务器的处理。

详细代码说明:
HTTP Status 400

 (错误请求) 
->服务器不理解请求的语法。
HTTP Status 401

 (未授权) 
->请求要求身份验证。 对于需要登录的网页,服务器可能返回此响应。
HTTP Status 403

 (禁止)
-> 服务器拒绝请求。
HTTP Status 404

 (未找到) 
->服务器找不到请求的网页。
HTTP Status 405

 (方法禁用) 
->禁用请求中指定的方法。
HTTP Status 406

 (不接受) 
->无法使用请求的内容特性响应请求的网页。
HTTP Status 407

 (需要代理授权) 
->此状态代码与 401(未授权)类似,但指定请求者应当授权使用代理。
HTTP Status 408

 (请求超时) 
->服务器等候请求时发生超时。
HTTP Status 409

 (冲突) 
->服务器在完成请求时发生冲突。 服务器必须在响应中包含有关冲突的信息。
HTTP Status 410

 (已删除)
-> 如果请求的资源已永久删除,服务器就会返回此响应。
HTTP Status 411

 (需要有效长度) 
->服务器不接受不含有效内容长度标头字段的请求。
HTTP Status 412

 (未满足前提条件) 
->服务器未满足请求者在请求中设置的其中一个前提条件。
HTTP Status 413

 (请求实体过大) 
->服务器无法处理请求,因为请求实体过大,超出服务器的处理能力。
HTTP Status 414

 (请求的 URI 过长) 请求的 URI(通常为网址)过长,服务器无法处理。
HTTP Status 415

 (不支持的媒体类型) 
->请求的格式不受请求页面的支持。
HTTP Status 416

 (请求范围不符合要求) 
->如果页面无法提供请求的范围,则服务器会返回此状态代码。
HTTP Status 417

 (未满足期望值) 
->服务器未满足”期望”请求标头字段的要求。
复制代码
复制代码
说明
HTTP Status 5xx

 (服务器错误)
->这些状态代码表示服务器在尝试处理请求时发生内部错误。 这些错误可能是服务器本身的错误,而不是请求出错。

代码详细及说明:
HTTP Status 500

 (服务器内部错误) 
->服务器遇到错误,无法完成请求。
HTTP Status 501

 (尚未实施) 
->服务器不具备完成请求的功能。 例如,服务器无法识别请求方法时可能会返回此代码。
HTTP Status 502

 (错误网关) 
->服务器作为网关或代理,从上游服务器收到无效响应。
HTTP Status 503

 (服务不可用)
-> 服务器目前无法使用(由于超载或停机维护)。 通常,这只是暂时状态。
HTTP Status 504

 (网关超时) 
->服务器作为网关或代理,但是没有及时从上游服务器收到请求。
HTTP Status 505

 (HTTP 版本不受支持)
-> 服务器不支持请求中所用的 HTTP 协议版本。
复制代码

 

end

分享到:
评论

相关推荐

    内置对象application,session,cokie,viewstate的区别与session详解

    内置对象application,session,cokie,viewstate的区别与session详解

    Cokie及Session

    Cookie及Session使用宝典,及多年工作的总结经验,对于初学者非常有帮助

    cokie vieer

    用于网络安全,主要查自己上过的网站留下的cookie

    Linux下安装与配置基于nginx的tomcat负载均衡和集群(通过cookie分发请求)

    NULL 博文链接:https://mljavalife.iteye.com/blog/1779444

    ASP.NET 3.5 深入学习

    asp.net 3.5 入门到精通 包括:WEB控件,ADO.NET、COKIE及SESSION应用 实例学习

    COKIE公司完整棋牌网游源码,客户端+服务器端(亲测可用)

    FishGame完整网游源码,客户端+服务器端(亲测可用)

    Cookie项目源码

    Cookie项目源码,用于cookie的保存,删除,获取等使用,BS项目,vs可以直接打开运行。

    Android 中cookie的处理详解

    Cookie,有时也用其复数形式Cookies,指某些网站为了辨别用户身份、进行session跟踪而储存在用户本地终端上的数据(通常经过加密)。 Cookie最早是网景公司的前雇员Lou Montulli在1993年3月的发明。 发起 Cookie是...

    Android持久化保存cookie的方法

    主要介绍了Android持久化保存cookie的方法,在解析网页信息的时候,需要登录后才能访问,所以使用httpclient模拟登录,然后把cookie保存下来,以供下一次访问使用,感兴趣的小伙伴们可以参考一下

    react-chat:React聊天

    [√] 注册、登录、cokie的使用 [√] 聊天室(可开启两个浏览器窗口进行聊天测试) [√] 实现服务端渲染 [√] 使用新特性对项目做一些优化 [√] 打包上线 下载项目 $ git clone git@github....

    Python HTTP客户端自定义Cookie实现实例

    主要介绍了Python HTTP客户端自定义Cookie实现实例的相关资料,需要的朋友可以参考下

    jquery.cookie.min.js

    最新的JQUERY.COOKIE.MIN.JS

    购物车ajax

    用ajax+josn+cokie开发的一个购物车demo,学习典经之作

    Python对页面功能进行AB测试

    零、度量选择 列出你将在此用作不变度量和评估度量的度量。 ...评估度量:总转化率、留存率、净转化率 对于每个度量,解释你为什么使用或不使用它作为不变度量和评估度量。此外,说明你期望从评估度量中获得什么试验...

    TQ即时聊天软件免费版的

     当用户点击网站上在线客服按钮后,系统通过用户IP或者Cokie,或者与网后台结合,判断用户所在地区、用户类型等相关信息,通过智能分拣技术,分配到提前设定好的相关客服进行接待。  5、智能机器人技术  系统可以...

    application-cookie-consent

    GDPR Cokie同意申请此扩展程序允许为Cookie和跟踪器设置GDPR兼容同意屏幕。 这将使您可以征求用户的同意,以激活或不使用Cookie或跟踪器,具体取决于不同类型的工具:必要,偏好,统计信息,市场营销。 项目负责人:...

Global site tag (gtag.js) - Google Analytics