开发者

Could it be that the google url shortening api key works only on 1 computer?

开发者 https://www.devze.com 2023-02-19 18:31 出处:网络
I\'m using the Google URL Shortener from an ASP.NET website. It works fine from my localhost, but on the test server I get the following

I'm using the Google URL Shortener from an ASP.NET website. It works fine from my localhost, but on the test server I get the following error:

System.Net.WebException: The remote server returned an error: (403)
Forbidden.
a开发者_StackOverflowt System.Net.HttpWebRequest.GetResponse()
at GoogleUrlShortnerApi.Shorten(String url) 

I'm using the exact code that is shown here: http://www.jphellemons.nl/post/Google-URL-shortener-API-%28googl%29-C-sharp-class-C.aspx

Could it be that the key works only on my local computer, and not any other computer? I have obtained another key (using another Google account), but this one gives me the same error (403) both on my local computer, and on the test server.


I doubt very much the API is linked to a particular PC. You need to check the requests - both the URL and headers - that your program is sending out, they must be different in some way. Is your server behind some kind of proxy - e.g Apache? If not configured right this might also be mangling the request. Also make sure your requests are encoded correctly.


I made a few modifications, according to a tutorial by Scott Mitchell, and I change the following lines of code:

First, Instead of:

string post = "{\"longUrl\": \"" + url + "\"}";

I used:

string post = string.Format(@"{{""longUrl"": ""{0}""}}", url );

Second, I commented out these 2 lines:

request.ServicePoint.Expect100Continue = false;  
request.Headers.Add("Cache-Control", "no-cache");

I don't know why, but suddenly it started working. So I wanted to see which of the 3 thins I did made the problem, so I returned each one, and - TADA - it still works, even with all 3 back there! So I really don't know what caused the problem, but since the code work without those 2 commented out lines, and the other modification, I am leaving it that way.

I hope this answer will help someone sometime...

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号