问题 Java和RFC 3986 URI编码


是否有一个编码泛型的类 String 遵循RFC 3986规范?

那是: "hello world" => "hello%20world"  不(RFC 1738)"hello+world"

谢谢


1588
2018-05-03 04:16


起源



答案:


如果是网址,请使用URI

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

6
2018-05-03 04:29



实际上它是一个通用字符串,我已经更新了问题:) - Mark
好吧,一种俗气的方式是使用上面然后从前面剥离http:// - MeBigFatGuy
只需传递null作为第一个参数。 - user207421


答案:


如果是网址,请使用URI

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

6
2018-05-03 04:29



实际上它是一个通用字符串,我已经更新了问题:) - Mark
好吧,一种俗气的方式是使用上面然后从前面剥离http:// - MeBigFatGuy
只需传递null作为第一个参数。 - user207421


解决了这个问题:

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

方法 encodeUri


5
2018-05-03 04:47





来源: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);
    }
}

2
2018-03-19 09:25





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

str.repaceAll( “+”, “%20”)


0
2018-05-03 04:23



它不只是关于“+”,而是完全遵循RFC 3986规范而不是适用于查询参数的RFC 1738(需要“+”)。 - Mark


在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

返回String

?KEY1 = Wally的%20crazy%20emp%C3%B4rium%3D&KEY2 = Horibble%20%25%20sign%20英寸%20value

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


0
2018-02-21 19:41