calling google Url Shortner API in C#

后端 未结 4 709
孤独总比滥情好
孤独总比滥情好 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 11:03

    you can check the code below (made use of System.Net). You should notice that the contenttype must be specfied, and must be "application/json"; and also the string to be send must be in json format.

    using System;
    using System.Net;
    
    using System.IO;
    namespace ConsoleApplication1
    {
        class Program
        {
            static void Main(string[] args)
            {
                var httpWebRequest = (HttpWebRequest)WebRequest.Create("https://www.googleapis.com/urlshortener/v1/url");
                httpWebRequest.ContentType = "application/json";
                httpWebRequest.Method = "POST";
    
                using (var streamWriter = new StreamWriter(httpWebRequest.GetRequestStream()))
                {
                    string json = "{\"longUrl\":\"http://www.google.com/\"}";
                    Console.WriteLine(json);
                    streamWriter.Write(json);
                }
    
                var httpResponse = (HttpWebResponse)httpWebRequest.GetResponse();
                using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
                {
                    var responseText = streamReader.ReadToEnd();
                    Console.WriteLine(responseText);
                }
    
            }
    
        }
    }
    

提交回复
热议问题