我们正在使用Swagger编写REST API。我们有一个POST服务,它应该接受请求体中的XML文件。 这是我们的请求定义:
/services/invoke:
post:
tags:
- invoke
summary: A request invocation
operationId: invokeUsingPOST
consumes:
- application/xml
produces:
- application/xml
parameters:
- name: User-Token
in: header
description: The user token
required: false
type: string
- in: body
name: request
description: invoke request XML
required: false
schema:
type: string
responses:
'200':
description: OK
schema:
type: string
'400':
description: Bad Operation
'401':
description: Unauthorized
'404':
description: Forbidden
但是,当我们使用swagger-codegen生成Java客户端代码时,生成的方法如下所示:
public String invokeUsingPOST (String userToken, Request request)
Request类生成为:
@ApiModel(description = "")
@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2015-11-25T18:45:31.524+02:00")
public class Request {
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("class Request {\n");
sb.append("}");
return sb.toString();
}
}
如何使用它发送我的XML?我是否必须从中派生并覆盖toString()方法,或者有更好的方法吗?
答案 0 :(得分:1)
有一个错误,大约在2小时前解决了。请从Swagger-Codegen中提取最新信息,Java API客户端中的参数request
应该是字符串而不是模型。
答案 1 :(得分:0)
快速解决方法对我来说是添加另一个if if serialize方法来检查内容类型是否为“application / xml”
} else if (contentType.equals("application/xml")) {
SerializerUtils s = new SerializerUtils();
return s.serializeRequestBody(contentType, obj);
}
和SerializerUtils有这两种方法
public class SerializerUtils {
public Marshaller registerSerializer(Class<?> modelClass) throws JAXBException {
JAXBContext jaxbContext = JAXBContext.newInstance(modelClass);
Marshaller jaxbMarshaller = jaxbContext.createMarshaller();
jaxbMarshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE);
return jaxbMarshaller;
}
public RequestBody serializeRequestBody(String contentType, Object obj) {
StringWriter sw = new StringWriter();
try {
registerSerializer(obj.getClass()).marshal(obj, sw);
} catch (JAXBException e) {
e.printStackTrace();
}
return RequestBody.create(MediaType.parse(contentType), sw.toString());
}
这适用于我,我希望它有所帮助