【发布时间】:2019-04-26 07:15:52
【问题描述】:
我有这个 Spring Rest API 端点:
@PostMapping(value = "/v1/", consumes = { MediaType.APPLICATION_XML_VALUE,
MediaType.APPLICATION_JSON_VALUE }, produces = { MediaType.APPLICATION_XML_VALUE,
MediaType.APPLICATION_JSON_VALUE })
public PaymentResponse handleMessage(@RequestBody PaymentTransaction transaction, HttpServletRequest request) throws Exception {
// get here plain XML
}
XML 模型。
@XmlRootElement(name = "payment_transaction")
@XmlAccessorType(XmlAccessType.FIELD)
public class PaymentTransaction {
public enum Response {
failed_response, successful_response
}
@XmlElement(name = "transaction_type")
public String transactionType;
.........
}
如何以纯 XML 文本获取 XML 请求?
我也尝试过使用 Spring 拦截器: 我试过这段代码:
@SpringBootApplication
@EntityScan("org.plugin.entity")
public class Application extends SpringBootServletInitializer implements WebMvcConfigurer {
@Override
protected SpringApplicationBuilder configure(SpringApplicationBuilder application) {
return application.sources(Application.class);
}
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
........
@Bean
public RestTemplate rsestTemplate() {
List<ClientHttpRequestInterceptor> interceptors = new ArrayList<>();
RestTemplate restTemplate = new RestTemplate(
new BufferingClientHttpRequestFactory(new SimpleClientHttpRequestFactory()));
restTemplate.setInterceptors(interceptors);
return restTemplate;
}
}
记录组件:
@Component
public class RestTemplateHeaderModifierInterceptor implements ClientHttpRequestInterceptor {
@Override
public ClientHttpResponse intercept(HttpRequest request, byte[] body, ClientHttpRequestExecution execution)
throws IOException {
StringBuilder sb = new StringBuilder();
sb.append("[ ");
for (byte b : body) {
sb.append(String.format("0x%02X ", b));
}
sb.append("]");
System.out.println("!!!!!!!!!!!!!!!");
System.out.println(sb.toString());
ClientHttpResponse response = execution.execute(request, body);
InputStream inputStream = response.getBody();
String result = IOUtils.toString(inputStream, StandardCharsets.UTF_8);
System.out.println("!!!!!!!!!!!!!!!");
System.out.println(result);
return response;
}
}
但是没有任何东西打印到控制台中。知道我哪里错了吗?可能这个组件没有注册?
【问题讨论】:
-
我认为你的拦截器工作不正常。无论如何,我认为使用拦截器进行日志记录有点过头了。你确定这是你想要的吗?
-
您真的希望请求是纯文本还是只是想转换或以其他方式转换 xml?如果您想以纯文本形式接收,您将无法使用 XML 或使用任何约定而不是使用 XML 的配置优势,而无需将其作为文本接收,然后将其转换为 XML,然后再转换回文本。我只是想澄清一下。你也可以提供一个样本请求
-
@ChrisMaggiulli 我想记录一切。不仅是 XML,还有请求尝试。你能给出一些如何实施的建议吗?
-
你看过this older的答案吗?看起来它回答了几乎相同的问题。
-
你忘了给
interceptors添加拦截器@list
标签: java spring rest spring-restcontroller spring-rest