How to modify Http headers before executing reques

2019-07-15 16:33发布

问题:

I have multiple rest endpoints. userId (http header) is common in all endpoints. I want to apply a logic, let say set its default value if not provided or trim it if is provided in request before request enters the method (for eg: heartbeat). How can we achieve this in spring boot rest mvc.

@RestController
public class MyResource {



        @RequestMapping(value = "/heartbeat", method= RequestMethod.GET)
        public String heartbeat (@RequestHeader (value="userId", required=false) String userId) 
        {
           ...
        }
    }

回答1:

First of all, you shouldn't use http headers this way. In your situation storing userId in session be much more preferable.

Although your goal can be achieved by using interceptors. Here's example of setting a header to every request:

import java.io.IOException;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpRequest;
import org.springframework.http.client.ClientHttpRequestExecution;
import org.springframework.http.client.ClientHttpRequestInterceptor;
import org.springframework.http.client.ClientHttpResponse;

public class XUserAgentInterceptor implements ClientHttpRequestInterceptor {

    @Override
    public ClientHttpResponse intercept(
            HttpRequest request, byte[] body, ClientHttpRequestExecution execution)
            throws IOException {

        HttpHeaders headers = request.getHeaders();
        headers.add("X-User-Agent", "My App v2.1");
        return execution.execute(request, body);
    }
}