我正在使用以下代码来缩短长网址
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) 禁止访问。 at System.Net.HttpWebRequest.GetResponse()
我在想,由于礼貌限制,我得到了这个异常,因此将每用户限制增加了 100,000.0 个请求/秒/用户,但我仍然得到同样的异常。
我不明白为什么即使我一次向服务器发出几乎 2000 个请求也会发生这种情况。
请指教。
看着你的问题,我认为这是一个速率限制超出错误。如果按如下所示修改代码,则可以检索错误响应:
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"
}
}
此错误是因为您非常快速地将数据发布到网络服务,因此谷歌将其检测为机器人。如果您经常手动发布数据,它将要求输入验证码)。
因此,要解决此问题,您需要增加每个 POST 请求之间的时间间隔。