Encode a URL

In this chapter you will learn:

  1. How to encode space for URL
  2. Encode % percentage for URL
  3. Encode plus sign for URL
  4. URLEncoder: slashes
  5. 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:

  1. Decode a URL with URLDecoder
  2. Decode a URL with parameters
Home » Java Tutorial » URL URI
URL
URL Creation
URL for jar file
URL Components
Convert file path to URL
URL Relative
URL Protocol
Read from URL
Compare URL
URLConnection
HTTP Header
URLConnection Post
Cookie
URLConnection Read
HttpURLConnection
HttpURLConnection Properties
HttpURLConnection proxy
HttpURLConnection Authenticator
HTTPS
JarURLConnection
Encode a URL
Decode a URL
URI
URI Normalization
URI Resolution
URI Relativization
Convert URI to URL
IP Address
IP Ping
NetworkInterface