Domanda

c'è una classe per codificare un generico String Seguendo le specifiche RFC 3986?

Questo è: "hello world" => "hello%20world" NOT (RFC 1738): "hello+world"

Grazie

È stato utile?

Altri suggerimenti

Se è un URL, usa URI

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

Fonte: funzioni di codifica conformi a Twitter RFC3986.

Questo metodo prende la stringa e lo converte in stringa codificata specifica 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);
    }
}

In non so se ce n'è uno. C'è una classe che fornisce codifica ma cambia "in"+". Ma puoi usare il metodo sostituita nella classe stringa per convertire il "+" in quello che vuoi.

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

Nel caso delle applicazioni Web Spring, sono stato in grado di utilizzare questo:

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

Restituisce la stringa

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

Un controllo incrociato su uno dei miei siti preferiti mostra lo stesso risultato, "Codifica percentuale per URI". Mi sembra buono. http://rishida.net/tools/conversion/

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top