2

我有 ac# 客户端与cherrypy(http/rest) 网络服务交谈。问题是我不能同时打开压缩和缓存。

request.AutomaticDecompression = DecompressionMethods.GZip | DecompressionMethods.Deflate;

通过省略上面的行,我得到了正确的缓存头(If-None-Math,If-Modified-Since),而注释掉它得到了压缩头(Accept-Encodig:gzip),但不是缓存头。在我看来,这就像一个错误,但也许我做错了什么。

[完整代码]

        public static string GET(string URL)
    {
        string JSON;
        // Create the web request  
        HttpWebRequest request = WebRequest.Create(URL) as HttpWebRequest;
        HttpRequestCachePolicy cPolicy = new HttpRequestCachePolicy(HttpRequestCacheLevel.Revalidate);

        request.Accept = "application/json";            
        request.CachePolicy = cPolicy;
        request.AutomaticDecompression = DecompressionMethods.GZip | DecompressionMethods.Deflate;
        request.Pipelined = false;

        // Get response  
        using (HttpWebResponse response = request.GetResponse() as HttpWebResponse)
        {                
            // Get the response stream  
            StreamReader readerF = new StreamReader(response.GetResponseStream());

            JSON = readerF.ReadToEnd();
            // Console application output  
            //Console.WriteLine(JSON);
            if (response.IsFromCache )
                Console.WriteLine("Request not from cache");
        }

        return JSON;
    }
4

2 回答 2

3

我已经实现了一种解决方法,请参见下面的代码。我认为处理压缩比处理缓存更容易,所以我自己实现了压缩部分。多亏了一篇博文,这很容易:HttpWebRequest 和 GZip Http Responses;我仍然认为这是.net中的一个错误。

        public static string GET(string URL)
    {
        string JSON;
        // Create the web request  
        HttpWebRequest request = WebRequest.Create(URL) as HttpWebRequest;
        HttpRequestCachePolicy cPolicy = new HttpRequestCachePolicy(HttpRequestCacheLevel.Revalidate);

        request.Accept = "application/json";
        request.Headers.Add(HttpRequestHeader.AcceptEncoding, "gzip,deflate");
        request.CachePolicy = cPolicy;
        request.Pipelined = false;

        // Get response  
        using (HttpWebResponse response = request.GetResponse() as HttpWebResponse)
        {
            //From http://www.west-wind.com/WebLog/posts/102969.aspx
            Stream responseStream = responseStream = response.GetResponseStream();
            if (response.ContentEncoding.ToLower().Contains("gzip"))
                responseStream = new GZipStream(responseStream, CompressionMode.Decompress);
            else if (response.ContentEncoding.ToLower().Contains("deflate"))
                responseStream = new DeflateStream(responseStream, CompressionMode.Decompress);


            // Get the response stream  
            StreamReader readerF = new StreamReader(responseStream);
            JSON = readerF.ReadToEnd();
        }

        return JSON;
    }
于 2009-04-19T12:12:43.897 回答
0

这是政策的副作用吗?如果您只使用默认策略或其他策略会发生什么?

其他选择是自己管理缓存。

于 2009-04-13T16:28:02.557 回答