@FeignClient 情況下header的傳遞方法,RestTemplate情況下Header傳遞方法


        今天因為要調用另一個服務,因為我們用的是SpringCloud框架,所以通過Fegin調用,正好另一方服務有權限校驗,需要傳遞token和設備ID,這兩個參數都需要放到Header中,

用 @RequestHeader 這個注解實現,可以看到下面兩個服務的代碼, 我的是三個參數,另一方服務是一個參數,實際上另一方服務接口方法所在的類上有個@IamPermissions注解,就是用來攔截用的,所以雖然參數個數不一致,但是@RequestHeader注解只是在Header里,我剛開始還挺迷惑的,事實上這樣是可行的,一個是放在body里,一個是header里。

 

我的服務的代碼:

@FeignClient("xxx-xxx-xxx")
public interface CompensationOrderService {

    /**
     * 下單
     * @param form
     * @return
     */
    @PostMapping(value = "/xxx-xxx-xxx/v1-0/xxx/xxxx")
    @ResponseBody
    Result addOrders(@Valid @RequestBody OrderForm form,
                             @RequestHeader(value = "X-CHJ-Token")String token,
                             @RequestHeader(value = "X-CHJ-Deviceid")String deviceid);

 

另一方服務接口代碼:

    @ApiOperation("下訂單")
    @PostMapping("/orders")
    @ApiResponses({
        @ApiResponse(code = MusicCode.MUSIC_VIP_PRODUCT_NOT_EXIST_CODE, message = MusicCode.MUSIC_VIP_PRODUCT_NOT_EXIST_DESC),
        @ApiResponse(code = MusicCode.MUSIC_VIP_ORDER_CODE_IS_REPEAT_CODE, message = MusicCode.MUSIC_VIP_ORDER_CODE_IS_REPEAT_DESC)}
    )
    public Result<String> addOrders(@Valid @RequestBody OrderForm form) {

 

      另一個是使用注入RestTemplate ,創建HttpHeaders 對象, 寫入header信息,  調用  postForEntity即可

@Service
@AllArgsConstructor
public class DemoService {

    @Autowired
    private RestTemplate restTemplate;

    中間代碼省略。。。。。。。。。。。 public SendVo sendMessage(){

        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON_UTF8);
        headers.set("Authorization",send_token);
        headers.set("Accept","application/json");

        Map<String,Object> map = new HashMap<String, Object>(2);

        Map<String, Object> mapJson = new HashMap<String, Object>(7);
        mapJson.put("type","oa");
        mapJson.put("title","title,釘釘推送消息demo測試完成,哈哈哈");
        mapJson.put("content",",釘釘推送消息demo測試完成,content-哈哈哈");
        mapJson.put("link","https://www.lixiang.com");
        mapJson.put("userid","dongpengju|chenwei");
        mapJson.put("mobile","13522396988");
        mapJson.put("need_sso",true);
        mapJson.put("in_dingding",true);

        map.put("message",Arrays.asList(mapJson));
        map.put("source","umu");

        HttpEntity httpEntity = new HttpEntity(map,headers);

        ResponseEntity<SendVo> postForEntity = this.restTemplate.postForEntity(send_url,httpEntity, SendVo.class);
        return  postForEntity.getBody();
    }

}

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM