Java URL encoding of query string parameters

To URL encode the query string parameters of a URL in Java, you can use the URLEncoder class from the java.net package.

The URLEncoder class provides static methods for encoding a string using the application/x-www-form-urlencoded MIME format. This is the format used by the application/x-www-form-urlencoded media type, which is used to submit HTML form data to a server.

Here is an example of how you can use the URLEncoder class to URL encode the query string parameters of a URL in Java:

import java.net.URLEncoder;

public class URLEncoderExample {
  public static void main(String[] args) {
    // Set the query string parameters
    String param1 = "value1";
    String param2 = "value2";
    String param3 = "value3";

    // URL encode the query string parameters
    String encodedParam1 = URLEncoder.encode(param1, "UTF-8");
    String encodedParam2 = URLEncoder.encode(param2, "UTF-8");
    String encodedParam3 = URLEncoder.encode(param3, "UTF-8");

    // Construct the URL with the encoded query string parameters
    String url = "http://example.com/path?" +
        "param1=" + encodedParam1 +
        "&param2=" + encodedParam2 +
        "&param3=" + encodedParam3;

    System.out.println(url);
  }
}

This example sets the query string parameters to value1, value2, and value3, and then URL encodes each parameter using the encode() method of the URLEncoder class. It specifies the UTF-8 encoding as the second parameter to the encode() method.

The encoded parameters are then used to construct the URL with the query string. The output of this example will be a URL with the encoded query string parameters, such as http://example.com/path?param1=value1&param2=value2&param3=value3.

Note that the URLEncoder class is designed to encode the query string parameters of a URL, but it is not suitable for encoding the entire URL. To encode the entire URL, you can use the URLEncoder.encode() method to encode each part of the URL separately. For example:

import java.net.URLEncoder;

public class URLEncoderExample {
  public static void main(String[] args) {
    // Set the URL parts
    String scheme = "http";
    String host = "example.com";
    String path = "/path";
    String query = "param1=value1&param2=value2&param3=value3";

    // URL encode the URL parts
    String encodedScheme = URLEncoder.encode(scheme, "UTF-8");
    String encodedHost = URLEncoder.encode(host, "UTF-8");
    String encodedPath = URLEncoder