Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Creating a URI in Java with a : in the query string

Tags:

java

uri

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?

like image 469
Thad House Avatar asked Jan 26 '26 05:01

Thad House


1 Answers

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;
like image 95
VGR Avatar answered Jan 28 '26 19:01

VGR



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!