我试图在Java中创建一个URI,其中我的查询字符串中有一个:
。但是,无论我如何尝试创建URI,我都会得到无效的响应。
new URI("http", "localhost:1181", "/stream.mjpg", "part1:part2", null).toString();
给了我http://localhost:1181/stream.mjpg?part1:part2
,在查询字符串中没有:
被转义。
如果我在创建URI之前转义查询字符串,它会逃脱%
中的%3A
,给出%253A
,这是不正确的。
new URI("http", "localhost:1181", "/stream.mjpg", "part1%3Apart2", null).toString();
给
http://localhost:1181/stream.mjpg?part1%253Apart2
我的结果需要是http://localhost:1181/stream.mjpg?part1%3Apart2
,因为我的服务器需要:
在查询字符串中编码
有什么我缺少的,或者我将不得不手动创建查询字符串?
它不漂亮,但你可以在查询部分使用URLEncoder:
String query = URLEncoder.encode("part1:part2", StandardCharsets.UTF_8);
// Required by server.
query = query.replace("+", "%20");
String uri =
new URI("http", "localhost:1181", "/stream.mjpg", null, null)
+ "?" + query;