Question Goo.gl URL Shortener - The remote server returned an error: (400) Bad Request.

quest2chill

Member
Joined
Mar 3, 2012
Messages
6
Programming Experience
Beginner
I have successfully connected to the Google URL Shortener service at Goo.gl and had my url shortened and returned but only using the basic service.
I now wish to initiate a request using an API Key and have a unique shortened URL returned and logged to a specific user.

The successful basic request is made using: request = "https://www.googleapis.com/urlshortener/v1/url"

For the request that is failing with supplied valid key I used:

request = "https://www.googleapis.com/urlshortener/v1/url?key={" & My.Settings.GURL_SV_APIKey & "}"

The above evaluates to: "https://www.googleapis.com/urlshortener/v1/url?key={API key Removed}" which according to Google this is all that is required.

Message received back:

System.Net.WebException was unhandled
Message=The remote server returned an error: (400) Bad Request.

Code used:

Dim request As String


If My.Settings.GURL_SV_APIKey <> "" Then
request = "https://www.googleapis.com/urlshortener/v1/url?key={" & My.Settings.GURL_SV_APIKey & "}"
Else
request = "https://www.googleapis.com/urlshortener/v1/url"
End If


Dim encoding As New UTF8Encoding


Dim req As HttpWebRequest = CType(WebRequest.Create(request), HttpWebRequest)
Dim byteData As Byte() = encoding.GetBytes("{'longUrl': '" & TextBox1.Text & "'}")


req.ContentType = "application/json"
req.ContentLength = byteData.Length
req.KeepAlive = True
req.Method = "POST"


Dim stream01 As IO.Stream = req.GetRequestStream
stream01.Write(byteData, 0, byteData.Length)


Dim resp As HttpWebResponse = CType(req.GetResponse(), HttpWebResponse)


Dim stream02 As IO.Stream = resp.GetResponseStream
Dim stream As New IO.StreamReader(stream02)
Dim work As String = stream.ReadToEnd

Any help would really be appreciated, I am getting nowhere with this.

Regards
 
Use query parameter key=yourAPIKey, not key={yourAPIKey}
 
Use query parameter key=yourAPIKey, not key={yourAPIKey}

John,

Many thanks, Request is now being excepted and is returning the shortened URL.

Unfortunately, this still only uses the basic shortening service as shortened URL not logged to user.

Will have to do further research.

Bit.ly was so much easier. :jaded:

Thanks again.
 
Back
Top