CFLib.org – Common Function Library Project

googleURLShorten(url[, apiKey])

Last updated January 14, 2011

author

Raymond Camden

Version: 2 | Requires: CF8 | Library: UtilityLib

Description:
Uses Google's URL Shortening service to shorten a URL.

Return Values:
Returns a string.

Example:

<cfset sampleURL = "http://www.coldfusionjedi.com/index.cfm/2011/1/10/jQuery-based-example-of-simple-shopping-cart-UI">
<cfset test = googleURLShorten(sampleURL)>
<cfoutput>
I shorteneded #sampleURL# to #test#.<br/>
</cfoutput>

Parameters:

Name Description Required
url URL to shorten. Yes
apiKey Optional API key. No

Full UDF Source:

<!---
 Uses Google's URL Shortening service to shorten a URL.
 v2 by RJLSoftware (rjlsoftware@gmail.com)
 
 @param url 	 URL to shorten. (Required)
 @param apiKey 	 Optional API key. (Optional)
 @return Returns a string. 
 @author Raymond Camden (ray@camdenfamily.com) 
 @version 2, January 14, 2011 
--->
<cffunction name="googleURLShorten" output="false" returnType="string">
	<cfargument name="url" type="string" required="true">
	<cfargument name="apiKey" type="string" required="false" default="" hint="API key identifies your application to Google">

	<cfset var requestURL = "https://www.googleapis.com/urlshortener/v1/url">
	<cfset var httpResult = "">
	<cfset var result = "">
	<cfset var response = "">
	<cfset var body = {"longUrl"=arguments.url}>
	<cfset body = serializeJson(body)>

	<cfif arguments.apiKey NEQ "">
	    <cfset requestURL=requestURL & "?key=" & arguments.apiKey>
	</cfif>

	<cfhttp url="#requestURL#" method="post" result="httpResult">
		<cfhttpparam type="header" name="Content-Type" value="application/json">
		<cfhttpparam type="body" value="#body#">
	</cfhttp>
	<cfset response=deserializeJSON(httpResult.filecontent.toString())>

    <cfif structkeyexists(response, 'error')>
        <cfset result=response.error.message>
    <cfelse>
        <!--- No Errors, return response.id (which is the shortened url) --->
        <cfset result=response.id>
    </cfif>

	<cfreturn result>
</cffunction>
blog comments powered by Disqus

Search CFLib.org


Latest Additions

Kevin Cotton added
date2ExcelDate
May 5, 2016

Raymond Camden added
CapFirst
April 25, 2016

Chris Wigginton added
loremIpsum
January 18, 2016

Gary Stanton added
calculateArrival...
November 19, 2015

Sebastiaan Naafs - van Dijk added
getDaysInQuarter
November 13, 2015

Created by Raymond Camden / Design by Justin Johnson