Why not URLEncoder.encode (String, Charset), URLDecoder.decode (String, Charset)

I'm not sure SOF is the best place to ask about this, but something about java URLEncoder and URLDecoder .

For URLEncoder, it has an encode(String, String) method, where the second parameter is the name of the encoding used. If the encoding is invalid, then a UnsupportedEncodingException is UnsupportedEncodingException . This is a proven exception, so when calling encode() , you should use the try-catch statement. This makes sense in terms of using string encoding ...

But Java has a Charset class, and you can easily access the Charset object of your favorite encoding using Java StandardCharsets or Guava Charsets . This would prevent an exception from occurring which, as you know, will never be thrown if you send encode() correctly spelled encoding name. Without the possibility of using a method such as URLEncoder.encode(String, Charset) , the code I write becomes really ugly because I need to save an additional String variable to store the encoding name, and I have a rather redundant try-catch statement, eg:

 private static final String utf8 = "UTF-8"; ... String msg = ...; try { String encodedMsg = URLEncoder.encode(msg, utf8); ... } catch (UnsupportedEncodingException e) { // This exception should never happen System.err.println("Uh oh..."); } 

The same logic applies to URLDecoder.decode(String, String) .

So, I'm just wondering why Java does not have URLEncoder.encode(String, Charset) and URLDecoder.decode(String, Charset) ? Do Java developers have any plans to support this? This would turn the multi-line monster I wrote above into a nicer single-line liner that doesn't require me to catch an exception. I know that will never happen if the government does not commit the crime of UTF-8. Are there any existing implementations or libraries that enhance this missing feature from URLEncoder and URLDecoder? I tried to find something in Guava, but I did not find anything.

+8
java character-encoding urlencode urldecode
source share
1 answer

I can’t say for sure, but I think it’s just time - URLDecoder came out with JDK 1.0, and Charset came out with JDK 1.4.

YourCharset.name() returns a string containing the canonical name that you must pass to decode () without fear of an exception.

+5
source share

All Articles