Encode a URL
In this chapter you will learn:
- How to encode space for URL
- Encode % percentage for URL
- Encode plus sign for URL
- URLEncoder: slashes
- Encode symbols for URL
Encode space for URL
URLEncoder
declares the following class method for encoding a string:
String encode(String s, String enc)
import java.net.URLEncoder;
//from ja v a2 s .c om
public class MainClass {
public static void main(String[] args) throws Exception {
System.out.println(URLEncoder.encode("http://java2s.com/A B C", "UTF-8"));
}
}
The code above generates the following result.
Encode % percentage for URL
import java.net.URLEncoder;
//from jav a 2 s . com
public class MainClass {
public static void main(String[] args) throws Exception {
System.out.println(URLEncoder.encode("http://java2s.com/A%B%C", "UTF-8"));
}
}
The code above generates the following result.
Encode plus sign for URL
import java.net.URLEncoder;
/*j a va 2 s. c om*/
public class Main {
public static void main(String[] args) throws Exception {
System.out.println(URLEncoder.encode("http://java2s.com/A+B+C", "UTF-8"));
}
}
The code above generates the following result.
URLEncoder: slashes
import java.net.URLEncoder;
/* ja v a2s . c o m*/
public class MainClass {
public static void main(String[] args) throws Exception {
System.out.println(URLEncoder.encode("http://java2s.com/A/B/C/", "UTF-8"));
}
}
The code above generates the following result.
Encode symbols for URL
import java.net.URLEncoder;
//ja v a 2 s . c om
public class MainClass {
public static void main(String[] args) throws Exception {
System.out.println(URLEncoder.encode("A\"B\"C\"D\"E", "UTF-8"));
System.out.println(URLEncoder.encode("A:B:C:D", "UTF-8"));
System.out.println(URLEncoder.encode("A~B~C~D", "UTF-8"));
System.out.println(URLEncoder.encode("A(B)C(D)", "UTF-8"));
System.out.println(URLEncoder.encode("A.B.C.E", "UTF-8"));
System.out.println(URLEncoder.encode("A=B=C=D=E", "UTF-8"));
System.out.println(URLEncoder.encode("A&B&C&D", "UTF-8"));
}
}
The code above generates the following result.
Next chapter...
What you will learn in the next chapter:
Home » Java Tutorial » URL URI