2015-07-27 4 views
1

Так что я пытаюсь использовать API-интерфейс Short URL Google в своем приложении. Вот класс, который я написал, чтобы сделать HTTP-вызов и получить сокращенный URL-адрес.Ошибка API URL-адреса google (403 запрещено) [обновление]

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) Запрещенный.» Ошибка.

я пытался отладить и поставить точку останова в классе 2-й using ..

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

Он никогда не выходит в этом using и ловит WebException.
Может ли кто-нибудь дать мне представление о том, что я делаю неправильно здесь?

Спасибо за ваше время.

=============== ОБНОВЛЕНИЕ =================== =======

Это значение responseText от WebException. Мне разрешено делать 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." 
} 
} 

ответ

1

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.

Я читал, что в качестве ключа API настроен быть ограничен IP и ваш запрос исходит от IP, который не зарегистрирован использовать этот ключ API. Имейте в виду, что запросы от эмулятора (скорее всего) имеют другой IP-адрес, чем тот, на котором они запущены, потому что эмулятор Android является отдельной виртуальной машиной.

Либо укажите IP-адрес, из которого получен запрос, и зарегистрируйте его с помощью ключа API, либо, если это возможно, переключите ограничение на каждый референт и обработайте его в коде.

+1

Я не зарегистрировал никакого IP к этому ключу API. Я даже не знал, что это вариант. Когда я создал ключ API, я поместил сертификат SHA1 keystore и имя пакета android. Но я просто создал новый ключ без этих полей, и я все еще получаю сообщение об ошибке. –

+1

Google «ipRefererBlocked», похоже, что консенсус в том, что служба Google Shortener Google просто плоха. – Jason

2

Я понял!

Ключ, который я создал, был для устройства Android, и он продолжал давать мне эту ошибку. Итак, осознав, что это проблема IP, я создал SERVER KEY, потому что никакой другой ключ не имеет IP-опции. Я поместил ключ сервера в свое приложение и BOOM! это сработало!

enter image description here

Смежные вопросы