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.
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.
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;
import java.nio.charset.StandardCharsets;
public class URLEncoderExample {
public static void main(String[] args) {
// Set the query string parameters
String param1 = "hello world";
String param2 = "a=b";
String param3 = "test&foo";
// URL encode the query string parameters
String encodedParam1 = URLEncoder.encode(param1, StandardCharsets.UTF_8);
String encodedParam2 = URLEncoder.encode(param2, StandardCharsets.UTF_8);
String encodedParam3 = URLEncoder.encode(param3, StandardCharsets.UTF_8);
// Construct the URL with the encoded query string parameters
String url = "http://example.com/path?" +
"param1=" + encodedParam1 +
"¶m2=" + encodedParam2 +
"¶m3=" + encodedParam3;
System.out.println(url);
}
}This example sets the query string parameters to hello world, a=b, and test&foo, and then URL encodes each parameter using the encode() method of the URLEncoder class. It specifies StandardCharsets.UTF_8 as the encoding parameter.
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=hello+world¶m2=a%3Db¶m3=test%26foo.
Note that the URLEncoder class is designed to encode query string parameters, not entire URLs. Encoding the scheme, host, or path with URLEncoder will break the URL structure. To properly construct a URL with encoded components, use java.net.URI instead. For example:
import java.net.URI;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.net.URISyntaxException;
public class URLEncoderExample {
public static void main(String[] args) {
// Set the URL parts
String scheme = "http";
String host = "example.com";
String path = "/path";
// Encode query values before passing to URI
String query = "param1=" + URLEncoder.encode("hello world", StandardCharsets.UTF_8) +
"¶m2=" + URLEncoder.encode("a=b", StandardCharsets.UTF_8);
// Use URI to properly construct and encode the URL
try {
URI uri = new URI(scheme, null, host, -1, path, query, null);
System.out.println(uri.toASCIIString());
} catch (URISyntaxException e) {
e.printStackTrace();
}
}
}When handling multiple values for the same parameter key, encode each value separately and join them with & (e.g., key=val1&key=val2).