我正在使用 netflix-feign 和 jackson 来创建 Mailgun API 的包装器。
问题是 API 要求 POST 请求带有 "Content-Type: application/x-www-form-urlencoded"
这是示例代码:
@RequestLine("POST /messages")
@Headers("Content-Type: application/x-www-form-urlencoded")
ResponseMessage sendMessage(Message message);
Message
对象包含必要的属性,并且它们具有 JSON 注释:
@JsonProperty(value = "from")
private String from;
问题是发送的对象是 JSON 对象:
{
"from" : "test@test.mailgun.org",
"to" : "atestaccount@gmail.com",
"subject" : "A test email",
"text" : "Hello this is the text of a test email.",
"html" : "<html><body><h1>Hello this is the html of a test email.</h1></body></html>"
}
但这不是有效的 x-www-form-urlencoded
内容类型。
有没有办法自动将对象序列化为正确的内容类型?
我认为我可以使用 @Body
注释,但为了使用它,我必须将不同的属性传递给 sendMessage
方法。
最佳答案
传递映射了 xml 内容的字符串
您只需在方法中发送一个之前已解析为 xml 的字符串即可:
@RequestLine("POST /messages")
@Headers("Content-Type: application/x-www-form-urlencoded")
ResponseMessage sendMessage(String message);
然后使用映射器(例如 Jackson),您可以将 Message 映射到 xml:
ObjectMapper xmlMapper = new XmlMapper();
String xml = xmlMapper.writeValueAsString(message);
然后用这个 xml 调用该方法:
sendMessage(xml);
使用编码器
否则,我认为可以根据需要配置编码器和解码器。在这种情况下,要使用 XML,您可以使用 JaxBEncoder
和 JaxBDecoder
:
api = Feign.builder()
.encoder(new JAXBEncoder())
.decoder(new JAXBDecoder())
.target(Api.class, "https://apihost");
关于java - 使用 Feign 和 Jackson 将对象序列化为 x-www-form-urlencoded,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39410839/