最近使用 SpringBoot 項目,把一些 http 請求轉為 使用 feign方式。但是遇到一個問題:個別請求是要設置header的。
於是,查看官方文檔和博客,大致推薦兩種方式。也可能是我沒看明白官方文檔。
接口如下:
@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. 使用Headers注解。直接在請求上或者在類上添加
這種方式經過嘗試,沒有作用。暫時不清楚原因。
2. 通過實現RequestInterceptor接口,完成對所有的Feign請求,設置Header
@Component
public class FeginClientConfig {
@Bean
public RequestInterceptor headerInterceptor() {
return new RequestInterceptor() {
@Override
public void apply(RequestTemplate requestTemplate) {
// 小示例,沒什么卵用
requestTemplate.header("Content-Type", "application/json");
}
};
}
@Bean
public Logger.Level level() {
return Logger.Level.FULL;
}
}
這種方式,是針對所有feign請求進行攔截,設置Header,不適於我的需求。
后來發現其實我的思路走偏了。咨詢了一個同事,既然使用的是RequestMapping注解。那么直接使用RequestMapping注解的header屬性就可以了。如下:
@RequestMapping(value = "/xx", method = RequestMethod.POST, headers = {"content-type=application/x-www-form-urlencoded"})
有一點需要注意:content-type=application/x-www-form-urlencoded。此時,方法里接收的參數,就不能直接是一個對象(Map等)。不然還是會默認
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;
