如何使用 java.net.URI

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/7362158/
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 19:40:49  来源:igfitidea点击:

How to use java.net.URI

javastandard-library

提问by Piotr Czapla

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.

我曾尝试使用 java.net.URI 来操作查询字符串,但我什至无法完成非常简单的任务,例如从一个 url 获取查询字符串并将其放置在另一个 url 中。

Do you know how to make this code below work

你知道如何使下面的代码工作吗

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%3D1but it returns: http://domain/a-path?param1=x%253D1(double encoding)

调用uri2.toASCIIString()应该返回:http://domain/a-path?param1=x%3D1但它返回:(http://domain/a-path?param1=x%253D1双重编码)

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

如果我使用 getQuery() 而不是 getRawQuery() 查询字符串根本没有编码,网址如下所示: http://domain/a-path?param1=x=1

采纳答案by Jesper

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 willencode it. That's exactly the opposite of what you want, in this case.

问题是第二个构造函数将使用 URL 编码对查询和片段进行编码。但它=是一个合法的 URI 字符,所以它不会为你编码;而%不是一个合法的URI字符,所以它对其进行编码。在这种情况下,这与您想要的完全相反。

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

所以,你不能使用第二个构造函数。使用第一个,通过自己将字符串的各个部分连接在一起。

回答by Ryan Ransford

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

getQuery()能用一个调用来包装调用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());