کد:
Public Shared Function Shorten(url As String) As String
Dim key As String = "$MYGOOGLEAPIKEY$"
Dim post As String = "{""longUrl"": """ & url & """}"
Dim shortUrl As String = url
Dim request As HttpWebRequest = DirectCast(WebRequest.Create("https://www.googleapis.com/urlshortener/v1/url?key=" & key), HttpWebRequest)
Try
request.ServicePoint.Expect100Continue = False
request.Method = "POST"
request.ContentLength = post.Length
request.ContentType = "application/json"
request.Headers.Add("Cache-Control", "no-cache")
Using requestStream As Stream = request.GetRequestStream()
Dim postBuffer As Byte() = Encoding.ASCII.GetBytes(post)
requestStream.Write(postBuffer, 0, postBuffer.Length)
End Using
Using response As HttpWebResponse = DirectCast(request.GetResponse(), HttpWebResponse)
Using responseStream As Stream = response.GetResponseStream()
Using responseReader As New StreamReader(responseStream)
Dim json As String = responseReader.ReadToEnd()
shortUrl = Regex.Match(json, """id"": ?""(?<id>.+)""").Groups("id").Value
End Using
End Using
End Using
Catch ex As Exception
' if Google's URL Shortner is down...
System.Diagnostics.Debug.WriteLine(ex.Message)
System.Diagnostics.Debug.WriteLine(ex.StackTrace)
End Try
Return shortUrl
End Function
Shorten(yourlink.com)