Prince Bhati
Prince Bhati

Reputation: 105

How do i access the http header in rest API

i'm using the @Request header to access the header , when i'm running , i found that i'm unable to access the values of header using map function, when i try to print the value of headers.get("externalId") it return null, even when i'm passing the value of externalId in postman. can anyone please describe , how can i access the http header and use the specific value to pass them in a function. And another thing when , i tried to print whole header , System.out.println(header), its printing ,the whole header.

 @GetMapping("transactionDetails")
            TransactionResponse getTransactionDetailsByExternalId(@RequestHeader Map<String,String> headers){
                if(headers.containsKey("externalId"))
                return transactionService.getTransactionDetailsByExternalId(headers.get("externalId");
            }

Upvotes: 2

Views: 2716

Answers (2)

Gary Liao
Gary Liao

Reputation: 81

I think there's nothing wrong to get headers by using @RequestHeader.

I can get all my headers normally, including a 'externalId' header.

This is console from my Postman. enter image description here

And this is my System.out.println of the Map headers from SpringBoot console. enter image description here

Everything is working fine.
Maybe check your spelling ?
If it wasn't spelling issue, check Postman console and make sure what Request Headers does it sends out.

And sorry for not having enough reputation yet to show image directly.

Upvotes: 1

learner
learner

Reputation: 314

Another way is to get from "HttpServletRequest". And request.getHeader("HEADER_NAME")

GetMapping("transactionDetails")
            TransactionResponse getTransactionDetailsByExternalId(@HttpServletRequest request){

 String externalId = request.getHeader("externalId");

.
.
.
.
}

Upvotes: 2

Related Questions