How to URL Encode a String in Java
2 minsProgrammers often need to perform URL encoding on query strings or form parameters while calling a remote api. URL encoding makes the transmitted data more reliable and secure.
URL Encoding a Query string or Form parameter in Java
Java provides a URLEncoder class 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.
Pitfall to avoid: Do not encode the entire URL. Encode only the query string and path segment.
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.io.UnsupportedEncodingException;
class URLEncodingExample {
// Method to encode a string value using `UTF-8` encoding scheme
private static String encodeValue(String value) {
try {
return URLEncoder.encode(value, StandardCharsets.UTF_8.toString());
} catch (UnsupportedEncodingException ex) {
throw new RuntimeException(ex.getCause());
}
}
public static void main(String[] args) {
String baseUrl = "https://www.google.com/search?q=";
String query = "Hellö Wörld@Java";
String encodedQuery = encodeValue(query); // Encoding a query string
String completeUrl = baseUrl + encodedQuery;
System.out.println(completeUrl);
}
}
# Output
https://www.google.com/search?q=Hell%C3%B6+W%C3%B6rld%40Java
Note that Java’s URLEncoder
class encodes space character(" "
) into a +
sign. This is contrary to other languages like Javascript that encode space character into %20
.
Check out this StackOverflow discussion to learn what it means to encode the space character into %20
or +
sign.
The encode()
function takes the encoding to be used as the second parameter. In our example, we’re using UTF-8
encoding scheme. The world wide web consortium recommends that you use UTF-8
encoding scheme whenever possible to avoid incompatibilities.
An UnsupportedEncodingException
is thrown if the encoding is not supported.
Also Read: URL Decoding in Java