Encoder les caractères spéciaux d’une URL en Java (comme Javascript.escape()) [Programmation]

[niveau intermédiaire]

Il est possible de reproduire la fonction escape() de Javascript pour le langage Java. Cela permet par exemple de transformer “François” en “Fran%E7ois” ou encore “Maël” en “Ma%EBl”.

public String myEncodeURI(String str) {
  StringBuffer ostr = new StringBuffer();
    for(int i=0; i<str.length(); i++) {
      char ch = str.charAt(i);
      if ((ch >= 0x0020) && (ch <= 0x007e))
        ostr.append(ch); // Pas besoin de convertir
      else {
        // conversion en HEX
        String hex = Integer.toHexString(str.charAt(i) & 0xFFFF);
        ostr.append("%"+hex.toUpperCase());
      }
    }
    return (new String(ostr));
}

Leave a Reply

Your email address will not be published. Required fields are marked *

*