Jit*_*oli 3 c# google-api google-url-shortener
我使用下面的代码来缩短长网址
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;
}
Run Code Online (Sandbox Code Playgroud)
我创建了一个调度程序来缩短大量的URL.并且大部分时间都低于例外
System.Net.WebException:远程服务器返回错误:(403)Forbidden.在System.Net.HttpWebRequest.GetResponse()
我在想,由于Courtesy Limit我得到了这个例外,所以每用户限制增加了100,000.0请求/秒/用户,但我仍然得到相同的例外.
我不明白为什么它发生,即使我一次几乎没有2000服务器的请求.
请指教.
看看你的问题,我认为这是一个超出速率限制的错误.如果您修改代码,则可以检索错误响应:
try
{
........
}
catch (WebException exception)
{
string responseText;
using(var reader = new StreamReader(exception.Response.GetResponseStream()))
{
responseText = reader.ReadToEnd();
}
}
catch (Exception ex)
{
......
}
Run Code Online (Sandbox Code Playgroud)
如果超出速率限制错误,您将在responseText以下内容中找到类似的内容:
{
"error": {
"errors": [
{
"domain": "usageLimits",
"reason": "rateLimitExceeded",
"message": "Rate Limit Exceeded"
}
],
"code": 403,
"message": "Rate Limit Exceeded"
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
6258 次 |
| 最近记录: |