英文:
Retrieving the name of the method from which HTTP call was made using an Interceptor
问题
我正在使用 Spring 的 ClientHttpRequestInterceptor 来捕获我应用程序中的所有外发 HTTP 调用,以便记录数据。除了在拦截器中已经收集的数据之外,我还想以某种方式获取发起 HTTP 调用的函数名称。例如,如果一个名为 getStuffFromUrl
的方法使用 Spring RestTemplate 进行如下的 HTTP 调用,
public String getStuffFromUrl() {
...
return restTemplate.exchange(url, HttpMethod.GET,entity, String.class).getBody();
}
当我在拦截器中捕获这个外发的 HTTP 调用时,我希望能够同时检索到方法 getStuffFromUrl
的名称。我应该如何实现这个目标呢?
英文:
I am using the Spring ClientHttpRequestInterceptor to capture all outgoing HTTP calls from my applications in order to log the data. In addition to the data that I am already collecting in the interceptor, I want to somehow fetch the name of the function from which the HTTP call originated. So, as an example, if a method called getStuffFromUrl
is making the HTTP call using the Spring RestTemplate as follows,
public String getStuffFromUrl() {
...
return restTemplate.exchange(url, HttpMethod.GET,entity, String.class).getBody();
}
when I capture this outbound HTTP call in my interceptor, I want to retrieve the name of the method getStuffFromUrl
as well. How could I go about doing this?
答案1
得分: 1
如果您被允许修改您的HTTP请求,一种方法是添加一个临时的HTTP标头来表示方法名:
public String getStuffFromUrl() {
HttpHeaders headers = new HttpHeaders();
headers.add("JavaMethod", "getStuffFromUrl");
entity = new Entity(headers)
...
return restTemplate.exchange(url, HttpMethod.GET, entity, String.class).getBody();
}
然后,在实际发送HTTP请求之前,您可以从ClientHttpRequestInterceptor中获取方法名并删除标头:
ClientHttpResponse intercept(HttpRequest request, byte[] body,
ClientHttpRequestExecution execution)
throws IOException {
String javaMethodName = "Unknown";
List<String> javaMethodHeader = request.getHeaders().remove("JavaMethod");
if (javaMethodHeader != null && javaMethodHeader.size() > 0) {
javaMethodName = javaMethodHeader.get(0);
}
log.info("Calling method = " + javaMethodName);
return execution.execute(request, body);
}
(提供的代码未经测试)
英文:
If you are allowed to modify your HTTP request, one way would be to add a ad-hoc HTTP header for the method name :
public String getStuffFromUrl() {
HttpHeaders headers = new HttpHeaders();
headers.add("JavaMethod", "getStuffFromUrl");
entity = new Entity(headers)
...
return restTemplate.exchange(url, HttpMethod.GET,entity, String.class).getBody();
}
You could then get back the method name and remove the header from within the ClientHttpRequestInterceptor prior the HTTP request is actualy sent out.
ClientHttpResponse intercept(HttpRequest request, byte[] body,
ClientHttpRequestExecution execution)
throws IOException {
String javaMethodName="Unknown";
List<String> javaMethodHeader = request.getHeaders().remove("JavaMethod");
if(javaMethodHeader!=null && javaMethodHeader.size()>0) {
javaMethodName = javaMethodHeader.get(0);
}
log.info("Calling method = "+ javaMethodName);
execution.execute(request, body);
}
(provided code not tested)
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论