Java URI Encode encodeURIComponent(String s, String charset)

Here you can find the source of encodeURIComponent(String s, String charset)

Description

Encodes the passed String as UTF-8 using an algorithm that's compatible with JavaScript's encodeURIComponent function.

License

Open Source License

Parameter

Parameter Description
s The String to be encoded
charset the character set to base the encoding on

Return

the encoded String

Declaration

public static String encodeURIComponent(String s, String charset) 

Method Source Code

//package com.java2s;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;

public class Main {
    /**/*from   w  w  w.  j  a  v a 2  s  . c  o  m*/
     * Encodes the passed String as UTF-8 using an algorithm that's compatible
     * with JavaScript's <code>encodeURIComponent</code> function. Returns
     * <code>null</code> if the String is <code>null</code>.
     * 
     * @param s The String to be encoded
     * @param charset the character set to base the encoding on
     * @return the encoded String
     */
    public static String encodeURIComponent(String s, String charset) {
        if (s == null) {
            return null;
        } else {
            String result;

            try {
                result = URLEncoder.encode(s, charset)
                        .replaceAll("\\+", "%20").replaceAll("\\%21", "!")
                        .replaceAll("\\%27", "'").replaceAll("\\%28", "(")
                        .replaceAll("\\%29", ")").replaceAll("\\%7E", "~");
            } catch (UnsupportedEncodingException e) {
                // This exception should never occur
                result = s;
            }

            return result;
        }
    }
}

Related

  1. encodeUri(URI uri)
  2. encodeURI(URI uri)
  3. encodeURIComponent(final String s)
  4. encodeURIComponent(String component)
  5. encodeURIComponent(String input)
  6. encodeURIComponent(String uriComp)
  7. encodeUriComponent(String value)
  8. encodeURIComponentForJavaScript(String str)
  9. encodeURIParam(String s)