Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Determine HTTP Version of incoming RequestEntity in SpringBoot 2.1

I am trying to fetch the HTTP Version from an incoming http request in Spring (Spring Boot 2.1.4 specifically). Meaning the HTTP 1.1 part as defined as "HTTP-Version" in the "Request-Line" in RFC2616: https://www.rfc-editor.org/rfc/rfc2616#section-5.1. Spring's RequestEntity seems to have all sorts of functionality to fetch url, path, headers, etc but not this. The official docs are not helping either.

Consider the following code:

@RestController
@RequestMapping("/")
public class MyController
{
    @GetMapping("/")
    @ResponseBody
    public ResponseEntity<String> getSomething(RequestEntity requestEntity)
    {
        // access HTTP Version number of incoming RequestEntity ***HERE***

When printing the headers of an incoming request like

Map<String, String> headers = requestEntity.getHeaders().toSingleValueMap();
Object[] keys = headers.keySet().toArray();

for(int i=0; i< headers.size(); i++) {
    System.out.println(keys[i].toString() + ": " + headers.get(keys[i].toString()));
}

(excuse my dirty logging code), I get the ACTUAL headers, such as

host: localhost:8888
connection: keep-alive
cache-control: max-age=0
upgrade-insecure-requests: 1
user-agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14_4) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/74.0.3729.108 Safari/537.36
dnt: 1
accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3
accept-encoding: gzip, deflate, br
accept-language: en-US,en;q=0.9,de;q=0.8

Still, there seems no way to tickle the HTTP Version number out of a RequestEntity.

Is there one though?

like image 634
Xenonite Avatar asked Oct 19 '25 09:10

Xenonite


2 Answers

RequestEntity is a high level representation of a request that allows you to conveniently have access to the payload in object form. What you're after is a far more low level attribute of a request that normally a REST endpoint shouldn't have to bother itself with.

You can inject the HttpServletRequest instance and that gives you access to the protocol.

@GetMapping("/")
@ResponseBody    
public ResponseEntity<String> getSomething(RequestEntity requestEntity,
                                           HttpServletRequest request) {

  log.info("HTTP protocol: " + request.getProtocol());

  ...
}
like image 143
Gimby Avatar answered Oct 21 '25 22:10

Gimby


Thank you @Gimby. Also found the following option:

String httpVersion = ((ServletRequestAttributes) RequestContextHolder.currentRequestAttributes()).getRequest().getProtocol;
like image 44
Xenonite Avatar answered Oct 22 '25 00:10

Xenonite



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!