Alex Rivera | Logout

How do I encode URI parameter values?

Asked 2009-01-14T18:21:23.623
57

I want to send a URI as the value of a query/matrix parameter. Before I can append it to an existing URI, I need to encode it according to RFC 2396. For example, given the input:

http://google.com/resource?key=value1 & value2

I expect the output:

http%3a%2f%2fgoogle.com%2fresource%3fkey%3dvalue1%2520%26%2520value2

Neither java.net.URLEncoder nor java.net.URI will generate the right output. URLEncoder is meant for HTML form encoding which is not the same as RFC 2396. URI has no mechanism for encoding a single value at a time so it has no way of knowing that value1 and value2 are part of the same key.

Edit
Report

3 Answers

20

You could also use Spring's UriUtils

answered 2011-07-16T03:48:28.357
9

I don't have enough reputation to comment on answers, but I just wanted to note that downloading the JSR-311 api by itself will not work. You need to download the reference implementation (jersey).

Only downloading the api from the JSR page will give you a ClassNotFoundException when the api tries to look for an implementation at runtime.

answered 2009-12-30T22:05:48.777
3

I wrote my own, it's short, super simple, and you can copy it if you like: http://www.dmurph.com/2011/01/java-uri-encoder/

answered 2011-01-17T06:15:59.537

Your Answer