URL Encoding and Decoding Functions for Hubitat

This code allows you to drop a Map into the function and get a URL encoded string back with item=value&item2=value2 etc.

Might save someone an hour of looking...especially if you are new to groovy.

import java.net.URLEncoder

/ some code I stole from a website.....
// thank you https://snipplr.com/view/68918/groovy-urlencode-and-urldecode-a-map/
// e.g. given map [x:1, y2] returns x=1&y=2
def urlEncodeMap( aMap ) {
    def encode = { URLEncoder.encode( "$it".toString() ) }
    return aMap.collect { encode(it.key) + '=' + encode(it.value) }.join('&')
}

// undoes the thing above......
def urlDecodeToMap( aUrlEncodedStr ) {
    def result = [:]
    def decode =  { URLDecoder.decode(it) }
    def ampSplit = aUrlEncodedStr.tokenize('&')
    ampSplit.each {
        def eqSplit = it.tokenize('=')
        result[ decode(eqSplit[0]) ] = decode(eqSplit[1])
    }
    return result;
}
1 Like

The URL Decode method is not needed. This is done automatically when the message is received. When you send an HTTP GET message to the hub via an app, the handling method is passed off all of the keys and values in the "params" map. So, you don't need to do it again. The full URL is not passed off to the handling method.

1 Like