Manually set the request header information when calling the feign interface

A demand scenario:

Some parameters in our provider service are obtained from the request header, but when the consumer service calls the feign interface, there are no parameters required by the provider in the interface request header itself. At this time, we want to manually set some parameters to the feign interface!

Two solutions

2.1 Add the @RequestHeader annotation to the feign interface

This method is to obtain the required parameters before executing the method, and then pass the retrieved values ​​as parameters to the method to be executed.

The Feign interface called by this method needs to be modified. Add an annotation with @RequestHeader in the parameters. This annotation means that the variables are placed in the request header instead of the request parameters or request body.

Insert image description here

2.2 The provider normally obtains parameters from the request header

    @GetMapping("getName")
    public Void getMerchantCompareInfo(@RequestParam(value = "name") String name,HttpServletRequest request) {
    
    
        String token = request.getHeader("token");
        String token2 = request.getHeader("X-TOKEN");
        System.out.println("token = " + token);
        System.out.println("X-TOKEN = " + token2);
        return null;
    }

2. 3 consumer manually transfers parameters

    @GetMapping("getName")
    public Void getMerchantCompareInfo() {
    
    
        feignParamApi.getMerchantCompareInfo("name","12344");
        return null;
    }

2.4 Testing

Insert image description here
If we specify the request header parameter name in @RequestHeader, then we also need to use the corresponding name when retrieving it.

Reference link
Feign request header setting/transmission issues (Synchronous method setting Header/Asynchronous method setting Header)

Guess you like

Origin blog.csdn.net/weixin_43811057/article/details/133066180