WebClient / HttpClient的缓存问题

编程入门 行业动态 更新时间:2024-10-28 11:20:07
本文介绍了WebClient / HttpClient的缓存问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我正在开发一个代码,以每30秒轮询一次Bitstamp交易行情。这是我拥有的代码:

I'm developing a code to poll a Bitstamp exchange ticker every 30 seconds. This is a code I have:

public IObservable<string> Stream(Uri way, WebClient wc) { Func<IObserver<string>, Task> Fun = async Observer => { var res = await wc.DownloadStringTaskAsync(way); Observer.OnNext(value: res); }; return Observable.Create<string>(Fun); } public IObservable<string> GetDelay(int secs) { var exe = TimeSpan.FromSeconds(secs); return Observable.Empty<string>("x").Delay(exe); } Stream(new Uri("bitstamp/api/ticker"), new WebClient { }).Concat(GetDelay(30)) .Repeat(5).Subscribe(res => Debug.WriteLine("got result: {0}", res));

问题是 WebClient (和 HttpClient )在第一次调用后都返回缓存的结果,可以在相同的时间戳记下看到:

The problem is that WebClient (and HttpClient, too) both return cached results after the first call, it can be seen by the same timestamp:

得到的结果:{ high: 690.00, last: 645.10, timestamp: 1387715532 ...} 得到的结果:{高: 690.00,最后: 645.10,时间戳: 1387715532 ...} ...

got result: {"high": "690.00", "last": "645.10", "timestamp": "1387715532" ... } got result: {"high": "690.00", "last": "645.10", "timestamp": "1387715532" ... } ...

即使在关闭网络后,它们也通常会返回结果,因此显然它们会将其缓存在某个位置。无法添加?cache = random之类的内容,因为Bitstamp上的代码不允许使用请求参数。为 WebRequest 设置 Headers [HttpRequestHeader.CacheControl] = no-cache 也不起作用。

Even after turning the networks off they return the result normally so obviously they cache it somewhere. Adding something like "?cache=random" does not work because request parameters are not allowed for ticker on Bitstamp. Setting Headers[HttpRequestHeader.CacheControl] = "no-cache" for WebRequest does not work either.

如何解决这种奇怪的缓存行为?

How can I fix this weird caching behavior?

推荐答案

已解决通过在每次后续调用之前设置 wc.Headers [HttpRequestHeader.IfModifiedSince] = DateTime.UtcNow.ToString(); 。

Solved by setting wc.Headers[HttpRequestHeader.IfModifiedSince] = DateTime.UtcNow.ToString(); before each subsequent call.

更多推荐

WebClient / HttpClient的缓存问题

本文发布于:2023-11-02 13:15:02,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1552500.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:缓存   WebClient   HttpClient

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!