Search code examples
javaurlencodeurl-encoding

UnsupportedEncodingException issue


I'm trying to create a link with URLEncoder but I obtain the UnsupportedEncodingException and I don't know why?

String param1="a";
String param2="b";
String key="key";
String h="h";

public static void main(String[]args){
    try {
         URLEncoder.encode(param1,key);
         URLEncoder.encode(param2, h);
    } catch (Exception e) {

        e.printStackTrace();
    }

Solution

  • URLEncoder.encode takes two parameters.

    1st: Value to be encoded.

    2nd: Name of the encoding (e.g UTF-8)

    So in your case, you would want to do something like this:

        static String param1 = "a";
        static String param2 = "b";
    
        public static void main(String[] args) {
            try {
                StringBuilder url = new StringBuilder();
                url.append("&key=");
                url.append(URLEncoder.encode(param1, "UTF-8"));
                url.append("&h=");
                url.append(URLEncoder.encode(param2, "UTF-8"));
                System.out.println(url);
            } catch (Exception e) {
    
                e.printStackTrace();
            }
        }