calling google Url Shortner API in C#

14,666

Solution 1

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);
            }

        }

    }
}

Solution 2

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)
        };
    }
}

Solution 3

How about changing

   var requestContent = new FormUrlEncodedContent(new[] 
        {new KeyValuePair<string, string>("longUrl", s),});

to

   var requestContent = new StringContent("{\"longUrl\": \" + s + \"}");
Share:
14,666
smohamed
Author by

smohamed

Software Engineer with speciality in Scala language, Microservice architecture, and RESTful API design.

Updated on July 17, 2022

Comments

  • smohamed
    smohamed almost 2 years

    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/v1/url

    Content-Type: application/json

    {"longUrl": "http://www.google.com/"}

    When I try to use this code:

    using System.Net;
    using System.Net.Http;
    using System.IO;
    

    and the main method is:

    static void Main(string[] args)
    {
        string s = "http://www.google.com/";
        var client = new HttpClient();
    
        // Create the HttpContent for the form to be posted.
        var requestContent = new FormUrlEncodedContent(new[] {new KeyValuePair<string, string>("longUrl", s),});
    
        // Get the response.            
        HttpResponseMessage response = client.Post("https://www.googleapis.com/urlshortener/v1/url",requestContent);
    
        // Get the response content.
        HttpContent responseContent = response.Content;
    
        // Get the stream of the content.
        using (var reader = new StreamReader(responseContent.ContentReadStream))
        {
            // Write the output.
            s = reader.ReadToEnd();
            Console.WriteLine(s);
        }
        Console.Read();
    }
    

    I get the error code 400: This API does not support parsing form-encoded input. I don't know how to fix this.

  • smohamed
    smohamed over 12 years
    it gives this error: Argument 2: cannot convert from 'string' to System.Net.Http.HttpContent'
  • smohamed
    smohamed over 12 years
    Error: 'System.Net.Http.HttpContent' does not contain a definition for 'CreateEmpty'
  • competent_tech
    competent_tech over 12 years
    Sorry, re-read the full question and realized I was answering it incorrectly. Please see the latest revision.
  • MW_hk
    MW_hk about 10 years
    const string MATCH_PATTERN = @"""id"": ?""(?<id>.+)"""; Console.WriteLine(Regex.Match(responseText, MATCH_PATTERN).Groups["id"].Value); gets the shorten url.
  • Jon
    Jon over 7 years
    application/json was the missing piece for me. Was using text/json, like an idiot.