C# 获取System.Net.WebException:远程服务器返回错误:(403)禁止。在Google URL Shortener API调用中

C# 获取System.Net.WebException:远程服务器返回错误:(403)禁止。在Google URL Shortener API调用中,c#,google-api,google-url-shortener,C#,Google Api,Google Url Shortener,我使用下面的代码来缩短长URL public static string UrlShorten(string url) { string post = "{\"longUrl\": \"" + url + "\"}"; string shortUrl = url; HttpWebRequest request = (HttpWebRequest)WebRequest.Create("https://www.googleapis.com/urlshortener/v1/ur

我使用下面的代码来缩短长URL

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缩短(字符串url)
{
字符串post=“{\”longUrl\:\”+url+“\”}”;
字符串shortUrl=url;
HttpWebRequest请求=(HttpWebRequest)WebRequest.Create(“https://www.googleapis.com/urlshortener/v1/url?key=“+ReadConfig”(“GoogleUrlShortnerApiKey”);
尝试
{
request.ServicePoint.Expect100Continue=false;
request.Method=“POST”;
request.ContentLength=post.Length;
request.ContentType=“application/json”;
添加(“缓存控制”、“无缓存”);
使用(Stream requestStream=request.GetRequestStream())
{
byte[]postBuffer=Encoding.ASCII.GetBytes(post);
Write(postBuffer,0,postBuffer.Length);
}
使用(HttpWebResponse=(HttpWebResponse)request.GetResponse())
{
使用(Stream responseStream=response.GetResponseStream())
{
使用(StreamReader responseReader=新的StreamReader(responseStream))
{
字符串json=responseReader.ReadToEnd();
shortUrl=Regex.Match(json,@“id”:?(?.+)“”)。Groups[“id”]值;
}
}
}
}
捕获(例外情况除外)
{
//如果谷歌的网址缩短器关闭了。。。
LogSave(“UrlShorten”,“谷歌的URL缩短器已关闭”,URL,例如ToString());
//系统.诊断.调试.写入线(例如消息);
//系统.诊断.调试.写入线(例如StackTrace);
}
返回短URL;
}
我创建了一个调度程序来缩短大量URL。大多数情况下,我们都得到了以下的例外

System.Net.WebException:远程服务器返回错误:(403)禁止。在System.Net.HttpWebRequest.GetResponse()中

我在想,由于礼貌限制,我得到了这个例外,因此每个用户的请求数限制增加了100000.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"
 }
}

发生此错误的原因是,您将数据快速发布到webservice,因此google会将其检测为robot(如果您如此频繁地手动发布数据,则会要求输入验证码)


因此,要解决这个问题,您需要增加每个post请求之间的时间间隔。

您能看到整个json响应是什么吗?不仅是状态代码。它在“using(HttpWebResponse=(HttpWebResponse)request.GetResponse()”处引发异常,完整的执行选项是“System.Net.WebException:远程服务器返回了一个错误:(403)禁止。在BusinessLogic.Utility.UrlShorten(字符串url)处的System.Net.HttpWebRequest.GetResponse()处在D:\Dotnet Projects\FutureZoom\FutureZoom\BusinessLogic\Utility.cs中:第140行“是的,我得到了完全相同的响应。但是为什么会这样呢?我把每个用户的请求数限制提高了100000.0次/秒/用户,礼貌限制是1000000次/天。我猜不出它到底是什么,但也许你对每秒的请求数做得太多了?否则,请尝试联系谷歌。我的总请求少于2000个。是否需要时间来反映礼貌限制?可能是这样,您的仪表盘会怎么说?