我有一个Spring应用程序,其中有多个服务通过REST进行通信。
想象简单
@RestController
内部调用另一个剩余端点。
当服务A调用服务B spring httpRequest时,例如[POST] / api / test / serviceb。有没有办法获取此类请求的父URL /端点?我想在服务B中知道谁打电话给它。如何在Spring中获得这些信息?
我写了Interceptor,它拦截了每个其余的调用,但不知道如何为每个调用获取父URL。
public class AuditRestInterceptor implements ClientHttpRequestInterceptor{
@Override
public ClientHttpResponse intercept(HttpRequest request, byte[] body, ClientHttpRequestExecution exec)
throws IOException {
// TODO any way to find out who call it ?
}
}
编辑: 我使用 HandlerInterceptorAdapter 重写了拦截器,该拦截器可以访问 HttpServletRequest
public class AuditRestInterceptor extends HandlerInterceptorAdapter implements HandlerInterceptor {
private static Logger log = LoggerFactory.getLogger(AuditRestInterceptor.class);
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
String referer = request.getHeader("Referer");
log.info(referer); // return null
return true;
}
我尝试过像这样的简单通话:
@RestController
@RequestMapping(value = "/api/runtime/case")
public class CaseController {
@Autowired
private CaseService caseService;
@RequestMapping(value = "/{cidla}", method = RequestMethod.GET)
public CaseDto load(@PathVariable("cidla") String cidla) {
return caseService.load(cidla);
}
}
CaseService像这样调用另一个端点:
@Component
public class CaseServiceImpl implements CaseService {
@Autowired
private RestTemplate restTemplate;
@Override
public CaseDto load(String cidla) {
String host = "http://localhost:8080";
restTemplate.getForObject(host + "/smart/api/runtime/case/{cidla}/record", RecordDto.class, cidla);
Case c = loadCase(cidla);
return transformCase(c);
}
}
期望的行为-第一次调用 / api / runtime / case / {cidla} 应该将父URL返回为null(我称之为),然后再次调用 / smart / api / runtime / case / {cidla} / record 应该返回 / api / runtime / case / {cidla} ,因为caseServiceImpl调用了它。
我拦截了第二次调用并尝试
String referer = request.getHeader("Referer");
但它将返回null。
答案 0 :(得分:1)
尝试一下:
URL url = new URL(request.getHeader("Referer")); //where request is the HttpServletRequest
System.out.println(url.getPath());