Nuget package for bitly to shorten the links

Dalvir Singh picture Dalvir Singh · Jul 18, 2015 · Viewed 8.7k times · Source

I need to shorten my links using bitly in C#. Is there any nuget package for this? Can some one provide me code for that so that I can use that.

Answer

devfunkd picture devfunkd · Jul 24, 2015

Check out https://www.nuget.org/packages/BitlyAPI/ or just make your own call to the bit.ly api. The api is very easy to use and work with.

public string Shorten(string longUrl, string login, string apikey)
{
    var url = string.Format("http://api.bit.ly/shorten?format=json&version=2.0.1&longUrl={0}&login={1}&apiKey={2}", HttpUtility.UrlEncode(longUrl), login, apikey);

    HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
    try
    {
        WebResponse response = request.GetResponse();
        using (Stream responseStream = response.GetResponseStream())
        {
            StreamReader reader = new StreamReader(responseStream, Encoding.UTF8);
            JavaScriptSerializer js = new JavaScriptSerializer();
            dynamic jsonResponse = js.Deserialize<dynamic>(reader.ReadToEnd());
            string s = jsonResponse["results"][longUrl]["shortUrl"];
            return s;
        }
    }
    catch (WebException ex)
    {
        WebResponse errorResponse = ex.Response;
        using (Stream responseStream = errorResponse.GetResponseStream())
        {
            StreamReader reader = new StreamReader(responseStream, Encoding.GetEncoding("utf-8"));
            String errorText = reader.ReadToEnd();
            // log errorText
        }
        throw;
    }
}

You can get your login and apikey from bit.ly by going to this link https://bitly.com/a/your_api_key