通过 RestTemplate 将 POST 和 PUT 发送到 Spring Data Rest Api

Man*_*áez 2 json resttemplate spring-data-rest spring-hateoas

我一直在开发一个云应用程序来处理 Spring Cloud 等问题。现在我被困在尝试使用 RestTemplate API 向 Spring Data Rest 后端发送 POST 或 PUT 请求,但我尝试的一切都以错误结束:HttpMessageNotReadableException:无法从 START_OBJECT 令牌中反序列化 java.lang.String 的实例,HttpMessageNotReadableException : 无法读取文档: 无法从 START_ARRAY 令牌中反序列化 java.lang.String 的实例,...来自内容类型为 application/xml;charset=UTF-8! 的请求,错误 400 null...你说出它的名字. 经过研究,我发现使用 RestTemplate(如果我没记错的话,级别 3 JSON 超媒体)实际上很难使用 HAL JSON,但我想知道这是否可能。

我想看看 RestTemplate 将 POST 和 PUT 发送到 Spring Data Rest 后端的一些工作(如果可能的话,请详细说明)示例。

编辑:我尝试过 postForEntity、postForLocation、exchange,但它以不同类型的错误结束。这些是我尝试过的一些片段(还有更多,只是我处理了它们)。

我的实体:

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

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

也像这样尝试并得到一个关于标题是 application/xml: RestTemplate POSTing entity with associations to Spring Data REST server 的错误

其他的只是重复这些错误之一。

Mar*_*rin 5

您需要配置您的 RestTemplate 以便它可以使用application/hal+json内容类型。

它已经在其他一些帖子中得到解决,例如这个那个,以及一堆博客帖子,例如这里。以下解决方案适用于 Spring Boot 项目:

首先,使用 bean 配置您的 RestTemplate:

// other import directives omitted for the sake of brevity
import static org.springframework.hateoas.MediaTypes.HAL_JSON;

@Configuration
public class RestTemplateConfiguration {

    @Autowired
    private ObjectMapper objectMapper;

    /**
     *
     * @return a {@link RestTemplate} with a HAL converter
     */
    @Bean
    public RestTemplate restTemplate() {

        // converter
        MappingJackson2HttpMessageConverter converter = new MappingJackson2HttpMessageConverter();
        converter.setSupportedMediaTypes(Arrays.asList(HAL_JSON));
        converter.setObjectMapper(objectMapper);

        RestTemplate restTemplate = new RestTemplate(Collections.singletonList(converter));

        return restTemplate;
    }
}
Run Code Online (Sandbox Code Playgroud)

然后,让 Spring 在您需要使用 REST 后端的地方注入 RestTemplate,并使用 RestTemplate#exchange 的众多变体之一:

@Autowired
public RestTemplate restTemplate;

...
// for a single ressource

// GET
Account newAccount = restTemplate.getForObject(url, Account.class);

// POST
Account newAccount = restTemplate.exchange(serviceUrl + "/accounts", HttpMethod.POST, entity, Account.class).getBody();
// or any of the specialized POST methods...
Account newAccount = restTemplate.postForObject(serviceUrl + "/accounts", entity, Account.class);
Run Code Online (Sandbox Code Playgroud)

对于一个集合,您将操作一个PagedResources

// for a collection
ParameterizedTypeReference<PagedResources<Account>> responseType =
        new ParameterizedTypeReference<PagedResources<Account>>() {};

// GET
PagedResources<Account> accounts =
        restTemplate.exchange(url, HttpMethod.GET, null, responseType).getBody();

//
Run Code Online (Sandbox Code Playgroud)