I was trying to clarify difference between Java's URLEncoder.encode(), Javascript's encodeURI(), encodeURIComponent(), and Android's Uri.encode().
It looks like this:
URLEncoder.encode() encodes, others keepencodeURI() keeps, others encode+ for URLEncoder.encode(), %20 for othersIt seems like URLEncoder.encode() and encodeURIComponent() behaves the same. Am I correct, or in fact they also have some difference?
Interesting question. I just ran some code to test this:
encodeURIComponent escapes all characters except:
Not Escaped:
A-Z a-z 0-9 - _ . ! ~ * ' ( )
Code:
var sb = [];
for (var i = 0; i < 256; ++i) {
var encoded = encodeURIComponent(String.fromCharCode(i));
if (encoded.indexOf('%') !== 0 && !encoded.match(/^[a-zA-Z0-9]+$/)) {
sb.push(encoded);
}
}
console.log(sb.join(' '));
Result:
! ' ( ) * - . _ ~
encodeURI escapes all characters except:
Not Escaped:
A-Z a-z 0-9 - _ . ! ~ * ' ( ) ; , / ? : @ & = + $ #
Code:
var sb = [];
for (var i = 0; i < 256; ++i) {
var encoded = encodeURI(String.fromCharCode(i));
if (encoded.indexOf('%') !== 0 && !encoded.match(/^[a-zA-Z0-9]+$/)) {
sb.push(encoded);
}
}
console.log(sb.join(' '));
Result:
! # $ & ' ( ) * + , - . / : ; = ? @ _ ~
Translates a string into application/x-www-form-urlencoded format using a specific encoding scheme. This method uses the supplied encoding scheme to obtain the bytes for unsafe characters.
Code:
public static void main(String[] args) {
try {
StringBuilder sb = new StringBuilder();
for (int i = 0; i < 256; ++i) {
String encoded = URLEncoder.encode(String.valueOf((char) i), "UTF-8");
if (!encoded.startsWith("%") && !encoded.matches("^[a-zA-Z0-9]+$")) {
sb.append(' ').append(encoded);
}
}
System.out.println(sb.substring(1));
} catch (Exception e) {}
}
Result:
Note that + is actually a whitespace.
+ * - . _
Encodes characters in the given string as '%'-escaped octets using the UTF-8 scheme. Leaves letters ("A-Z", "a-z"), numbers ("0-9"), and unreserved characters ("_-!.~'()*") intact. Encodes all other characters.
Code:
try {
StringBuilder sb = new StringBuilder();
for (int i = 0; i < 256; ++i) {
String encoded = Uri.encode(String.valueOf((char) i));
if (!encoded.startsWith("%") && !encoded.matches("^[a-zA-Z0-9]+$")) {
sb.append(' ').append(encoded);
}
}
System.out.println(sb.substring(1));
} catch (Exception e) {}
Result:
! ' ( ) * - . _ ~
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With