开发者

How to use java.net.URI

I've tried to use java.net.URI to manipulate query strings but I failed to even on very simple task like getting the query string from one url and placing it in another.

Do you know how to make this code below wor开发者_运维百科k

URI sample = new URI("test?param1=x%3D1");
URI uri2 = new URI(
            "http",
            "domain",
            "/a-path",
            sample.getRawQuery(),
            sample.getFragment());

Call to uri2.toASCIIString() should return: http://domain/a-path?param1=x%3D1 but it returns: http://domain/a-path?param1=x%253D1 (double encoding)

if I use getQuery() instead of getRawQuery() the query string is not encoded at all and the url looks like this: http://domain/a-path?param1=x=1


The problem is that the second constructor will encode the query and fragment using URL encoding. But = is a legal URI character, so it will not encode that for you; and % is not a legal URI character, so it will encode it. That's exactly the opposite of what you want, in this case.

So, you can't use the second constructor. Use the first one, by concatenating the parts of the string together yourself.


Could you wrap the call to getQuery() with a call to java.net.URLEncoder.encode(String)?

URI sample = new URI("test?param1=x%3D1");
URI uri2 = new URI(
        "http",
        "domain",
        "/a-path",
        URLEncoder.encode(sample.getQuery(), "UTF-8"),
        sample.getFragment());
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜