1

そのため、アプリで 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) Forbidden.」というエラーが表示され続けます。

クラスの2番目にデバッグしてブレークポイントを配置しようとしましusingた..

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

その中に入ることはなく、 .usingをキャッチしWebExceptionます。
ここで私が間違っていることについて誰かが私に考えを与えることができますか?

お時間をいただきありがとうございます。

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

これはresponseTextからの の値ですWebException。1 日あたり 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."
 }
}
4

2 に答える 2

2

私はそれを考え出した!!

私が作成したキーは Android デバイス用であり、そのエラーが何度も発生しました。それが IP の問題であることを認識した後、他のキーに IP オプションがないため、サーバー キーを作成しました。サーバーキーをアプリに入れ、BOOM! 出来た!

ここに画像の説明を入力

于 2015-07-28T14:44:18.610 に答える
1

API キーに構成された IP ごとまたはリファラーごとの制限があり、リクエストがこれらの制限に一致しません。この IP またはリファラーからのリクエストを許可する必要がある場合は、Google Developers Console を使用して API キーの設定を更新してください。

APIキーがIPによって制限されるように設定されており、そのAPIキーを使用するように登録されていないIPからリクエストが送信されていることを読みました. Android エミュレーターは別の VM であるため、エミュレーターからの要求は (ほとんどの場合) 実行されているマシンとは異なる IP を持つことに注意してください。

リクエストの発信元の IP を特定して API キーに登録するか、(可能であれば) 制限をリファラーごとに切り替えてコードで処理します。

于 2015-07-27T21:27:41.540 に答える