Encoding URL query parameters in Java

url encode
java url decode query parameters
how to pass query parameter in url in java
spring url encode
spring boot url encoding
urlencoder java
apache commons url encode
convert string to url java

How does one encode query parameters to go on a url in Java? I know, this seems like an obvious and already asked question.

There are two subtleties I'm not sure of:

  1. Should spaces be encoded on the url as "+" or as "%20"? In chrome if I type in "http://google.com/foo=?bar me" chrome changes it to be encoded with %20
  2. Is it necessary/correct to encode colons ":" as %3B? Chrome doesn't.

Notes:

  • java.net.URLEncoder.encode doesn't seem to work, it seems to be for encoding data to be form submitted. For example, it encodes space as + instead of %20, and encodes colon which isn't necessary.
  • java.net.URI doesn't encode query parameters

java.net.URLEncoder.encode(String s, String encoding) can help too. It follows the HTML form encoding application/x-www-form-urlencoded.

URLEncoder.encode(query, "UTF-8");

On the other hand, Percent-encoding (also known as URL encoding) encodes space with %20. Colon is a reserved character, so : will still remain a colon, after encoding.

Guide to Java URL Encoding/Decoding, java.net.URLEncoder.encode(String s, String encoding) can help too. It follows the HTML form encoding application/x-www-form-urlencoded . URL Decoding in Java URL decoding is the process of converting URL encoding query strings and form parameters into their original form. By default, HTML form parameters are encoded using application/x-www-form-urlencoded MIME type. Before using them in your application, you must decode them.

EDIT: URIUtil is no longer available in more recent versions, better answer at Java - encode URL or by Mr. Sindi in this thread.


URIUtil of Apache httpclient is really useful, although there are some alternatives

URIUtil.encodeQuery(url);

For example, it encodes space as "+" instead of "%20"

Both are perfectly valid in the right context. Although if you really preferred you could issue a string replace.

Encoding URL query parameters in Java, URLEncoder is the way to go. You only need to keep in mind to encode only the individual query string parameter name and/or value, not the entire URL,  URL encoding makes the transmitted data more reliable and secure. URL Encoding a Query string or Form parameter in Java Java provides a URLEncoderclass for encoding any query string or form parameter into URL encoded format. The following example demonstrates how to use URLEncoder.encode()method to perform URL encoding in Java.

Unfortunately, URLEncoder.encode() does not produce valid percent-encoding (as specified in http://tools.ietf.org/html/rfc3986#section-2.1).

URLEncoder.encode() encodes everything just fine, except space is encoded to "+". All the Java URI encoders that I could find only expose public methods to encode the query, fragment, path parts etc. - but don't expose the "raw" encoding. This is unfortunate as fragment and query are allowed to encode space to +, so we don't want to use them. Path is encoded properly but is "normalized" first so we can't use it for 'generic' encoding either.

Best solution I could come up with:

return URLEncoder.encode(raw, "UTF-8").replaceAll("\\+", "%20");

If replaceAll() is too slow for you, I guess the alternative is to roll your own encoder...

EDIT: I had this code in here first which doesn't encode "?", "&", "=" properly:

//don't use - doesn't properly encode "?", "&", "="
new URI(null, null, null, raw, null).toString().substring(1);

Java URL encoding of query string parameters, This Java tutorial describes how to encode URL parameters using the GET method, parameter names and their values get submitted on the URL string after a  URLEncoder should be the way to go. You only need to keep in mind to encode only the individual query string parameter name and/or value, not the entire URL, for sure not the query string parameter separator character & nor the parameter name-value separator character =.

It is not necessary to encode a colon as %3B in the query, although doing so is not illegal.

URI         = scheme ":" hier-part [ "?" query ] [ "#" fragment ]
query       = *( pchar / "/" / "?" )
pchar         = unreserved / pct-encoded / sub-delims / ":" / "@"
unreserved    = ALPHA / DIGIT / "-" / "." / "_" / "~"
pct-encoded   = "%" HEXDIG HEXDIG
sub-delims    = "!" / "$" / "&" / "'" / "(" / ")" / "*" / "+" / "," / ";" / "="

It also seems that only percent-encoded spaces are valid, as I doubt that space is an ALPHA or a DIGIT

look to the URI specification for more details.

How do I encode URL parameters? - Web Tutorials, Say I have a URL http://example.com/query?q= and I have a query entered by the user such URI/URL objects but none of them come out  In Java Examples, when using the GET method, parameter names and their values get submitted on the URL string after a question mark. Different parameter name/value pairs are separated by ampersands. Usually, parameters are accessed from a request in an already decoded format (via request.getParameter () ), so no decoding is necessary.

The built in Java URLEncoder is doing what it's supposed to, and you should use it.

A "+" or "%20" are both valid replacements for a space character in a URL. Either one will work.

A ":" should be encoded, as it's a separator character. i.e. http://foo or ftp://bar. The fact that a particular browser can handle it when it's not encoded doesn't make it correct. You should encode them.

As a matter of good practice, be sure to use the method that takes a character encoding parameter. UTF-8 is generally used there, but you should supply it explicitly.

URLEncoder.encode(yourUrl, "UTF-8");

Java URL encoding of query string parameters, Only encode the individual query string parameter value or portion of the URI (​path segment). Let us have another example with multiple query  assertThat (testUrl, is (encodedURL)); The encode method accepts two parameters: data – string to be translated. encodingScheme – name of the character encoding. This encode method converts the string into application/x-www-form-urlencoded format.

How to encode or decode a URL string in Java, In Java Examples, when using the GET method, parameter names and their values get submitted on the URL string after a question mark. Different parameter​. A URL String or form parameters can be encoded using the URLEncoder class – static encode (String s, String enc) method. For example, when a user enters following special characters, and your web application doesn’t handle encoding, it will caused cross site script attack.

Java: How to Encode or Decode URL String Or Form Parameter , The encode method of URLEncoder takes two arguments: The first argument defines the URL to be encoded. The second argument defines the  Java Provides a URLDecoder class containing a method named decode(). It takes a URL encoded string and a character encoding as arguments and decodes the string using the supplied encoding. Java URL Decoding example. Learn how to decode any URL encoded query string or form parameter in Java.

URL Encoding and Decoding Using Java, A URL String or form parameters can be encoded using the URLEncoder class – static encode (String s, String enc) method. For example, when  URL encoding stands for encoding certain characters in a URL by replacing them with one or more character triplets that consist of the percent character "%" followed by two hexadecimal digits. The two hexadecimal digits of the triplet(s) represent the numeric value of the replaced character.

Comments
  • This question looks useful: stackoverflow.com/questions/444112/…
  • the structure of the query part is server-dependent, though most expect application/x-www-form-urlencoded key/value pairs. See here for more: illegalargumentexception.blogspot.com/2009/12/…
  • I mentioned that I didn't think that does url encoding, instead it encodes data to be submitted via a form. comments?
  • That's because URLEncoder is conformed to application/x-www-form-urlencoded MIME format (which is a valid HTML form encoding). I'm assuming that's not what you're looking for.
  • I ended up using URLEncoder.encode and replacing "+" with "%20"
  • It encodes slashes to "%2F", shouldn't it leave the URL slashes as they are?
  • @golimar No, it shouldn't. You are supposed to give it parameter value only and not the whole URL. Consider example http://example.com/?url=http://example.com/?q=c&sort=name. Should it encode &sort=name or not? There is no way to distinguish value from the URL. That is the exact reason why you need value encoding in the first place.
  • I would have to agree. Use HttpClient, you will be much happier.
  • That look promising, got a link by chance? I'm googling but finding many.
  • This method doesn't seem to be present in HttpClient 4.1? hc.apache.org/httpcomponents-client-ga/httpclient/apidocs/org/…
  • @Alex, hmm that's annoying, I've always used that routine with good results. One idea is to grab the source code from the 3 release since they now obviously didn't want to maintain it anymore.