Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Nuget package for bitly to shorten the links

Tags:

.net

bit.ly

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.

like image 494
Dalvir Singh Avatar asked Nov 29 '22 07:11

Dalvir Singh


1 Answers

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

like image 145
devfunkd Avatar answered Dec 21 '22 22:12

devfunkd