我想创建一个接收 POST 发送的 XML 字符串的 REST API 方法。我正在使用Swagger Editor自上而下设计我的 REST API 并生成服务器存根代码。
我的 POST 方法如下所示swagger.yaml
:
/models:
post:
summary: Store a model.
description: Stores the XML content of the specified model.
consumes:
- application/xml;charset=UTF-8
parameters:
- name: model
in: body
description: The model XML you want to store
schema:
type: string
required: true
responses:
201:
description: Model stored successfully
headers:
location:
description: URL of the stored model.
type: string
我在 yaml 文件中也有这个全局设置:
produces:
- application/json
当我使用 Swagger Editor 的Generate Server > Spring菜单选项时,会为 POST 方法生成以下接口方法:
@ApiOperation(value = "Store a model.", notes = "Stores the XML content of the specified model.", response = Void.class, tags={ })
@ApiResponses(value = {
@ApiResponse(code = 201, message = "Model stored successfully", response = Void.class) })
@RequestMapping(value = "/models",
produces = { "application/json" },
consumes = { "application/xml;charset=UTF-8" },
method = RequestMethod.POST)
ResponseEntity<Void> modelsPost(
@ApiParam(value = "The model XML you want to store" ,required=true ) @RequestBody String model);
这是相应的存根实现:
public ResponseEntity<Void> modelsPost(
@ApiParam(value = "The model XML you want to store" ,required=true ) @RequestBody String model
) {
// do some magic!
return new ResponseEntity<Void>(HttpStatus.OK);
}
我使用 Postman 将一些虚拟 XML 发布到我正在运行的 Springboot 服务上的方法中:
但是当我打印出model
实现方法内部的值时,log.debug("Model XML = " + model);
我在日志中得到如下输出:
Model XML = ------WebKitFormBoundaryA3o70hOgLFoLLBoY
Content-Disposition: form-data; name="model"
<?xml version="1.0" encoding="utf-8"?><Hello></Hello>
------WebKitFormBoundaryA3o70hOgLFoLLBoY--
如何将 XML 本身转化为 的值model
?在这个例子中,我希望它是这样的:
<?xml version="1.0" encoding="utf-8"?><Hello></Hello>
请记住,我不能直接编辑 Java 方法签名,因为 Swagger 编辑器正在生成它们。如果我的招摇定义是错误的,我应该使用什么来发布 XML 字符串?
实际上,XML 可能很大,因此不能将其作为请求参数发送。我也不打算处理 XML,因此可以将其视为字符串。