1

I am trying to hit a webservice URL with a query parameter as foo & bar with the URL as encoded. To achieve encoding, I am using Apache URIBuilder. The code is as follows:

URIBuilder ub = new URIBuilder("http://example.com/query").setParameter("q", "foo & bar");
            URI uri = ub.build();
            HttpGet httpget = new HttpGet(uri);
            System.out.println(httpget.getURI());

I get the following as output: http://example.com/query?q=+foo+%2526+bar

I am new to this JAR file and have 2 questions:

  1. Why is the space in the query param replaced with a '+' sign and not with %20 special character.

  2. Why is the '&' symbol in the query param getting encoded twice and how to avoid it.

surya
  • 31
  • 1
  • 8
  • for you second question take a look here https://stackoverflow.com/questions/9292865/what-is-url-encoding-2526. and '+' is valid replacement for space character more info here (https://stackoverflow.com/questions/2678551/when-to-encode-space-to-plus-or-20). – Michal Jun 20 '18 at 10:43
  • Thanks Michal. Sorry for the delay in response. – surya Jun 29 '18 at 11:56

1 Answers1

1
  1. Why is the space in the query param replaced with a '+' sign and not with %20 special character.

In URI encoding, plus sign and %20 are interchangeable. However, another encoding may be used in different environment. For example when you are uploading using multipart/form-data, it will use different encoding. Thus you can't use neither %20 nor +.

  1. Why is the '&' symbol in the query param getting encoded twice and how to avoid it.

It is not encoded twice, but it is URI encoded.

When you put query=A&B, you are sending two parameters:

  • query with value A
  • B with no value

This way, you can't send the actual &. To send & as a parameter, you must encode the parameter. If you send query=+foo+%2526+bar, you are sending only 1 parameter:

  • query with value foo & bar

To send q=foo&bar, you need to write this code:

URIBuilder ub = new URIBuilder("http://example.com/query");
ub.setParameter("q", "foo");
ub.setParameter("bar", "");
URI uri = ub.build();
HttpGet httpget = new HttpGet(uri);
System.out.println(httpget.getURI());
waza
  • 486
  • 9
  • 19