Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get request header in spring boot

How do I get the header and body of the current request from an application which called my Springboot application? I need to extract this information. Unfortunately this does not work. I tried to get the current request with this code sample (https://stackoverflow.com/a/26323545/5762515):

public static HttpServletRequest getCurrentHttpRequest(){
    RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes();
    if (requestAttributes instanceof ServletRequestAttributes) {
        HttpServletRequest request = ((ServletRequestAttributes)requestAttributes).getRequest();
        return request;
    }
    throw new IllegalArgumentException("Request must not be null!");
}

And then I tried to get the body

ContentCachingRequestWrapper requestWrapper = (ContentCachingRequestWrapper) currentRequest;
    String requestBody = new String(requestWrapper.getContentAsByteArray());

Can someone tell me what im doing wrong? Thanks in advance

like image 366
TryHard Avatar asked Sep 05 '25 03:09

TryHard


2 Answers

@RestController
public class SampleController {

    @PostMapping("/RestEndpoint")
    public ResponseEntity<?> sampleEndpoint(@RequestHeader Map<String, String> headers,@RequestBody Map<String,String> body) {
        //Do something with header / body
        return null;
    }
}

If the application's are communicating through a rest endpoint I believe this would be the simplest solution. In spring you can add RequestHeader and RequestBody annotations to method arguments to have them setup to be used.

Of course you can map RequestBody directly to some POJO instead of using a map but just as an example.

Let me know if this is what you were looking for !

like image 161
Briano Bruno Avatar answered Sep 07 '25 22:09

Briano Bruno


you can get header with your code but need apply some changes.

private String getRequest() throws Exception {
        RequestAttributes attribs = RequestContextHolder.getRequestAttributes();
        if (attribs != null) {
            HttpServletRequest request = ((ServletRequestAttributes) attribs).getRequest();
            return request ;
        }
        
        throw new IllegalArgumentException("Request must not be null!");
}

after you can extract header info from request. For example if you want get Accept-Encoding

String headerEncoding = getRequest().getHeader("Accept-Encoding");

obliviusly you don't use this approce if not necessary.

If you want exract the body NOT use this solution

like image 27
Kemot 90 Avatar answered Sep 07 '25 21:09

Kemot 90