calling google Url Shortner API in C#

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

    Google has a NuGet package for using the Urlshortener API. Details can be found here.

    Based on this example you would implement it as such:

    using System;
    using System.Net;
    using System.Net.Http;
    using Google.Apis.Services;
    using Google.Apis.Urlshortener.v1;
    using Google.Apis.Urlshortener.v1.Data;
    using Google.Apis.Http;
    
    namespace ConsoleTestBed
    {
        class Program
        {
            private const string ApiKey = "YourAPIKey";
    
            static void Main(string[] args)
            {
                var initializer = new BaseClientService.Initializer
                {
                    ApiKey = ApiKey,
                    //HttpClientFactory = new ProxySupportedHttpClientFactory()
                };
                var service = new UrlshortenerService(initializer);
                var longUrl = "http://wwww.google.com/";
                var response = service.Url.Insert(new Url { LongUrl = longUrl }).Execute();
    
                Console.WriteLine($"Short URL: {response.Id}");
                Console.ReadKey();
            }
        }
    }
    

    If you are behind a firewall you may need to use a proxy. Below is an implementation of the ProxySupportedHttpClientFactory, which is commented out in the sample above. Credit for this goes to this blog post.

    class ProxySupportedHttpClientFactory : HttpClientFactory
    {
        private static readonly Uri ProxyAddress 
            = new UriBuilder("http", "YourProxyIP", 80).Uri;
        private static readonly NetworkCredential ProxyCredentials 
            = new NetworkCredential("user", "password", "domain");
    
        protected override HttpMessageHandler CreateHandler(CreateHttpClientArgs args)
        {
            return new WebRequestHandler
            {
                UseProxy = true,
                UseCookies = false,
                Proxy = new WebProxy(ProxyAddress, false, null, ProxyCredentials)
            };
        }
    }
    

提交回复
热议问题