- Url encode with java
- Method Summary
- Methods declared in class java.lang.Object
- Method Detail
- encode
- encode
- encode
- Class URLEncoder
- Method Summary
- Methods declared in class java.lang.Object
- Method Details
- encode
- encode
- encode
- How to URL Encode a String in Java
- How to encode or decode a URL string in Java
- You might also like.
Url encode with java
For example using UTF-8 as the encoding scheme the string «The string ü@foo-bar» would get converted to «The+string+%C3%BC%40foo-bar» because in UTF-8 the character ü is encoded as two bytes C3 (hex) and BC (hex), and the character @ is encoded as one byte 40 (hex).
Method Summary
Methods declared in class java.lang.Object
Method Detail
encode
@Deprecated public static String encode(String s)
The resulting string may vary depending on the platform’s default encoding. Instead, use the encode(String,String) method to specify the encoding.
Translates a string into x-www-form-urlencoded format. This method uses the platform’s default encoding as the encoding scheme to obtain the bytes for unsafe characters.
encode
public static String encode(String s, String enc) throws UnsupportedEncodingException
Translates a string into application/x-www-form-urlencoded format using a specific encoding scheme. This method behaves the same as encode(java.lang.String,java.nio.charset.Charset) except that it will look up the charset using the given encoding name.
encode
public static String encode(String s, Charset charset)
Translates a string into application/x-www-form-urlencoded format using a specific Charset. This method uses the supplied charset to obtain the bytes for unsafe characters. Note: The World Wide Web Consortium Recommendation states that UTF-8 should be used. Not doing so may introduce incompatibilities.
Report a bug or suggest an enhancement
For further API reference and developer documentation see the Java SE Documentation, which contains more detailed, developer-targeted descriptions with conceptual overviews, definitions of terms, workarounds, and working code examples.
Java is a trademark or registered trademark of Oracle and/or its affiliates in the US and other countries.
Copyright © 1993, 2023, Oracle and/or its affiliates, 500 Oracle Parkway, Redwood Shores, CA 94065 USA.
All rights reserved. Use is subject to license terms and the documentation redistribution policy.
Class URLEncoder
Utility class for HTML form encoding. This class contains static methods for converting a String to the application/x-www-form-urlencoded MIME format. For more information about HTML form encoding, consult the HTML specification.
- The alphanumeric characters » a » through » z «, » A » through » Z » and » 0 » through » 9 » remain the same.
- The special characters » . «, » — «, » * «, and » _ » remain the same.
- The space character » » is converted into a plus sign » + «.
- All other characters are unsafe and are first converted into one or more bytes using some encoding scheme. Then each byte is represented by the 3-character string » %xy «, where xy is the two-digit hexadecimal representation of the byte. The recommended encoding scheme to use is UTF-8. However, for compatibility reasons, if an encoding is not specified, then the default charset is used.
For example using UTF-8 as the encoding scheme the string «The string ü@foo-bar» would get converted to «The+string+%C3%BC%40foo-bar» because in UTF-8 the character ü is encoded as two bytes C3 (hex) and BC (hex), and the character @ is encoded as one byte 40 (hex).
Method Summary
Methods declared in class java.lang.Object
Method Details
encode
The resulting string may vary depending on the default charset. Instead, use the encode(String,String) method to specify the encoding.
Translates a string into x-www-form-urlencoded format. This method uses the default charset as the encoding scheme to obtain the bytes for unsafe characters.
encode
Translates a string into application/x-www-form-urlencoded format using a specific encoding scheme. This method behaves the same as encode(String s, Charset charset) except that it will look up the charset using the given encoding name.
encode
Translates a string into application/x-www-form-urlencoded format using a specific Charset. This method uses the supplied charset to obtain the bytes for unsafe characters. Note: The World Wide Web Consortium Recommendation states that UTF-8 should be used. Not doing so may introduce incompatibilities.
Report a bug or suggest an enhancement
For further API reference and developer documentation see the Java SE Documentation, which contains more detailed, developer-targeted descriptions with conceptual overviews, definitions of terms, workarounds, and working code examples. Other versions.
Java is a trademark or registered trademark of Oracle and/or its affiliates in the US and other countries.
Copyright © 1993, 2023, Oracle and/or its affiliates, 500 Oracle Parkway, Redwood Shores, CA 94065 USA.
All rights reserved. Use is subject to license terms and the documentation redistribution policy.
How to URL Encode a String in Java
Programmers 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.
How to encode or decode a URL string in Java
It is a common practice to URL encode the query strings or form parameters while calling a remote web service to avoid cross-site attacks. URL encoding converts a string into a valid URL format that makes the transmitted data more reliable and secure.
In this article, you will learn how to URL encode or decode query strings and form parameters using Java.
You can easily encode a URL string or a form parameter into a valid URL format by using the URLEncoder class in Java. This utility class contains static methods for converting a string into the application/x-www-form-urlencoded MIME format. The following example shows how to use the URLEncoder.encode() method to perform URL encoding in Java:
try // base url String baseURL = "https://www.google.com/search?q="; // query string String query = "Dankeschön für Ihre €100"; // URL encode query string String encodeStr = URLEncoder.encode(query, StandardCharsets.UTF_8.name()); // final url String url = baseURL + encodeStr; // print the url System.out.println(url); > catch (UnsupportedEncodingException ex) ex.printStackTrace(); >
https://www.google.com/search?q=Dankesch%C3%B6n+f%C3%BCr+Ihre+%E2%82%AC100
- str — The string to be encoded.
- encodingScheme — The name of the character encoding. In the above example, we used the UTF-8 encoding scheme. The World Wide Web Consortium recommends that the UTF-8 encoding scheme should be used whenever possible to avoid incompatibilities. If the given encoding is not supported, an UnsupportedEncodingException is thrown.
Common Pitfall: When performing URL encoding, don’t encode the entire URL. Only encode the individual query string parameter value or portion of the URI (path segment).
Let us have another example with multiple query string parameters encoding:
// request parameters MapString, String> params = new HashMap>(); params.put("name", "John @ Doe"); params.put("email", "john.doe@example.com"); params.put("password", "$34!%N!(d"); params.put("phone", "+1 (4566) 788-565"); // create a URL encoded string String encodedURL = params.entrySet().stream() .map(entry -> try return entry.getKey() + "=" + URLEncoder.encode(entry.getValue(), StandardCharsets.UTF_8.name()); > catch (UnsupportedEncodingException e) e.printStackTrace(); > return ""; >) .collect(Collectors.joining("&", "http://example.com?", "")); // print the url System.out.println(encodedURL);
Here is how the output looks like:
http://example.com?password=%2434%21%25%26%2378%21%28d&phone=%2B1+%284566%29+788-565&name=John+%40+Doe&email=john.doe%40example.com
- The alphanumeric characters ( a-z , A-Z , and 0-9 ) remain the same.
- The special characters . , — , * , and _ remain the same.
- The white space character » » is converted into a + sign. This is opposite to other programming languages like JavaScript which encodes the space character into %20 . But it is completely valid as the spaces in query string parameters are represented by + , and not %20 . The %20 is generally used to represent spaces in URI itself (the URL part before ? ).
- All other characters are considered unsafe and are first converted into one or more bytes using the given encoding scheme. Then each byte is represented by the 3-character string %XY , where XY is the two-digit hexadecimal representation of the byte.
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. The same is the case with query string parameters included in the URL. Mostly, these parameters are already decoded by the framework you’re using in your application like Spring or Express. But in a standalone Java application, you must manually decode query string and form parameters by using the URLDecoder utility class. The following example uses the URLDecoder.decode() method to perform URL decoding in Java:
try // encoded URL String encodedURL = "https://www.google.com/search?q=Dankesch%C3%B6n+f%C3%BCr+Ihre+%E2%82%AC100"; // decode URL String url = URLDecoder.decode(encodedURL, StandardCharsets.UTF_8.name()); // print the url System.out.println(url); > catch (UnsupportedEncodingException ex) ex.printStackTrace(); >
https://www.google.com/search?q=Dankeschön für Ihre €100
- str — The string to be decoded.
- encodingScheme — The name of the character encoding scheme. It is recommended to use the UTF-8 encoding to avoid incompatibilities with other systems.
The decoding process is the opposite of that used by the URLEncoder class. It is assumed that all characters in the encoded string are one of the following: a through z , A through Z , 0 through 9 , and — , _ , . , and * . The character % is permitted but is interpreted as the start of a special escaped sequence.
✌️ Like this article? Follow me on Twitter and LinkedIn. You can also subscribe to RSS Feed.