VaV
VaV

Reputation: 133

Java.net.URI constructor is not encoding & character

I am trying to create a URL where the query parameters contain a symbol &. When I am passing this to Java.net.uri(https://docs.oracle.com/javase/8/docs/api/java/net/URI.html) class constructor its not encoding the & symbol to %26.

Example: https://www.anexample.com:443/hello/v5/letscheck/image/down?name=tom&jerry&episode=2

Now tom&jerry is the value of the query parameter but when we pass this to Java.net.uri constructor it encodes all spaces and special symbols but does not encode & to %26.

So tom and jerry both become separate query parameter which I don't want.

code will look something like below:

String query = "name=tom&jerry&episode=2"

URI uri = new URI(scheme, null, host, port, path, query, null);

I have also tried encoding the query parameters myself and then sending it to the constructor like below:

String query = "name=tom%26jerry&episode=2"

URI uri = new URI(scheme, null, host, port, path, query, null);

But in this case the encoded parameter becomes tom%2526jerry as % is encoded to %25

So how can I encode it so I can send & inside as a query parameter?

Upvotes: 0

Views: 740

Answers (1)

jpllosa
jpllosa

Reputation: 2202

Have you tried something like below?

String tomJerry = "name=" + URLEncoder.encode("tom&jerry", StandardCharsets.UTF_8.toString());
String episode = "episode=" + URLEncoder.encode("2", StandardCharsets.UTF_8.toString());
String query = tomJerry + '&' + episode;
URI uri = new URI(scheme, null, host, port, path, query, null);

A better way would be looping through the key value pairing of the queries and applying URLEncoder to the value then joining the rest of the query with & after or perhaps stream, map then collect. But the point is to encode the value part of the query string.

Upvotes: 0

Related Questions