Grails – Error creating URL for parameters – UnsupportedEncodingException

Recently (with Grails 2.4.2) an exception popped up in the logs

Caused by: org.codehaus.groovy.grails.web.servlet.mvc.exceptions.ControllerExecutionException: 
Error creating URL for parameters [{language=en, id=256, controller=gallery, action=ajaxLoadMoreDesigns}], 
problem encoding URL part [en]: 'UTF-8'
..
Caused by: java.io.UnsupportedEncodingException: 'UTF-8'
        at java.net.URLEncoder.encode(URLEncoder.java:215)
        ... 9 more

for which there was not really an explanation/fix around google. Looking twice, it turns out the quotes (around UTF-8) are the problem causing the encoding lookup to fail. The exception is caused in RegexUrlMapping.groovy which in the end gets the encoding from the request in ApplicationTagLib.groovy:

String generatedLink = linkGenerator.link(urlAttrs, request.characterEncoding)

It’s easily reproduced like this:

import groovyx.net.http.RESTClient

def client = new RESTClient("http://localhost:8080")
client.get(path: '/', headers: ['Content-Type': "text/xml; charset='UTF-8'"]) //quotes around charset here

And there’s also an easy workaround – clean up the encoding in a Grails filter:

//workaround for some browsers/clients sending quoted encoding values which breaks link generation
if (request.characterEncoding) {
   request.characterEncoding = request.characterEncoding.replace("'", "").replace("\"", "")
}
This entry was posted in Uncategorized. Bookmark the permalink.