首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >使用Feign和Jackson将对象序列化为x-www-form-urlencoded

使用Feign和Jackson将对象序列化为x-www-form-urlencoded
EN

Stack Overflow用户
提问于 2016-09-09 19:44:19
回答 1查看 2.3K关注 0票数 1

我正在使用netflix-feign和jackson来创建Mailgun的包装器。问题是API要求POST请求使用"Content-Type: application/x-www-form-urlencoded"

这是一个示例代码:

代码语言:javascript
复制
@RequestLine("POST /messages")
@Headers("Content-Type: application/x-www-form-urlencoded")
ResponseMessage sendMessage(Message message);

JSON对象包含必要的属性,并具有Message注释:@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方法。

EN

回答 1

Stack Overflow用户

发布于 2016-10-28 17:40:45

传递映射了xml内容的字符串

您只需在您的方法中发送一个字符串,该字符串之前已被解析为xml:

代码语言:javascript
复制
@RequestLine("POST /messages")
@Headers("Content-Type: application/x-www-form-urlencoded")
ResponseMessage sendMessage(String message);

然后使用映射器(例如Jackson),您可以将消息映射到xml:

代码语言:javascript
复制
ObjectMapper xmlMapper = new XmlMapper();
String xml = xmlMapper.writeValueAsString(message);

因此,然后使用此xml调用该方法:

代码语言:javascript
复制
sendMessage(xml);

使用编码器

另外,我认为可以根据需要配置编码器和解码器。在本例中,要使用XML,可以使用JaxBEncoderJaxBDecoder

代码语言:javascript
复制
api = Feign.builder()
              .encoder(new JAXBEncoder())
              .decoder(new JAXBDecoder())
              .target(Api.class, "https://apihost");
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/39410839

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档