Welcome to WuJiGu Developer Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
967 views
in Technique[技术] by (71.8m points)

windows phone 8 - Caching issue with WebClient/HttpClient

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("https://bitstamp.net/api/ticker"), new WebClient { }).Concat(GetDelay(30))
    .Repeat(5).Subscribe(res => Debug.WriteLine("got result: {0}", res));

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

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

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to WuJiGu Developer Q&A Community for programmer and developer-Open, Learning and Share
...