【发布时间】:2018-09-27 07:17:51
【问题描述】:
我有一个 POJO 的形式:
@Data
public class BaseRequest {
private String type;
private Map<String, Object> details;
private Map<String, Object> signature;
}
我有一个服务正在运行,它只接受内容类型:“application/x-www-form-urlencoded”。
我用 Java 编写了一个客户端,它使用 Spring 的 RestTemplate 进行调用。
public String getInvoice(BaseRequest req, String url) {
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
HttpEntity<BaseRequest> httpEntity = new HttpEntity<BaseRequest>(req, headers);
String response = this.restTemplate.postForObject(url, httpEntity, String.class);
return response;
}
但是,它会引发错误:
org.springframework.web.client.RestClientException: Could not write request: no suitable HttpMessageConverter found for request type [com.x.y.z.BaseRequest] and content type [application/x-www-form-urlencoded]
如果我将内容类型设置为 JSON,它会起作用:
headers.setContentType(MediaType.APPLICATION_JSON);
我知道它适用于 JSON,因为我已经使用 JacksonHTTPMessageConverter 配置了我的 RestTemplate Bean。所以我可以轻松地将 POJO 转换为 application/json。但是,我无法弄清楚如何使用 application/x-www-form-urlencoded 来做到这一点。
我已经搜索了一段时间了,我找到的唯一解决方案是编写自己的转换器,将我的 BaseRequest 类转换为 Spring 的 MultiValueMap,然后 Spring 的 FormHttpMessageConverter 会自动处理它。但我想避免这样做。有没有其他办法解决这个问题?
任何线索将不胜感激。谢谢!
编辑: 我的问题与@JsonProperty not working for Content-Type : application/x-www-form-urlencoded 不同。那里发生的转换是关于接受 application/x-www-form-urlencoded 中的数据并将其转换为 POJO。我的问题是关于在使用 Spring 的 resttemplate 进行调用时将 POJO 转换为 application/x-www-form-urlencoded。就像我提到的那样,我知道我可以通过编写自己的转换器将我的 POJO 转换为 Spring 的 MultiValueMap 来实现这一点。但是,我想知道我是否可以避免这样做。
编辑:
Dump of $_POST on the API when I send my data as MultiValueMap<String, Object>:
"array(0) {
}"
Dump of $_POST on the API when I send my data through Postman in the correct format:
"array(2) {
["type"]=>
string(16) "abcd"
["details"]=>
array(1) {
["template_file"]=>
string(16) "x.html"
}
}"
【问题讨论】:
-
所以你已经用“produces(application/x-www-form-urlencoded)”注释了你的控制器方法?
-
@dainu 控制器方法的代码在不同的服务上,我无法在那里进行更改。该服务是用 PHP 编写的。我只是从我的服务(用 Java 编写)对该服务进行 API 调用。
标签: java spring resttemplate pojo form-data