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.
Guide to Java URL Encoding/Decoding
The Kubernetes ecosystem is huge and quite complex, so it’s easy to forget about costs when trying out all of the exciting tools.
To avoid overspending on your Kubernetes cluster, definitely have a look at the free K8s cost monitoring tool from the automation platform CAST AI. You can view your costs in real time, allocate them, calculate burn rates for projects, spot anomalies or spikes, and get insightful reports you can share with your team.
Connect your cluster and start monitoring your K8s costs right away:
We rely on other people’s code in our own work. Every day.
It might be the language you’re writing in, the framework you’re building on, or some esoteric piece of software that does one thing so well you never found the need to implement it yourself.
The problem is, of course, when things fall apart in production — debugging the implementation of a 3rd party library you have no intimate knowledge of is, to say the least, tricky.
Lightrun is a new kind of debugger.
It’s one geared specifically towards real-life production environments. Using Lightrun, you can drill down into running applications, including 3rd party dependencies, with real-time logs, snapshots, and metrics.
Learn more in this quick, 5-minute Lightrun tutorial:
Slow MySQL query performance is all too common. Of course it is. A good way to go is, naturally, a dedicated profiler that actually understands the ins and outs of MySQL.
The Jet Profiler was built for MySQL only, so it can do things like real-time query performance, focus on most used tables or most frequent queries, quickly identify performance issues and basically help you optimize your queries.
Critically, it has very minimal impact on your server’s performance, with most of the profiling work done separately — so it needs no server changes, agents or separate services.
Basically, you install the desktop application, connect to your MySQL server, hit the record button, and you’ll have results within minutes:
DbSchema is a super-flexible database designer, which can take you from designing the DB with your team all the way to safely deploying the schema.
The way it does all of that is by using a design model, a database-independent image of the schema, which can be shared in a team using GIT and compared or deployed on to any database.
And, of course, it can be heavily visual, allowing you to interact with the database using diagrams, visually compose queries, explore the data, generate random data, import data or build HTML5 database reports.
The Kubernetes ecosystem is huge and quite complex, so it’s easy to forget about costs when trying out all of the exciting tools.
To avoid overspending on your Kubernetes cluster, definitely have a look at the free K8s cost monitoring tool from the automation platform CAST AI. You can view your costs in real time, allocate them, calculate burn rates for projects, spot anomalies or spikes, and get insightful reports you can share with your team.
Connect your cluster and start monitoring your K8s costs right away:
We’re looking for a new Java technical editor to help review new articles for the site.
1. Overview
Simply put, URL encoding translates special characters from the URL to a representation that adheres to the spec and can be correctly understood and interpreted.
In this tutorial, we’ll focus on how to encode/decode the URL or form data so that it adheres to the spec and transmits over the network correctly.
2. Analyze the URL
Let’s first look at a basic URI syntax:
scheme:[//[user:[email protected]]host[:port]][/]path[?query][#fragment]
The first step into encoding a URI is examining its parts and then encoding only the relevant portions.
Now let’s look at an example of a URI:
String testUrl = "http://www.baeldung.com?key1=value+1&key2=value%40%21%242&key3=value%253";
One way to analyze the URI is loading the String representation to a java.net.URI class:
@Test public void givenURL_whenAnalyze_thenCorrect() throws Exception
The URI class parses the string representation URL and exposes its parts via a simple API, e.g., getXXX.
3. Encode the URL
When encoding URI, one of the common pitfalls is encoding the complete URI. Typically, we need to encode only the query portion of the URI.
Let’s encode the data using the encode(data, encodingScheme) method of the URLEncoder class:
private String encodeValue(String value) < return URLEncoder.encode(value, StandardCharsets.UTF_8.toString()); >@Test public void givenRequestParam_whenUTF8Scheme_thenEncode() throws Exception < MaprequestParams = new HashMap<>(); requestParams.put("key1", "value 1"); requestParams.put("key2", "[email protected]!$2"); requestParams.put("key3", "value%3"); String encodedURL = requestParams.keySet().stream() .map(key -> key + "=" + encodeValue(requestParams.get(key))) .collect(joining("&", "http://www.baeldung.com?", "")); assertThat(testUrl, is(encodedURL));
The encode method accepts two parameters:
The encoding scheme will convert special characters into two digits hexadecimal representation of eight bits that will be represented in the form of “%xy“. When we are dealing with path parameters or adding parameters that are dynamic, we will encode the data and then send to the server.
Note: The World Wide Web Consortium Recommendation states that we should use UTF-8. Not doing so may introduce incompatibilities. (Reference: https://docs.oracle.com/javase/7/docs/api/java/net/URLEncoder.html)
4. Decode the URL
Let’s now decode the previous URL using the decode method of the URLDecoder:
There are two important points to remember here:
If we were to decode and then analyze, URL portions might not be parsed correctly. If we used another encoding scheme to decode the data, it would result in garbage data.
5. Encode a Path Segment
We can’t use URLEncoder for encoding path segments of the URL. Path component refers to the hierarchical structure that represents a directory path, or it serves to locate resources separated by “/”.
Reserved characters in path segments are different than in query parameter values. For example, a “+” sign is a valid character in path segments and therefore should not be encoded.
To encode the path segment, we use the UriUtils class by Spring Framework instead.
UriUtils class provides encodePath and encodePathSegment methods for encoding path and path segment respectively:
private String encodePath(String path) < try < path = UriUtils.encodePath(path, "UTF-8"); >catch (UnsupportedEncodingException e) < LOGGER.error("Error encoding parameter <>", e.getMessage(), e); > return path; >
@Test public void givenPathSegment_thenEncodeDecode() throws UnsupportedEncodingException < String pathSegment = "/Path 1/Path+2"; String encodedPathSegment = encodePath(pathSegment); String decodedPathSegment = UriUtils.decode(encodedPathSegment, "UTF-8"); assertEquals("/Path%201/Path+2", encodedPathSegment); assertEquals("/Path 1/Path+2", decodedPathSegment); >
In the above code snippet, we can see that when we used the encodePathSegment method, it returned the encoded value, and + is not encoded because it is a value character in the path component.
Let’s add a path variable to our test URL:
String testUrl = "/path+1?key1=value+1&key2=value%40%21%242&key3=value%253";
And to assemble and assert a properly encoded URL, we’ll change the test from Section 2:
String path = "path+1"; String encodedURL = requestParams.keySet().stream() .map(k -> k + "=" + encodeValue(requestParams.get(k))) .collect(joining("&", "/" + encodePath(path) + "?", "")); assertThat(testUrl, CoreMatchers.is(encodedURL));
6. Conclusion
In this article, we saw how to encode and decode the data so that it can be transferred and interpreted correctly.
While the article focused on encoding/decoding URI query parameter values, the approach applies to HTML form parameters as well.
As always, the source code is available over on GitHub.
Slow MySQL query performance is all too common. Of course it is. A good way to go is, naturally, a dedicated profiler that actually understands the ins and outs of MySQL.
The Jet Profiler was built for MySQL only, so it can do things like real-time query performance, focus on most used tables or most frequent queries, quickly identify performance issues and basically help you optimize your queries.
Critically, it has very minimal impact on your server’s performance, with most of the profiling work done separately — so it needs no server changes, agents or separate services.
Basically, you install the desktop application, connect to your MySQL server, hit the record button, and you’ll have results within minutes:
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.