Java encoding similiar to JavaScript encodeURIComponent

February 20, 2012 in JavaScript, Web 2.0

You may have a REST service that returns an encoded output to a JavaScript client which decodes this output in the client side. Unfortunately, this scenario will not always work because of the mismatch between both the Java java.net.URLEncoder encode() API and the JavaScript encodeURIComponent().

To be able to make the java.net.URLEncoder encode() behavior equivalent to the JavaScript encodeURIComponent(), all what you should do is the following String replacements.

public static String encodeURIComponent(String component)   {     
	String result = null;      
	
	try {       
		result = URLEncoder.encode(component, "UTF-8")   
			   .replaceAll("\\%28", "(")                          
			   .replaceAll("\\%29", ")")   		
			   .replaceAll("\\+", "%20")                          
			   .replaceAll("\\%27", "'")   			   
			   .replaceAll("\\%21", "!")
			   .replaceAll("\\%7E", "~");     
	catch (UnsupportedEncodingException e) {       
		result = component;     
	}      
	
	return result;   
}   

After that you can safely decode the output in the client side using the JavaScript decodeURIComponent().

References:

http://stackoverflow.com/questions/607176/java-equivalent-to-javascripts-encodeuricomponent-that-produces-identical-outpu

https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/encodeURIComponent

http://docs.oracle.com/javase/1.4.2/docs/api/java/net/URLEncoder.html

3 comments on “Java encoding similiar to JavaScript encodeURIComponent

  1. This appears to be essentially the same code developed by John Topley who also provides a JAVA decodeURICompoenent. (You can see his posting and earlier attempts at http://stackoverflow.com/questions/607176/java-equivalent-to-javascripts-encodeuricomponent-that-produces-identical-outpu)

    Its good to have such a clean solution posted several places on the web, and it may be that these were independently developed, but if you did base your solution on his, it is also good to give reference to prior developers.

  2. Yes David, It was one of my references, I added it to the reference section. Thanks for reminding me.

  3. mouse on said:

    Thanks! This post helped me alot!

Leave a reply

Your email address will not be published. Required fields are marked *

309,154 Spam Comments Blocked so far by Spam Free Wordpress

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>

Powered by sweet Captcha