Fegin调用修改httpheader

修改httpheader目前知道的有两种方式。

通过在方法上加注解@RequestHeader

此种方式比较灵活,但是如果需要全部请求都需要带上相同的header,建议采用第二种方式。

第一种方式通过验证,第二种方式也试验过,但是我的需求是要求header头是动态变化的,所以第一种更加适合。

@FeignClient(name = "risk-service")
public interface RiskApiService {

    @PostMapping("/rule/call")
    RespResult<Object> call(@RequestHeader(name = "tr") String tr,
                            @RequestHeader(name = "cs") String cs,
                            @RequestHeader(name = "ci") String ci,
                            @RequestHeader(name = "contentType") String contentType,
                            @RequestBody @Valid RuleCallPO callPO);
}


    //使用 

      Map<String, Object> map = new HashMap<>();
        map.put("clientId", urUser.getId());
        map.put("applyId", "");
        o.setParams(map);
        String contentType = "application/json;charset=utf-8";
        log.info("调用风控参数{}", JSONObject.toJSONString(o));
        RespResult<Object> result = new RespResult<>();
        try {
            result = riskApiService.call(tr, cs, ci, contentType, o);
        } catch (Exception e) { }

通过全局拦截的方式

如果调用另一个服务的时候,前端传过来的token也要带过去,具体做法是写一个RequestInterceptor的实现类,在其apply方法里,根据当前线程获取request,取出里面的token,放到参数RequestTemplate中。

它的原理,根据之前说的feign源码,在SynchronousMethodHandler的invoke—>executeAndDecode—>Request request = targetRequest(template)中。

import feign.RequestInterceptor;
import feign.RequestTemplate;
import org.springframework.stereotype.Component;

@Component
public class FeignInterceptor implements RequestInterceptor{

    public void apply(RequestTemplate requestTemplate){
        requestTemplate.header("hotelId", "111111");
    }
}

猜你喜欢

转载自blog.csdn.net/gonghaiyu/article/details/107413536