我一直在開發一個雲應用程序,以便與Spring Cloud等有點混亂。現在,我試圖使用RestTemplate API將POST或PUT請求發送到Spring Data Rest後端,但我嘗試的所有內容都以錯誤結束:HttpMessageNotReadableException:無法將START_OBJECT標記中的java.lang.String實例反序列化,HttpMessageNotReadableException :無法讀取文檔:無法將START_ARRAY標記的java.lang.String實例反序列化,...來自application/xml內容類型的請求; charset = UTF-8 !, Error 400 null ...您將其命名爲。經過研究,我發現用RestTemplate(3級JSON超媒體,如果我正確記得)使用HAL JSON確實很難,但我想知道它是否可行。通過RestTemplate將POST和PUT發送到Spring Data Rest Api
我希望看到一些RestTemplate的例子,如果可能的話,發送POST和PUT到Spring Data Rest後端。
編輯:我試過postForEntity,postForLocation,交換,它只是以不同類型的錯誤結束。這些是我嘗試過的一些片段(還有更多,只是我把它們處理掉了)。
我的實體:
@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 attemps:
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"].
也試過這樣,得到了關於頭部被應用/ XML的錯誤:RestTemplate POSTing entity with associations to Spring Data REST server
其他的人只是重複其中一個錯誤。
小心分享你的代碼?我們一定會很樂意幫助 – Coder
您確定服務器在您發佈後會返回一個正文嗎? – zeroflagL
由於RestTemplate中斷,服務器不返回任何內容。它在控制器上給出了錯誤的請求錯誤,並且我在Spring Data Rest後端的答案中評論了錯誤。 –