所以我试图在我的应用程序中使用 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
.
谁能告诉我我在这里做错了什么?
感谢您的时间。
=========================更新======================== =
这是responseText
from 的值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."
}
}