I'm building a HttpRequest with where I want to supply the request with a map of headers: Map<String, List<String>>.
Problem
The HttpRequest builder only takes headers as a key(String) value(String) and not as whole map. How can I supply the contents of the map to the headers in the builder?
HttpRequest httpRequest = java.net.http.HttpRequest.newBuilder()
.uri(URI.create("google.com"))
.headers("String", "String")
.GET()
.build();
The docs say there is another ovlerload headers(String... headers). It Adds the given name value pairs to the set of headers for this request. The supplied String instances must alternate as header names and header values. To add several values to the same name then the same name must be supplied with each new value.
You'd need to convert the map Map<String, List<String>>, say {"a" -> (1,2), "b"->3} to a String[] {"a", 1, "a", 2, "b", 3}}
Flattening the map to the array should work like this:
public static String[] flattenMap(Map<String, List<String>> m) {
return m.entrySet().stream().flatMap(x ->
x.getValue().stream().flatMap(y -> Stream.of(x.getKey(), y)))
.toArray(String[]::new);
}
Or
public static HttpRequest.Builder addHeaders(HttpRequest.Builder builder, Map<String, List<String>> headers) {
for (Map.Entry<String, List<String>> e : headers.entrySet()) {
for (String value : e.getValue()) {
builder.header(e.getKey(), value);
}
}
return builder;
}
With less flatMap 'magic' :-)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With