我使用下面的代码来缩短长网
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;
}
我创建了一个调度程序来缩短大量网址。并且大部分时间都低于异常
System.Net.WebException:远程服务器返回错误:(403)Forbidden。在System.Net.HttpWebRequest.GetResponse()
我在想,由于Courtesy Limit我得到了这个例外,所以每用户限制增加了100,000.0请求/秒/用户,但我仍然得到同样的例外。
我不明白为什么它会发生,即使我一次只向服务器发出2000请求。
请告知。
答案 0 :(得分:6)
看看你的问题,我认为这是一个超出速率限制的错误。如果您修改代码,则可以检索错误响应:
try
{
........
}
catch (WebException exception)
{
string responseText;
using(var reader = new StreamReader(exception.Response.GetResponseStream()))
{
responseText = reader.ReadToEnd();
}
}
catch (Exception ex)
{
......
}
如果超出了速率限制错误,您会在responseText
中找到类似的内容:
{
"error": {
"errors": [
{
"domain": "usageLimits",
"reason": "rateLimitExceeded",
"message": "Rate Limit Exceeded"
}
],
"code": 403,
"message": "Rate Limit Exceeded"
}
}
答案 1 :(得分:0)
发生此错误是因为您将数据快速发布到webservice,因此谷歌将其检测为机器人。(如果您经常手动发布数据,则会要求输入验证码。)
所以要解决这个问题,你需要增加每个帖子请求之间的时间间隔。