Home > Back-end >  How can i set Header map in case of custom HTTP Request in java?
How can i set Header map in case of custom HTTP Request in java?

Time:07-09

I was using java.net.http package to create custom request. i could set additional headers to pass but can't set a header map in the request, is there any way i can do this in this particular way of making http request, or in any other method of making request.

HttpRequest.newBuilder()
.uri(URI.create(targetUrl)
.setHeader("Content-Type", "application/json")
.method(myMethod, HttpRequest.BodyPublishers.ofString(body))
.build();

I want to set HeaderMap => Map<String,List> just like we are setting a single header above.

It would be great if anyone could help me in this.

CodePudding user response:

The HttpRequestBuilder doesn't allow a direct set of the Map<String, List<String>> into the headers nor exposes an equivalent of putAll.

However, provided you have a Map<String, List<String>> called yourHeaders, then you can simply do the following:

HttpRequest.Builder builder = HttpRequest.newBuilder()
  .uri(URI.create(targetUrl)
  .setHeader("Content-Type", "application/json")
  .method(myMethod, HttpRequest.BodyPublishers.ofString(body));

yourHeaders.forEach((headerKey, headerValues) -> headerValues.forEach(value -> builder.header(headerKey, value)));

return builder.build();
  • Related