开发者

Java and RFC 3986 URI encoding

is there a class to encode a generic String开发者_开发知识库 following the RFC 3986 specification?

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

Thanks


Solved with this:

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

Method encodeUri


If it's a url, use URI

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


Source : Twitter RFC3986 compliant encoding functions.

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

/** 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 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.

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


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

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/

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜