calling google Url Shortner API in C#

后端 未结 4 766
孤独总比滥情好
孤独总比滥情好 2021-02-08 10:36

I want to call the google url shortner API from my C# Console Application, the request I try to implement is:

POST https://www.googleapis.com/urlshortener

4条回答
  •  半阙折子戏
    2021-02-08 10:55

    Following is my working code. May be its helpful for you.

    private const string key = "xxxxxInsertGoogleAPIKeyHerexxxxxxxxxx";
    public string urlShorter(string url)
    {
                string finalURL = "";
                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 = "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();
                                finalURL = Regex.Match(json, @"""id"": ?""(?.+)""").Groups["id"].Value;
                            }
                        }
                    }
                }
                catch (Exception ex)
                {
                    // if Google's URL Shortener is down...
                    System.Diagnostics.Debug.WriteLine(ex.Message);
                    System.Diagnostics.Debug.WriteLine(ex.StackTrace);
                }
                return finalURL;
    }
    

提交回复
热议问题