Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using tinyurl.com in a .Net application ... possible?

I found the following code to create a tinyurl.com url:

http://tinyurl.com/api-create.php?url=http://myurl.com

This will automatically create a tinyurl url. Is there a way to do this using code, specifically C# in ASP.NET?

like image 766
mattruma Avatar asked Dec 14 '08 03:12

mattruma


People also ask

Does TinyURL have an API?

TinyURL offers an API which allows applications to automatically create short URLs.


2 Answers

You should probably add some error checking, etc, but this is probably the easiest way to do it:

System.Uri address = new System.Uri("http://tinyurl.com/api-create.php?url=" + YOUR ADDRESS GOES HERE);
System.Net.WebClient client = new System.Net.WebClient();
string tinyUrl = client.DownloadString(address);
Console.WriteLine(tinyUrl);
like image 194
mcrumley Avatar answered Sep 19 '22 07:09

mcrumley


After doing some more research ... I stumbled upon the following code:

    public static string MakeTinyUrl(string url)
    {
        try
        {
            if (url.Length <= 30)
            {
                return url;
            }
            if (!url.ToLower().StartsWith("http") && !Url.ToLower().StartsWith("ftp"))
            {
                url = "http://" + url;
            }
            var request = WebRequest.Create("http://tinyurl.com/api-create.php?url=" + url);
            var res = request.GetResponse();
            string text;
            using (var reader = new StreamReader(res.GetResponseStream()))
            {
                text = reader.ReadToEnd();
            }
            return text;
        }
        catch (Exception)
        {
            return url;
        }
    }

Looks like it may do the trick.

like image 21
mattruma Avatar answered Sep 19 '22 07:09

mattruma