2011-05-03 119 views
11

是否有一个类来编码符合RFC 3986规范的通用StringJava和RFC 3986 URI编码

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

感谢

回答

1

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

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

+1

这不仅仅是关于“+”,它是关于完全遵循RFC 3986规范而不是适用于查询参数(需要“+”)的RFC 1738。 – Mark 2011-05-03 04:26:09

6

如果它是一个网址,使用URI

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

其实这是一个通用的字符串,我已经更新了这个问题:) – Mark 2011-05-03 04:31:40

+0

好吧,一个俗气的方法是使用上面,然后从前面去掉http:// – MeBigFatGuy 2011-05-03 04:33:14

+1

只需传递null作为第一个参数。 – EJP 2012-03-26 22:50:08

0

在Spring Web应用程序的情况下,我是abl E可使用此:

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/

1

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