Shortening a URL using bitly’s API in C#
Using the snippet below you can convert links in your application from this
1 | http://www.fluxbytes.com/ |
to this
1 | http://bit.ly/WVk1qN |
This is especially important in cases where you have a fairly long URL which you want to post somewhere and you either don’t want to use such a long URL, or simply you are limited by characters. An example of that situation would be a URL such as
1 | http://www.google.com/url?sa=t&rct=j&q=c+sharp+convert+string+to+binary&source=web&cd=1&cad=rja&ved=0CDQQFjAA&url=http%3A%2F%2Fwww.fluxbytes.com%2Fcsharp%2Fconvert-string-to-binary-and-binary-to-string-in-c%2F&ei=T79SUcOVI4rEPOeogPgP&usg=AFQjCNEihqo_KsRZuGpb0-ZpWdqjdqr_sA |
which can be shortened down to
1 | http://bit.ly/WVuXF4 |
The first thing you are going to need it an account from bitly.com. After you have created an account, log in and navigate to https://bitly.com/a/your_api_key. The page will contain your username and your API key which are both needed.
Here is the snippet which you will need to modify to use your own username and API key
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 | string statusCode = string.Empty; // The variable which we will be storing the status code of the server response string statusText = string.Empty; // The variable which we will be storing the status text of the server response string shortUrl = string.Empty; // The variable which we will be storing the shortened url string longUrl = string.Empty; // The variable which we will be storing the long url string urlToShorten = "http://www.fluxbytes.com/"; // The url we want to shorten XmlDocument xmlDoc = new XmlDocument(); // The xml document which we will use to parse the response from the server WebRequest request = WebRequest.Create("http://api.bitly.com/v3/shorten"); byte[] data = Encoding.UTF8.GetBytes(string.Format("login={0}&apiKey={1}&longUrl={2}&format={3}", "your username", // Your username "your API key", // Your API key HttpUtility.UrlEncode(urlToShorten), // Encode the url we want to shorten "xml")); // The format of the response we want the server to reply with request.Method = "POST"; request.ContentType = "application/x-www-form-urlencoded"; request.ContentLength = data.Length; using (Stream ds = request.GetRequestStream()) { ds.Write(data, 0, data.Length); } using (WebResponse response = request.GetResponse()) { using (StreamReader sr = new StreamReader(response.GetResponseStream())) { xmlDoc.LoadXml(sr.ReadToEnd()); } } statusCode = xmlDoc.GetElementsByTagName("status_code")[0].InnerText; statusText = xmlDoc.GetElementsByTagName("status_txt")[0].InnerText; shortUrl = xmlDoc.GetElementsByTagName("url")[0].InnerText; longUrl = xmlDoc.GetElementsByTagName("long_url")[0].InnerText; Console.WriteLine(statusCode); // Outputs "200" Console.WriteLine(statusText); // Outputs "OK" Console.WriteLine(shortUrl); // Outputs "http://bit.ly/WVk1qN" Console.WriteLine(longUrl); // Outputs "http://www.fluxbytes.com/" |
Keep in mind since bitly’s API supports both POST and GET methods this could be rewritten to something shorter using the WebClient class. As an example:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 | string statusCode = string.Empty; string statusText = string.Empty; string shortUrl = string.Empty; string longUrl = string.Empty; string urlToShorten = "http://wwww.fluxbytes.com/"; using (WebClient wb = new WebClient()) { string data = string.Format("http://api.bitly.com/v3/shorten/?login={0}&apiKey={1}&longUrl={2}&format={3}", "your username", // Your username "your API key", // Your API key HttpUtility.UrlEncode(urlToShorten), // Encode the url we want to shorten "xml"); XmlDocument xmlDoc = new XmlDocument(); xmlDoc.LoadXml(wb.DownloadString(data)); statusCode = xmlDoc.GetElementsByTagName("status_code")[0].InnerText; statusText = xmlDoc.GetElementsByTagName("status_txt")[0].InnerText; shortUrl = xmlDoc.GetElementsByTagName("url")[0].InnerText; longUrl = xmlDoc.GetElementsByTagName("long_url")[0].InnerText; Console.WriteLine(statusCode); // Outputs "200" Console.WriteLine(statusText); // Outputs "OK" Console.WriteLine(shortUrl); // Outputs "http://bit.ly/WVk1qN" Console.WriteLine(longUrl); // Outputs "http://www.fluxbytes.com/" } |
The reason why I prefer the first approach is because it gives your more control over to what is happening, which makes its easier to add various features later on down the line if you want something like a progress bar that shows how long it will take for the task to complete and so on.
Sometimes I get error: 403 – RATE_LIMIT_EXCEEDED. And ApiKey is deprecated.
Good, great post.
any good patterns and practices about it? any Nuget ? thx
Thanks CooLMinE. I’ll check it :)
Thanks it really works. This is what I was looking for. If at all any exception comes how to handle it. Is there any exception class that is provided by bitly API?
If something goes wrong on bitly’s side (including authentication) you will get all the information from the status code and status text.
For additional information on what kind of status codes you can expect, have a look at http://dev.bitly.com/formats.html
Very nice article, exactly what I wanted to find.
very good guide , this really help. thank you
This site was… how do I say it? Relevant!! Finally I have found something which helped me. Thanks a lot!
Hello there, You have done an excellent job. I will certainly digg it and personally suggest to my friends. I am sure they will be benefited from this site.
Useful info. Lucky me I found your website by chance, and I am stunned why this coincidence did not took place earlier! I bookmarked it.
Very great post. I simply stumbled upon your weblog and wished to say that I’ve truly enjoyed surfing around your weblog posts. After all I will be subscribing in your feed and I am hoping you write again soon!