【发布时间】:2017-07-10 08:45:00
【问题描述】:
我一直在开发一个云应用程序来稍微弄乱 Spring Cloud 等。现在我被困在尝试使用 RestTemplate API 向 Spring Data Rest 后端发送 POST 或 PUT 请求,但我尝试的一切都以错误结束:HttpMessageNotReadableException:无法反序列化 java.lang.String 的实例出 START_OBJECT 令牌,HttpMessageNotReadableException :无法读取文档:无法从 START_ARRAY 令牌中反序列化 java.lang.String 的实例,...来自内容类型为 application/xml;charset=UTF-8! 的请求,错误 400 null ... .经过研究,我发现实际上很难通过 RestTemplate 使用 HAL JSON(如果我没记错的话,它是 3 级 JSON 超媒体),但我想知道这是否可能。
我希望看到一些将 POST 和 PUT 发送到 Spring Data Rest 后端的 RestTemplate 的工作示例(如果可能,请详细说明)。
编辑:我尝试了 postForEntity、postForLocation、exchange,但它只是以不同类型的错误结束。这些是我尝试过的一些sn-ps(还有更多,只是我处理它们)。
我的实体:
@Entity
public class Account implements Serializable {
private static final long serialVersionUID = 1L;
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String name;
@NotNull
@NotEmpty
private String username;
@NotNull
@NotEmpty
private String authorities;
@NotNull
@NotEmpty
private String password;
//Constructor, getter and setter
一些restTemplate尝试:
public Account create(Account account) {
//Doesnt work :S
MultiValueMap<String, String> map = new LinkedMultiValueMap<String, String>();
map.add("name", account.getName());
map.add("username", account.getUsername());
map.add("password", account.getPassword());
map.add("authorities", account.getAuthorities());
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_JSON);
final HttpEntity<MultiValueMap<String, String>> entity = new HttpEntity<MultiValueMap<String, String>>(map,
headers);
return restTemplate.exchange(serviceUrl + "/accounts", HttpMethod.POST, entity, Account.class).getBody();
}
//Also tried with a AccountResource which extends from ResourceSupport and doesn't work either. This one gives me a error saying it cannot deserialize Account["name"].
也尝试过这样,得到一个关于 header 是 application/xml:RestTemplate POSTing entity with associations to Spring Data REST server的错误
其他的只是重复其中一个错误。
【问题讨论】:
-
愿意分享您的代码吗?我们一定很乐意提供帮助
-
您确定服务器在您发帖时返回正文吗?
-
服务器没有返回任何东西,因为 RestTemplate 中断了。它在控制器上给出了错误的请求错误,并且我在 Spring Data Rest 后端的答案中评论了错误。
标签: json spring-data-rest resttemplate spring-hateoas