0

I have to encode querystring value in a http request in Java. For example:

http://mysite.com/service?name=James Smith&address=my street

must become:

http://mysite.com/service?name=James%20Smith&address=my%20street

I have to do this in a method where I have querystring value in input, so I have to encode only the value (James Smith, my street, ecc.). I was thinking about using this method org.apache.commons.httpclient.util.URIUtil.encodeWithinQuery: is this right? I have seen many confusing discussion about encoding http request.

Teo
  • 69
  • 2
  • 8

1 Answers1

0

You can URLEncode the URL with

yourNewURL = java.net.URLEncoder.encode(oldurl.toString(), "ISO-8859-1").replace("+", "%20"));

Look at this discussion for further explanations:

URLEncoder not able to translate space character

Community
  • 1
  • 1
Davide Berra
  • 6,387
  • 2
  • 29
  • 50
  • This method replace spaces with "+", but not with "%20" – Teo Feb 12 '13 at 07:55
  • However, I'm not sure if I have to encode using application/x-www-form-urlencoded or RFC-3986 in my case. If i look at http://www.w3schools.com/TAGS/ref_urlencode.asp and try the "Try It Yourself" section, spaces are replaced by "+". – Teo Feb 13 '13 at 15:26