WebClient client = new WebClient();
string url = "https://someurl.com/..."
string get = client.DownloadString(url);如何统计url被下载了多少次?
发布于 2016-06-19 04:51:21
解决这个问题的一种方法是将WebClient子类化并覆盖您想要获取统计数据的方法。我在下面的实现中选择了保留通过GetWebRequest的任何url的统计信息。我对代码进行了广泛的注释,所以我认为很明显,它可以归结为在字典中保留每个Uri的计数。
// subclass WebClient
public class WebClientWithStats:WebClient
{
// appdomain wide storage
static Dictionary<Uri, long> stats = new Dictionary<Uri, long>();
protected override WebResponse GetWebResponse(WebRequest request)
{
// prevent multiple threads changing shared state
lock(stats)
{
long count;
// do we have thr Uri already, if yes, gets its current count
if (stats.TryGetValue(request.RequestUri, out count))
{
// add one and update value in dictionary
count++;
stats[request.RequestUri] = count;
}
else
{
// create a new entry with value 1 in the dictionary
stats.Add(request.RequestUri, 1);
}
}
return base.GetWebResponse(request);
}
// make statistics available
public static Dictionary<Uri, long> Statistics
{
get
{
return new Dictionary<Uri, long>(stats);
}
}
}典型的使用场景如下所示:
using(var wc = new WebClientWithStats())
{
wc.DownloadString("http://stackoverflow.com");
wc.DownloadString("http://stackoverflow.com");
wc.DownloadString("http://stackoverflow.com");
wc.DownloadString("http://meta.stackoverflow.com");
wc.DownloadString("http://stackexchange.com");
wc.DownloadString("http://meta.stackexchange.com");
wc.DownloadString("http://example.com");
}
var results = WebClientWithStats.Statistics;
foreach (var res in results)
{
Console.WriteLine("{0} is used {1} times", res.Key, res.Value);
}它将输出:
https://meta.stackoverflow.com/被使用了1次
https://stackexchange.com/被使用了1次
https://meta.stackexchange.com/被使用了1次
http://example.com/被使用了1次
我会认为pluralization bug是理所当然的。
https://stackoverflow.com/questions/30307822
复制相似问题