1

I want to generate a Get query string in java like so

www.example.com/somethingToGet?key1=value&key2=value....

So my method has 2 parameters the base url(www.example.com/somethingToGet) is the first argument and the 2nd argument is a map data structure. I want to iterate over the map and generate a string like so

key1=value&key2=value....

It shouldn't end with ampersand. I don't want to use any built in functions, I want to know the logic how such strings are generated.

2 Answers 2

1

Something like this:

public static String getQuery(String base, java.util.Map<String, String> map) {
    StringBuilder str = new StringBuilder(base);
    str.append('?');
    boolean first = true;
    for (java.util.Map.Entry<String, String> e : map.entrySet()) {
        if (first)
            first = false;
        else
            str.append('&');
        str.append(e.getKey());
        str.append('=');
        str.append(e.getValue());
    }
    return str.toString();
}
Sign up to request clarification or add additional context in comments.

Comments

0

You can also use the format method in URLEncoder class from the Apache HttpComponents library to create a query string. As per the documentation it

Returns a String that is suitable for use as an application/x-www-form-urlencoded list of parameters in an HTTP PUT or HTTP POST.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.