谷歌URL缩短API错误(403禁止)[更新]

时间:2015-07-27 20:43:21

标签: android api http xamarin google-url-shortener

所以我正在尝试在我的应用中使用Google URL Shortener API。这是我编写的用于进行HTTP调用并检索缩短URL的类。

public class GoogleUrlShortnerApi
{
    //API Key from Google
    private const string key = "-----------MY_KEY-----------";

    public static string Shorten(string url)
    {
        string post = "{\"longUrl\": \"" + url + "\"}";

        string shortUrl = url;
        HttpWebRequest request = (HttpWebRequest)WebRequest.Create("https://www.googleapis.com/urlshortener/v1/url?key=" + key);

        try {
            request.ServicePoint.Expect100Continue = false;
            request.Method = WebRequestMethods.Http.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 (WebException webEx) {
            System.Diagnostics.Debug.WriteLine (webEx.Message);

            string responseText;
            using(var reader = new StreamReader(webEx.Response.GetResponseStream()))
            {
                responseText = reader.ReadToEnd();
            }
        } catch (Exception ex) {
            System.Diagnostics.Debug.WriteLine (ex.Message);
        }
        return shortUrl;
    }
}

但我一直得到“远程服务器返回错误:(403)禁止。”错误。

我尝试调试并在类中的第二个using上放置一个断点..

using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())

它永远不会进入using并抓住WebException 谁能让我知道我在这里做错了什么?

感谢您的时间。

========================= 更新 ============== ===========

这是responseTextWebException的值。我被允许每天发出1,000,000个请求。为什么我会收到此错误?

{
 "error": {
  "errors": [
   {
    "domain": "usageLimits",
    "reason": "ipRefererBlocked",
    "message": "There is a per-IP or per-Referer restriction configured on your API key and the request does not match these restrictions. Please use the Google Developers Console to update your API key configuration if request from this IP or referer should be allowed.",
    "extendedHelp": "https://console.developers.google.com"
   }
  ],
  "code": 403,
  "message": "There is a per-IP or per-Referer restriction configured on your API key and the request does not match these restrictions. Please use the Google Developers Console to update your API key configuration if request from this IP or referer should be allowed."
 }
}

2 个答案:

答案 0 :(得分:2)

我明白了!!

我创建的密钥是针对Android设备而且它一直给我错误。 因此,在意识到它是IP问题之后,我创建了一个SERVER KEY,因为没有其他密钥具有IP选项。我把服务器密钥放在我的应用程序和BOOM中!它有效!

enter image description here

答案 1 :(得分:1)

  

您的API密钥上配置了每IP或每个Referer限制,并且请求与这些限制不匹配。如果允许来自此IP或引用者的请求,请使用Google Developers Console更新您的API密钥配置。

我读到,因为您的API密钥设置为受IP限制,而您的请求来自未注册使用该API密钥的IP。请记住,来自模拟器的请求(很可能)具有与运行它们的计算机不同的IP,因为Android模拟器是一个单独的VM。

要么找出请求来自的IP并使用您的API密钥注册它,或者(如果可能的话)将限制转换为每个Referer并在您的代码中处理它。