I am trying to get a list of all headers sent in a http request in a Micronaut @Controller.
Asked
Active
Viewed 5,388 times
2 Answers
1
You need to add a variable of type io.micronaut.http.HttpHeaders
to your API endpoint parameters. Give this a shot:
import io.micronaut.http.annotation.Controller;
import io.micronaut.http.annotation.Get;
import io.micronaut.http.HttpResponse;
@Controller
public class TestController {
@Get("/test/http-headers")
public HttpResponse<String> getHttpHeaders(HttpHeaders headers) {
for (val header : headers.entrySet()) {
// Do stuff with header.getKey() and header.getValue()
}
return HttpResponse.ok("Testing");
}
}
Latest docs on HttpHeaders
: https://docs.micronaut.io/latest/api/io/micronaut/http/HttpHeaders.html#method.summary

Mass Dot Net
- 2,150
- 9
- 38
- 50
-1
https://docs.micronaut.io/latest/guide/index.html#requestResponse
import io.micronaut.http.HttpRequest;
import io.micronaut.http.HttpResponse;
import io.micronaut.http.annotation.Controller;
import io.micronaut.http.annotation.Get;
@Controller("/request")
public class MessageController {
@Get("/hello")
public HttpResponse<String> hello(HttpHeaders headers) {
// deal with the headers
return HttpResponse.ok("Hello world!!")
.header("X-My-Header", "Foo");
}
}
https://docs.micronaut.io/latest/api/io/micronaut/http/HttpHeaders.html

IEE1394
- 1,181
- 13
- 33
-
I don't think that code sample shows how to get a list of all request headers. That code sample appears to be setting a response header. – Jeff Scott Brown Jun 18 '20 at 13:19
-
Jeff look carefully. The headers are injected as method parameter. I assume accessing the header is obvious – IEE1394 Jun 18 '20 at 13:23
-
"I assume accessing the header is obvious" - Are you proposing that `headers.iterator()` be invoked to return an iterator that can be interacted with? – Jeff Scott Brown Jun 18 '20 at 14:00
-
Either that or you use a getAll on headers.. Depends a lot what he want to achieve. – IEE1394 Jun 18 '20 at 14:03
-
3Right. I don't think those are necessarily obvious. I think your answer would be more helpful if you included that code. – Jeff Scott Brown Jun 18 '20 at 14:04
-
Well feel free to add it ;-) thing for me is, that he do not specify what to do with the headers – IEE1394 Jun 18 '20 at 14:08
-
"Well feel free to add it" - I don't think it is appropriate for me to add code to your answer. I expect these comments may be helpful. If OP still wants clarification I can help. Thanks for submitting an answer. – Jeff Scott Brown Jun 18 '20 at 17:39