How to Convert Map to Url Query String

How to convert map to url query string?

The most robust one I saw off-the-shelf is the URLEncodedUtils class from Apache Http Compoments (HttpClient 4.0).

The method URLEncodedUtils.format() is what you need.

It doesn't use map so you can have duplicate parameter names, like,

  a=1&a=2&b=3

Not that I recommend this kind of use of parameter names.

Dart: convert map into query string

Can you describe your usage a bit? First off, keeping data such as password in a GET request is not good practice. This is something that would better off being a POST request. That said, if you do want to use it as a POST request to send the map the server, take a look at: HttpRequest.postFormData it will automatically add the Map you provide as the POST data to the server. One caveat to remember is that data must be a Map (or keys and values must be strings). Example usage:

import 'dart:html';
// ...

// Somewhere in your login related method
HttpRequest.postFormData('login.php', data).then((HttpRequest req) {
if(req.status != 200) {
print(req.statusText);
}
});

There is a package available for server-side Dart which allows you to easily compose hand deal with various HTTP request, aptly named http. However this does not work with Client side scripts. I'm not aware of any existing packages which would provide the functionality you're looking for.

On that note, if you do decide to roll your own, perhaps provide a pull request to the QueryString project you mentioned in your question so that functionality can become available to others in one simple package.

Convert Map to QueryString

You can define a method mapToueryString by yourself as:

  StringBuilder sb = new StringBuilder();
for(HashMap.Entry<String, String> e : queryString.entrySet()){
if(sb.length() > 0){
sb.append('&');
}
sb.append(URLEncoder.encode(e.getKey(), "UTF-8")).append('=').append(URLEncoder.encode(e.getValue(), "UTF-8"));
}

How to convert map to URL query string in Clojure/Compojure/Ring?

Yes, there is a utility for this already that doesn't involve Hiccup or rolling your own string/join/URLEncoder function:

user=> (ring.util.codec/form-encode {:foo 1 :bar 2 :baz 3})
"foo=1&bar=2&baz=3"
user=>

Compojure depends on ring/ring-core, which includes ring.util.codec, so you already have it.

Convert HashMap into String with keys and values

You can use streams:

String result = map.entrySet().stream()
.map(e -> e.getKey() + "=" + e.getValue())
.collect(Collectors.joining("&"));

Note: You should probably use an url encoding. First create a helper method like this:

public static String encode(String s){
try{
return java.net.URLEncoder.encode(s, "UTF-8");
} catch(UnsupportedEncodingException e){
throw new IllegalStateException(e);
}
}

And then use that inside of your stream to encode the key and value:

String result = map.entrySet().stream()
.map(e -> encode(e.getKey()) + "=" + encode(e.getValue()))
.collect(Collectors.joining("&"));

How to generate query string in golang?

You almost got it. Call Values.Encode() to encode the map in URL-encoded form.

fmt.Print(q.Encode()) // another_thing=foobar&api_key=key_from_environment_or_flag

Create the map directly instead of using req.URL.Query() to return an empty map:

values := url.Values{}
values.Add("api_key", "key_from_environment_or_flag")
values.Add("another_thing", "foobar")
query := values.Encode()

Use strings.NewReader(query) to get an io.Reader for the POST request body.

Parse a URI String into Name-Value Collection

If you are looking for a way to achieve it without using an external library, the following code will help you.

public static Map<String, String> splitQuery(URL url) throws UnsupportedEncodingException {
Map<String, String> query_pairs = new LinkedHashMap<String, String>();
String query = url.getQuery();
String[] pairs = query.split("&");
for (String pair : pairs) {
int idx = pair.indexOf("=");
query_pairs.put(URLDecoder.decode(pair.substring(0, idx), "UTF-8"), URLDecoder.decode(pair.substring(idx + 1), "UTF-8"));
}
return query_pairs;
}

You can access the returned Map using <map>.get("client_id"), with the URL given in your question this would return "SS".

UPDATE URL-Decoding added

UPDATE As this answer is still quite popular, I made an improved version of the method above, which handles multiple parameters with the same key and parameters with no value as well.

public static Map<String, List<String>> splitQuery(URL url) throws UnsupportedEncodingException {
final Map<String, List<String>> query_pairs = new LinkedHashMap<String, List<String>>();
final String[] pairs = url.getQuery().split("&");
for (String pair : pairs) {
final int idx = pair.indexOf("=");
final String key = idx > 0 ? URLDecoder.decode(pair.substring(0, idx), "UTF-8") : pair;
if (!query_pairs.containsKey(key)) {
query_pairs.put(key, new LinkedList<String>());
}
final String value = idx > 0 && pair.length() > idx + 1 ? URLDecoder.decode(pair.substring(idx + 1), "UTF-8") : null;
query_pairs.get(key).add(value);
}
return query_pairs;
}

UPDATE Java8 version

public Map<String, List<String>> splitQuery(URL url) {
if (Strings.isNullOrEmpty(url.getQuery())) {
return Collections.emptyMap();
}
return Arrays.stream(url.getQuery().split("&"))
.map(this::splitQueryParameter)
.collect(Collectors.groupingBy(SimpleImmutableEntry::getKey, LinkedHashMap::new, mapping(Map.Entry::getValue, toList())));
}

public SimpleImmutableEntry<String, String> splitQueryParameter(String it) {
final int idx = it.indexOf("=");
final String key = idx > 0 ? it.substring(0, idx) : it;
final String value = idx > 0 && it.length() > idx + 1 ? it.substring(idx + 1) : null;
return new SimpleImmutableEntry<>(
URLDecoder.decode(key, StandardCharsets.UTF_8),
URLDecoder.decode(value, StandardCharsets.UTF_8)
);
}

Running the above method with the URL

https://stackoverflow.com?param1=value1¶m2=¶m3=value3¶m3

returns this Map:

{param1=["value1"], param2=[null], param3=["value3", null]}


Related Topics



Leave a reply



Submit