18

是否有一个类可以String按照 RFC 3986 规范对泛型进行编码?

即:"hello world"=>"hello%20world" 不是(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

在不知道有没有。有一个类提供编码,但它将“”更改为“+”。但是您可以使用 String 类中的 replaceAll 方法将“+”转换为您想要的。

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

于 2011-05-03T04:23:25.823 回答
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=Wally's%20crazy%20emp%C3%B4rium%3D&KEY2=Horibble%20%25%20sign%20in%20value

对我最喜欢的网站之一的交叉检查显示了相同的结果,“URI 的百分比编码”。对我来说看上去很好。http://rishida.net/tools/conversion/

于 2012-02-21T19:41:33.053 回答