使用查询字符串中的:在Java中创建URI

我试图在
Java中创建一个URI,其中我的查询字符串有一个:在其中.但是,无论我如何尝试创建URI,我都会得到无效的响应.

新URI(“http”,“localhost:1181”,“/ stream.mjpg”,“part1:part2”,null).toString();给我
http:// localhost:1181 / stream.mjpg?part1:part2,没有:在查询字符串中被转义.

如果我在创建URI之前转义查询字符串,它会转义:中的%,给出%3A,这是不正确的.

新URI(“http”,“localhost:1181”,“/ stream.mjpg”,“part1:part2”,null).toString();给
HTTP://本地主机:1181 / stream.mjpg part1的%3Apart2

我的结果需要是http:// localhost:1181 / stream.mjpg?part1:part2,因为我的服务器需要:在查询字符串中编码

有什么我缺少的,或者我将不得不手动创建查询字符串?

最佳答案 它不漂亮,但你可以在查询部分使用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;
点赞