そのため、アプリで 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."
}
}