Looking on the W3 Schools URL encoding webpage, it says that @
should be encoded as %40
, and that space
should be encoded as %20
.
I've tried both URLEncoder
and URI
, but neither does the above properly:
import java.net.URI;
import java.net.URLEncoder;
public class Test {
public static void main(String[] args) throws Exception {
// Prints me%40home.com (CORRECT)
System.out.println(URLEncoder.encode("[email protected]", "UTF-8"));
// Prints Email+Address (WRONG: Should be Email%20Address)
System.out.println(URLEncoder.encode("Email Address", "UTF-8"));
// http://www.home.com/test?Email%[email protected]
// (WRONG: it has not encoded the @ in the email address)
URI uri = new URI("http", "www.home.com", "/test", "Email [email protected]", null);
System.out.println(uri.toString());
}
}
For some reason, URLEncoder
does the email address correctly but not spaces, and URI
does spaces currency but not email addresses.
How should I encode these 2 parameters to be consistent with what w3schools says is correct (or is w3schools wrong?)
URLEncoder
does not encode as per the URL specification but as per the theapplication/x-www-form-urlencoded
MIME format (which is what most application servers expect for parameter keys/values.) TheURI
type encodes as per its documentation - that is, it isn't a complete URL builder. Note that different parts of the URI have different rules. See this post for more analysis. – McDowell Jan 14 at 16:05