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>

Search CFLib.org


Latest Additions

Raymond Camden added
QueryDeleteRows
November 04, 2017

Leigh added
nullPad
May 11, 2016

Raymond Camden added
stripHTML
May 10, 2016

Kevin Cotton added
date2ExcelDate
May 05, 2016

Raymond Camden added
CapFirst
April 25, 2016

Created by Raymond Camden / Design by Justin Johnson