Spring uses feign to set header information

Recently, I used the SpringBoot project to convert some http requests to feign. But there is a problem: individual requests need to set headers.

Therefore, check the official documents and blogs, and generally recommend two methods. It may also be that I did not understand the official documentation.

The interface is as follows:

@FeignClient(url = "XX_url", value = "XXService")
public interface XXService {

    @RequestMapping(value = "/xx", method = RequestMethod.POST)
    @Headers({"Content-Type: application/json","Accept: application/json"})
    String sendDing(String params);
}

  

1. Use the Headers annotation. Add directly on the request or on the class

Tried this way and it didn't work. The reason is not yet clear.

2. By implementing the RequestInterceptor interface, complete all Feign requests and set the Header

@Component
public class FeginClientConfig {
    @Bean
    public RequestInterceptor headerInterceptor() {
        return new RequestInterceptor() {
            @Override
            public void apply(RequestTemplate requestTemplate) {
                    // small example, useless
                    requestTemplate.header("Content-Type", "application/json");
            }
        };
    }

    @Bean
    public Logger.Level level() {
        return Logger.Level.FULL;
    }

}
            

  This method is to intercept all feign requests and set Header, which is not suitable for my needs.

 

I found out later that my thinking had gone wrong. I consulted a colleague, since the RequestMapping annotation is used. Then you can directly use the header attribute of the RequestMapping annotation. as follows:

@RequestMapping(value = "/xx", method = RequestMethod.POST, headers = {"content-type=application/x-www-form-urlencoded"})

  One thing to note: content-type=application/x-www-form-urlencoded. At this point, the parameters received in the method cannot be directly an object (Map, etc.). Otherwise, it will default to

content-type为 application/json.
@RequestMapping(value = "/xx", method = RequestMethod.POST, headers = {"content-type=application/x-www-form-urlencoded"})
String login(@RequestParam("username") String username, @RequestParam("password") String password;

  

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325040720&siteId=291194637