Java 和 RFC 3986 URI 编码

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5864954/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-30 13:11:12  来源:igfitidea点击:

Java and RFC 3986 URI encoding

javauriencoderfc3986

提问by Mark

is there a class to encode a generic Stringfollowing the RFC 3986 specification?

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

That is: "hello world"=> "hello%20world"Not (RFC 1738): "hello+world"

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

Thanks

谢谢

回答by MeBigFatGuy

If it's a url, use URI

如果是 url,请使用 URI

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

回答by Amit Tumkur

Source : Twitter RFC3986 compliant encoding functions.

来源:Twitter RFC3986 兼容编码函数。

This method takes string and converts it to RFC3986 specific encoded string.

此方法采用字符串并将其转换为 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);
    }
}

回答by Jason Dunkelberger

In the case of Spring Web applications, I was able to use this:

在 Spring Web 应用程序的情况下,我能够使用它:

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

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

returns the String

返回字符串

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

A cross check on one of my favorite sites shows the same result, "Percent encoding for URIs". Looks good to me. http://rishida.net/tools/conversion/

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

回答by Radu Stoenescu

In don't know if there is one. There is a class that provides encoding but it changes " " into "+". But you can use the replaceAll method in String class to convert the "+" into what you want.

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

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

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