Percent encoding in Groovy

I was writing some helpers for OAuth Twitter authorization. One of the problem I got was the encoding. OAuth is using UTF-8 and percent encoding (special style of URL ecoding).

I couldn’t find anything build-in in Java or Groovy so I wrote a very short little method that does it.

def encodeString(def stringToEncode){

def reservedCaracters = [32:1, 33:1, 42:1, 34:1, 39:1, 40:1, 41:1, 59:1, 58:1, 64:1, 38:1, 61:1, 43:1, 36:1, 33:1, 47:1, 63:1, 37:1, 91:1, 93:1, 35:1]

def encoded =  stringToEncode.collect { letter ->
reservedCaracters[(int)letter] ? “%” +Integer.toHexString((int)letter).toString().toUpperCase() : letter
}
return encoded.join(“”)
}

If you ever need something similar, use it 😉

Greg