Thad House
Thad House

Reputation: 183

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

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?

Upvotes: 4

Views: 141

Answers (1)

VGR
VGR

Reputation: 44414

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;

Upvotes: 1

Related Questions