【发布时间】:2012-10-01 07:46:09
【问题描述】:
我正在使用下面的代码来缩短长网址
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 个请求,我也不明白为什么会发生这种情况。
请指教。
【问题讨论】:
-
你能看到整个 json 响应是什么吗?不仅是状态码。
-
它在“使用(HttpWebResponse response = (HttpWebResponse)request.GetResponse())”处抛出异常,完整的执行是“System.Net.WebException:远程服务器返回错误:(403 ) Forbidden. at System.Net.HttpWebRequest.GetResponse() at BusinessLogic.Utility.UrlShorten(String url) in D:\Dotnet Projects\FutureZoom\FutureZoom\BusinessLogic\Utility.cs:line 140"
标签: c# google-api google-url-shortener