In every web application, it is a common requirement to include some parameters in the HTTP requests. In most cases, these parameters are retrieved from the database and stored internally in some data structures, such as maps. In this article, we will see how to convert a Map to a URL query string in Java.

Convert map to URL query string

We can use the java.net.URLEncoder class to encode query string parameters. To convert a Map to the URL query string, we need to iterate through the map’s key-value pairs, encode them, and concatenate them with appropriate separators.

Following is an example of how to convert map to URL query string

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.Map;

public class MapToQueryStringExample {
    public static void main(String[] args) {
        // Create a sample Map
        Map<String, String> queryParams = Map.of(
            "param1", "value1",
            "param2", "value2",
            "param3", "value3"
        );

        String queryString = mapToQueryString(queryParams);
        System.out.println("Query String: " + queryString);
    }

    public static String mapToQueryString(Map<String, String> params) {
        StringBuilder result = new StringBuilder();
        for (Map.Entry<String, String> entry : params.entrySet()) {
            if (result.length() > 0) {
                result.append("&");
            }
            try {
                result.append(URLEncoder.encode(entry.getKey(), "UTF-8"))
                      .append("=")
                      .append(URLEncoder.encode(entry.getValue(), "UTF-8"));
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }
        }
        return result.toString();
    }
}

In the above example, the mapToQueryString() method iterates through the key-value pairs in the map, and encodes them using URLEncoder, and appends them to the result StringBuilder with appropriate separators.

Following is the output that we get after executing the above program.

Query String: param1=value1&param2=value2&param3=value3

References:

https://docs.oracle.com/javase/8/docs/api/java/net/URLEncoder.html

Categorized in:

Tagged in: