Put parameters into query string in a predictable order

Previously, the order of query parameters depended on the iteration order of items in a Set.
This order is undefined for some Sets. Nevertheless, unit test for createQueryString expected
that query parameters are in a particular order.
This commit is contained in:
Jiri Danek 2016-03-31 23:18:17 +02:00 committed by jbertram
parent 01d6e26081
commit 2788eaa1bf
2 changed files with 9 additions and 6 deletions

View File

@ -463,7 +463,7 @@ public class URISupport {
/**
* Given a key / value mapping, create and return a URI formatted query string that is valid and
* can be appended to a URI.
* can be appended to a URI. Query parameters in the string are sorted by key.
*
* @param options The Mapping that will create the new Query string.
* @return a URI formatted query string.
@ -472,9 +472,12 @@ public class URISupport {
public static String createQueryString(Map<String, ? extends Object> options) throws URISyntaxException {
try {
if (options.size() > 0) {
StringBuffer rc = new StringBuffer();
StringBuilder rc = new StringBuilder();
boolean first = true;
for (String key : options.keySet()) {
List<String> keys = new ArrayList<String>();
keys.addAll(options.keySet());
Collections.sort(keys);
for (String key : keys) {
if (first) {
first = false;
}

View File

@ -114,12 +114,12 @@ public class URIParserTest {
System.out.println("queryString2: " + queryString);
Assert.assertEquals("key1=value1", queryString);
query.put("key2", "value2");
query.put("key3", "value3");
queryString = URISupport.createQueryString(query);
System.out.println("queryString3: " + queryString);
Assert.assertEquals("key1=value1&key2=value2", queryString);
Assert.assertEquals("key1=value1&key3=value3", queryString);
query.put("key3", "value3");
query.put("key2", "value2");
queryString = URISupport.createQueryString(query);
System.out.println("queryString4: " + queryString);
Assert.assertEquals("key1=value1&key2=value2&key3=value3", queryString);