18

StringRFC 3986 仕様に従ってジェネリックをエンコードするクラスはありますか?

つまり: "hello world"=> "hello%20world" Not (RFC 1738) :"hello+world"

ありがとう

4

5 に答える 5

8

URL の場合は、URI を使用します

URI uri = new URI("http", "//hello world", null);
String urlString = uri.toASCIIString();
System.out.println(urlString);
于 2011-05-03T04:29:18.520 に答える
7

これで解決:

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

方法encodeUri

于 2011-05-03T04:47:06.100 に答える
4

出典:Twitter RFC3986準拠のエンコード関数。

このメソッドは文字列を受け取り、それを 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);
    }
}
于 2016-03-19T09:25:19.077 に答える
0

Spring Webアプリケーションの場合、私はこれを使用することができました:

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

文字列を返します

?KEY1 =ウォーリーの%20crazy%20emp%C3%B4rium%3D&KEY2 = Horibble%20%25%20sign%20in%20value

私のお気に入りのサイトの1つをクロスチェックすると、同じ結果「URIのパーセントエンコード」が表示されます。は、私にはよく見えますよ。http://rishida.net/tools/conversion/

于 2012-02-21T19:41:33.053 に答える
0

あるかどうかはわかりません。エンコーディングを提供するクラスがありますが、それは " " を "+" に変更します。ただし、 String クラスの replaceAll メソッドを使用して、「+」を必要なものに変換できます。

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

于 2011-05-03T04:23:25.823 に答える