I am trying to create a URI in Java, where my query string has a : in it. However, no matter how I try to create the URI, I get an invalid response.
new URI("http", "localhost:1181", "/stream.mjpg", "part1:part2", null).toString(); gives me
http://localhost:1181/stream.mjpg?part1:part2, without the : in the query string being escaped.
If I escape the query string before creating the URI, it escapes the % in the %3A, giving %253A, which is incorrect.
new URI("http", "localhost:1181", "/stream.mjpg", "part1%3Apart2", null).toString(); gives
http://localhost:1181/stream.mjpg?part1%253Apart2
My result needs to be http://localhost:1181/stream.mjpg?part1%3Apart2 because my server requires : to be encoded in query strings`
Is there something I am missing, or am I going to have to manually create the query string?
It’s not pretty, but you can use URLEncoder on just the query part:
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;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With