Archive for code

A Nifty ASP Function to Convert a Regular URL into a TinyURL

Posted in Technology, Web Programming with tags , , , on May 14, 2008 by webzealot

I was pretty intrigued when I noticed Twitter will automatically convert a “long” URL into a “TinyURL” (see http://www.TinyURL.com if you’re not familiar with this) so I assumed TinyURL.com must have some sort of open API for automatically converting a URL.

Well, there might be an open API, but I sure couldn’t find it!

However, I figured there had to be a way to query against TinyURL.com and get the desired result. So, I wrote my own little script to do exactly that! This uses classic ASP and the XMLHTTP object:

function GetTiny(URL)
if instr(URL, “tinyurl.com”) = 0 then
preText = “<input type=hidden name=tinyurl value=”””
postText = “x = document.all.tinyurl.createTextRange();”

strFrom = “http://tinyurl.com/create.php?url=&#8221; & URL

Set xml = Server.CreateObject(“Microsoft.XMLHTTP”)
xml.Open “GET”, strFrom, False
xml.Send
sHTML = xml.responseText

strFirst = InStr(sHTML, preText ) ‘ Start of data
strLast = InStr(sHTML, postText) -20 ‘ End of Data
TinyURL = Mid(sHTML, strFirst + len(preText), strLast-strFirst-len(preText))

set xml = nothing

GetTiny = TinyURL
else
GetTiny = URL
end if

end function

To invoke it:

call GetTiny("http://www.websiteURLtoShorten.com")

Just that simple! Hope somebody finds this useful! Please let me know if you see any ways this can be improved!

UPDATE: I did discover there is an API for TinyURL… However, I have found it to be problematic. For instance, only “www.” domains seem to work, and adding “http://&#8221; onto the URL will generate an incorrect TinyURL. My script seems to work regardless.