溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務(wù)條款》

Spring使用feign時怎么設(shè)置header信息

發(fā)布時間:2021-08-04 10:52:06 來源:億速云 閱讀:388 作者:chen 欄目:開發(fā)技術(shù)

這篇文章主要介紹“Spring使用feign時怎么設(shè)置header信息”,在日常操作中,相信很多人在Spring使用feign時怎么設(shè)置header信息問題上存在疑惑,小編查閱了各式資料,整理出簡單好用的操作方法,希望對大家解答”Spring使用feign時怎么設(shè)置header信息”的疑惑有所幫助!接下來,請跟著小編一起來學(xué)習(xí)吧!

Spring feign時設(shè)置header信息

最近使用 SpringBoot 項目,把一些 http 請求轉(zhuǎn)為 使用 feign方式。但是遇到一個問題:個別請求是要設(shè)置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注解。直接在請求上或者在類上添加

這種方式經(jīng)過嘗試,沒有作用。暫時不清楚原因。

2. 通過實現(xiàn)RequestInterceptor接口,完成對所有的Feign請求,設(shè)置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請求進行攔截,設(shè)置Header,不適于我的需求。

后來發(fā)現(xiàn)其實我的思路走偏了。咨詢了一個同事,既然使用的是RequestMapping注解。那么直接使用RequestMapping注解的header屬性就可以了。如下:

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

有一點需要注意:content-type=application/x-www-form-urlencoded。此時,方法里接收的參數(shù),就不能直接是一個對象(Map等)。不然還是會默認(rèn)

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;

Feign動態(tài)設(shè)置Header

Feign調(diào)用接口:

/**
 * @author Liangzhifeng
 * date: 2018/9/13
 */
public interface UserInfoFeignClient {

    /**
     * 根據(jù)token獲取用戶信息
     * @param token
     * @return
     */
    @RequestMapping(value = "/user/info/1.0", method = RequestMethod.POST)
    Object getUserInfoByToken(@RequestParam("token") String token);
}

/**
 * @author Liangzhifeng
 * date: 2018/9/15
 */
@Component
public class AuthorityConfig {

    /**
     * 授權(quán)信息Header的key
     */
    public static final String OAUTH_KEY = "token";

    /**
     * 授權(quán)信息Header的值的前綴
     */
    public static final String OAUTH_VALUE_PREFIX = "Bearer ";

	// GlobalConstant.AUTHORITY_SERVICE_LINK  : 服務(wù)的名稱

    @Autowired
    private Client client;

    public UserInfoFeignClient userInfoFeignClient(String token) {
        UserInfoFeignClient authorityServiceLoginInvoker = Feign.builder().client(client)
                .encoder(new GsonEncoder())
                .decoder(new GsonDecoder())
                .contract(new SpringMvcContract())
                .requestInterceptor(template -> template.header(OAUTH_KEY, OAUTH_VALUE_PREFIX + token))
                .target(UserInfoFeignClient.class, GlobalConstant.AUTHORITY_SERVICE_LINK);
        return authorityServiceLoginInvoker;
    }
}

接口調(diào)用:

@Autowired
private AuthorityConfig authorityConfig;

/**
 * 根據(jù)token獲取用戶信息
 *
 * @param token 用戶登錄的授權(quán)token
 * @return 用戶信息JSON
 */
public Object getUserInfo(String token) {
    try {
        Object userInfo = authorityConfig.userInfoFeignClient(token).getUserInfoByToken(token);
        return userInfo;
    } catch (Exception e) {
        log.info("獲取用戶信息異常", e);
        return null;
    }
}

到此,關(guān)于“Spring使用feign時怎么設(shè)置header信息”的學(xué)習(xí)就結(jié)束了,希望能夠解決大家的疑惑。理論與實踐的搭配能更好的幫助大家學(xué)習(xí),快去試試吧!若想繼續(xù)學(xué)習(xí)更多相關(guān)知識,請繼續(xù)關(guān)注億速云網(wǎng)站,小編會繼續(xù)努力為大家?guī)砀鄬嵱玫奈恼拢?/p>

向AI問一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進行舉報,并提供相關(guān)證據(jù),一經(jīng)查實,將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI