🧠 What is URL Encoding?
✅ URL encoding is the process of translating special characters in a URL into a format that can be safely transmitted over the Internet.
In URLs:
- Only letters, digits, and a few special characters (
-,_,.,~) are allowed as-is. - Spaces, symbols (
@,#,?,=,/, etc.) must be encoded.
🔵 Encoding replaces unsafe characters with a % followed by two hexadecimal digits.
✅ Example:
| Character | Encoded as |
|---|---|
| Space () | %20 |
@ | %40 |
: | %3A |
/ | %2F |
? | %3F |
& | %26 |
🎯 Why do we need URL encoding?
- To safely pass data inside URLs without confusion.
- To avoid breaking the URL structure.
- To transmit non-ASCII characters (like
ü,ç,你好) safely over HTTP.
If you don’t encode properly:
- URLs can get corrupted.
- Parameters might be misinterpreted.
⚙️ How to Do URL Encoding in Java
✅ Java provides a built-in class: java.net.URLEncoder
Example:
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
public class UrlEncodeExample {
public static void main(String[] args) {
String original = "Hello World! @2024";
String encoded = URLEncoder.encode(original, StandardCharsets.UTF_8);
System.out.println(encoded);
}
}
✅ Output:
Hello+World%21+%402024
🔵 Note:
- Spaces become
+(inapplication/x-www-form-urlencoded). - Special characters are encoded as
%XX.
🛠️ Important:
- Always specify the character encoding (usually
UTF-8). - Don’t forget to decode later if needed using
URLDecoder.decode()!
import java.net.URLDecoder;
String decoded = URLDecoder.decode(encoded, StandardCharsets.UTF_8);
System.out.println(decoded); // back to "Hello World! @2024"
🔥 Example: Sending data safely in a query parameter
Suppose you want to create a link like:
https://example.com/search?query=Hello World! @2024
✅ Correct way:
String query = "Hello World! @2024";
String encodedQuery = URLEncoder.encode(query, StandardCharsets.UTF_8);
String url = "https://example.com/search?query=" + encodedQuery;
System.out.println(url);
Result:
https://example.com/search?query=Hello+World%21+%402024
🛡️ Warning:
| Situation | Correct Approach |
|---|---|
| Encoding full URL | ❌ Don’t encode the whole URL blindly (only parameters!) |
| Encoding query parameters | ✅ Always encode values (key/value parts) |
| Encoding path segments | ✅ Encode separately if needed |
🚀 Quick Summary
| Concept | Meaning |
|---|---|
| URL Encoding | Convert unsafe characters in a URL into safe %XX format |
| Java class | URLEncoder.encode(String, Charset) |
| Common encoding | UTF-8 |
| Also decode | Use URLDecoder.decode() when needed |