Welcome to collectivesolver - Programming & Software Q&A with code examples. A website with trusted programming answers. All programs are tested and work.

Contact: aviboots(AT)netvision.net.il

Buy a domain name - Register cheap domain names from $0.99 - Namecheap

Scalable Hosting That Grows With You

Secure & Reliable Web Hosting, Free Domain, Free SSL, 1-Click WordPress Install, Expert 24/7 Support

Semrush - keyword research tool

Boost your online presence with premium web hosting and servers

Disclosure: My content contains affiliate links.

39,845 questions

51,766 answers

573 users

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
...