简体   繁体   English

Java.net.URI 构造函数不是编码和字符

[英]Java.net.URI constructor is not encoding & character

I am trying to create a URL where the query parameters contain a symbol &.我正在尝试创建一个 URL,其中查询参数包含符号 &。 When I am passing this to Java.net.uri( https://docs.oracle.com/javase/8/docs/api/java/net/URI.html ) class constructor its not encoding the & symbol to %26.当我将它传递给 Java.net.uri( https://docs.oracle.com/javase/8/docs/api/java/net/URI.html ) 类构造函数时,它没有将 & 符号编码为 %26。

Example: https://www.anexample.com:443/hello/v5/letscheck/image/down?name=tom&jerry&episode=2示例: https : //www.anexample.com : 443/hello/v5/letscheck/image/down?name=tom&jerry&episode=2

Now tom&jerry is the value of the query parameter but when we pass this to Java.net.uri constructor it encodes all spaces and special symbols but does not encode & to %26.现在 tom&jerry 是查询参数的值,但是当我们将它传递给 Java.net.uri 构造函数时,它会对所有空格和特殊符号进行编码,但不会将 & 编码为 %26。

So tom and jerry both become separate query parameter which I don't want.所以 tom 和 jerry 都成为我不想要的单独查询参数。

code will look something like below:代码如下所示:

String query = "name=tom&jerry&episode=2"

URI uri = new URI(scheme, null, host, port, path, query, null);

I have also tried encoding the query parameters myself and then sending it to the constructor like below:我也尝试过自己编码查询参数,然后将其发送到构造函数,如下所示:

String query = "name=tom%26jerry&episode=2"

URI uri = new URI(scheme, null, host, port, path, query, null);

But in this case the encoded parameter becomes tom%2526jerry as % is encoded to %25但在这种情况下,编码参数变为 tom%2526jerry,因为 % 被编码为 %25

So how can I encode it so I can send & inside as a query parameter?那么我如何编码它以便我可以将 & 作为查询参数发送到内部?

Have you tried something like below?你有没有试过像下面这样的?

String tomJerry = "name=" + URLEncoder.encode("tom&jerry", StandardCharsets.UTF_8.toString());
String episode = "episode=" + URLEncoder.encode("2", StandardCharsets.UTF_8.toString());
String query = tomJerry + '&' + episode;
URI uri = new URI(scheme, null, host, port, path, query, null);

A better way would be looping through the key value pairing of the queries and applying URLEncoder to the value then joining the rest of the query with & after or perhaps stream , map then collect .更好的方法是遍历查询的键值对并将URLEncoder应用于该值,然后使用& after 或streammap然后collect加入查询的其余部分。 But the point is to encode the value part of the query string.但重点是对查询字符串的值部分进行编码。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM