Here this example will explain how to encode URL string in Java using URLEncoder. URLEncoder is a tool class that encodes HTML that can be decoded using methods in the URLDecoder class.
Source Code
package com.beginner.examples;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
public class URLEncoderTest {
public static void main(String[] args) {
String testStr = "I want something just like this";
try {
//Encode () methods in the URLEncoder class are used
String encoderStr = URLEncoder.encode(testStr, "utf-8");
System.out.println(encoderStr);
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
}
}
Output:
I+want+something+just+like+this
References
Imported packages in Java documentation: