How to create an equivalent to JavaScript encodeURIComponent and decodeURIComponent in Java

1 Answer

0 votes
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.net.URLDecoder;

public class Program {
    public static String decodeURIComponent(String s) {
        if (s == null) {
          return null;
        }
    
        String result = null;
    
        try {
          result = URLDecoder.decode(s, "UTF-8");
        }
    
        catch (UnsupportedEncodingException e) {
          result = s;  
        }
    
        return result;
    }
    public static String encodeURIComponent(String str) {
        String result = null;
    
        try {
            result = URLEncoder.encode(str, "UTF-8")
                             .replaceAll("\\+", "%20")
                             .replaceAll("\\%21", "!")
                             .replaceAll("\\%27", "'")
                             .replaceAll("\\%28", "(")
                             .replaceAll("\\%29", ")")
                             .replaceAll("\\%7E", "~");
        }
    
        // This exception should never occur.
        catch (UnsupportedEncodingException e) {
          result = str;
        }
    
        return result;
    }  
    public static void main(String[] args) {
        String str = "https://www.seek4info.com/search.php?query=seo";
        
        String encode = encodeURIComponent(str); 
        System.out.println(encode);
        
        String decode = decodeURIComponent(encode); 
        System.out.println(decode);
    }
}



/*
run:

https%3A%2F%2Fwww.seek4info.com%2Fsearch.php%3Fquery%3Dseo
https://www.seek4info.com/search.php?query=seo

*/

 



answered Apr 13, 2025 by avibootz
...