我正在使用下面的代码来缩短长网址
public static string UrlShorten(string url)
{
string post = "{\"longUrl\": \"" + url + "\"}";
string shortUrl = url;
HttpWebRequest request = (HttpWebRequest)WebRequest.Create("https://www.googleapis.com/urlshortener/v1/url?key=" + ReadConfig("GoogleUrlShortnerApiKey"));
try
{
request.ServicePoint.Expect100Continue = false;
request.Method = "POST";
request.ContentLength = post.Length;
request.ContentType = "application/json";
request.Headers.Add("Cache-Control", "no-cache");
using (Stream requestStream = request.GetRequestStream())
{
byte[] postBuffer = Encoding.ASCII.GetBytes(post);
requestStream.Write(postBuffer, 0, postBuffer.Length);
}
using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
{
using (Stream responseStream = response.GetResponseStream())
{
using (StreamReader responseReader = new StreamReader(responseStream))
{
string json = responseReader.ReadToEnd();
shortUrl = Regex.Match(json, @"""id"": ?""(?<id>.+)""").Groups["id"].Value;
}
}
}
}
catch (Exception ex)
{
// if Google's URL Shortner is down...
Utility.LogSave("UrlShorten", "Google's URL Shortner is down", url, ex.ToString());
//System.Diagnostics.Debug.WriteLine(ex.Message);
//System.Diagnostics.Debug.WriteLine(ex.StackTrace);
}
return shortUrl;
}
我创建了一个调度程序来缩短大量 url。而且大部分时间都低于异常
System.Net.WebException:远程服务器返回错误:(403)禁止。在 System.Net.HttpWebRequest.GetResponse()
我在想,由于礼貌限制,我得到了这个例外,所以每用户限制增加了 100,000.0 个请求/秒/用户,但我仍然得到同样的例外。
我不明白为什么它会发生,即使我一次几乎没有向服务器发出 2000 个请求。
请指教。