Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 825
Mark Avatar asked May 03 '11 04:05

Mark


3 Answers

If it's a url, use URI

URI uri = new URI("http", "//hello world", null);
String urlString = uri.toASCIIString();
System.out.println(urlString);
like image 114
MeBigFatGuy Avatar answered Nov 10 '22 20:11

MeBigFatGuy


Solved with this:

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

Method encodeUri

like image 33
Mark Avatar answered Nov 10 '22 20:11

Mark


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);
    }
}
like image 4
Amit Tumkur Avatar answered Nov 10 '22 20:11

Amit Tumkur