小编Qaw*_*wls的帖子

在Java中将POJO转换为表单数据

我有一个形式的POJO:

@Data
public class BaseRequest {
    private String type;
    private Map<String, Object> details;
    private Map<String, Object> signature;
}
Run Code Online (Sandbox Code Playgroud)

我正在运行一个仅接受内容类型的服务:“ 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;
}
Run Code Online (Sandbox Code Playgroud)

但是,它将引发错误:

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]
Run Code Online (Sandbox Code Playgroud)

如果我将内容类型设置为JSON,它将起作用:

headers.setContentType(MediaType.APPLICATION_JSON);
Run Code Online (Sandbox Code Playgroud)

我知道它适用于JSON,因为我已经用JacksonHTTPMessageConverter配置了RestTemplate Bean。因此,我可以轻松地将POJO转换为application / json。但是,我不知道如何使用application / x-www-form-urlencoded做到这一点。

我已经搜索了一段时间,发现的唯一解决方案是编写自己的转换器,将BaseRequest类转换为Spring的MultiValueMap,然后Spring的FormHttpMessageConverter将自动处理它。但我想避免这样做。还有其他解决方法吗?

任何线索将不胜感激。谢谢!

编辑:我的问题不同于 …

java spring form-data pojo resttemplate

8
推荐指数
1
解决办法
1364
查看次数

标签 统计

form-data ×1

java ×1

pojo ×1

resttemplate ×1

spring ×1