gpt4 book ai didi

java - 在 Java 中解码 URI 查询字符串

转载 作者:IT老高 更新时间:2023-10-28 20:24:23 25 4
gpt4 key购买 nike

我需要解码一个包含查询字符串的 URI;预期的输入/输出行为类似于以下内容:

abstract class URIParser
{
/** example input:
* something?alias=pos&FirstName=Foo+A%26B%3DC&LastName=Bar */
URIParser(String input) { ... }
/** should return "something" for the example input */
public String getPath();
/** should return a map
* {alias: "pos", FirstName: "Foo+A&B=C", LastName: "Bar"} */
public Map<String,String> getQuery();
}

我尝试过使用 java.net.URI ,但它似乎解码了查询字符串,因此在上面的示例中,我留下了“alias=pos&FirstName=Foo+A&B=C&LastName=Bar”,因此“&”是查询分隔符还是中的字符存在歧义一个查询组件。

编辑:我刚试过URI.getRawQuery()它不进行编码,所以我可以用 & 拆分查询字符串,但是我该怎么办? Javascript 有 decodeURIComponent ,在Java中好像找不到对应的方法。

有什么建议吗?我不想使用任何新的库。

最佳答案

使用

URLDecoder.decode(proxyRequestParam.replace("+", "%2B"), "UTF-8")
.replace("%2B", "+")

模拟decodeURIComponent。 Java 的 URLDecoder 将加号解码为空格,这不是您想要的,因此您需要替换语句。

Warning: the .replace("%2B", "+") at the end will corrupt your data if the original (pre-x-www-form-urlencoded) contained that string, as @xehpuk pointed out.

关于java - 在 Java 中解码 URI 查询字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2632175/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com