Question

est-il une classe pour coder une String générique suivant la spécification RFC 3986?

C'est: "hello world" => "hello%20world" Non (RFC 1738) : "hello+world"

Merci

Était-ce utile?

Autres conseils

Si c'est une URL, utilisez URI

URI uri = new URI("http", "//hello world", null);
String urlString = uri.toASCIIString();
System.out.println(urlString);

Source: Twitter RFC3986 fonctions de codage conforme.

Cette méthode prend chaîne et la convertit en chaîne codée spécifique RFC3986.

/** The encoding used to represent characters as bytes. */
public static final String ENCODING = "UTF-8";

public static String percentEncode(String s) {
    if (s == null) {
        return "";
    }
    try {
        return URLEncoder.encode(s, ENCODING)
                // OAuth encodes some characters differently:
                .replace("+", "%20").replace("*", "%2A")
                .replace("%7E", "~");
        // This could be done faster with more hand-crafted code.
    } catch (UnsupportedEncodingException wow) {
        throw new RuntimeException(wow.getMessage(), wow);
    }
}

ne sais pas s'il y a un. Il y a une classe qui fournit un codage mais il change « » dans « + ». Mais vous pouvez utiliser la méthode replaceAll dans la classe String pour convertir le « + » dans ce que vous voulez.

str.repaceAll ( "+", "% 20")

Dans le cas des applications Web Spring, j'ai pu utiliser ceci:

http: //static.springsource.org/spring/docs/3.1.x/javadoc-api/org/springframework/web/util/UriComponentsBuilder.html

UriComponentsBuilder.newInstance()
  .queryParam("KEY1", "Wally's crazy empôrium=")
  .queryParam("KEY2", "Horibble % sign in value")
  .build().encode("UTF-8") // or .encode() defaults to UTF-8

renvoie la chaîne

?KEY1=Wally's%20crazy%20emp%C3%B4rium%3D&KEY2=Horibble%20%25%20sign%20in%20value

Une vérification croix sur un de mes sites préférés montre le même résultat, « codage en pourcentage pour les URIs ». Cela me semble correct. http://rishida.net/tools/conversion/

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top