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

2 thoughts on “Percent encoding in Groovy

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s