2017-02-20 70 views
2

我一直在開發一個雲應用程序,以便與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

其他的人只是重複其中一個錯誤。

+0

小心分享你的代碼?我們一定會很樂意幫助 – Coder

+0

您確定服務器在您發佈後會返回一個正文嗎? – zeroflagL

+0

由於RestTemplate中斷,服務器不返回任何內容。它在控制器上給出了錯誤的請求錯誤,並且我在Spring Data Rest後端的答案中評論了錯誤。 –

回答

3

您需要配置RestTemplate,以便它可以使用內容類型application/hal + json

它已經在一些其他帖子,如this onethat one,以及一堆博客文章,如here。 以下解決方案適用於一個春天啓動項目:

首先,使用一個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; 
    } 

}

然後,讓Spring注入RestTemplate,你需要消耗REST後端,並使用RestTemplate#交換的許多變種之一:

@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); 

對於集合,你將操縱PagedResources

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

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

// 
+0

我記得那個博客,但我沒有實現代碼,因爲我不知道「HAL_JSON」來自哪裏。我嘗試使用MediaType.parseMediaType(「應用程序/ hal + json」)而不是該HAL_JSON並且不起作用。錯誤是一樣的:無法反序列化實例的java.lang.String超出START_ARRAY標記 –

+0

這是確切的軌道:無法讀取文檔:無法反序列化java.lang的實例。在[Source:org.apache.catalina.conn[email protected]; START_ARRAY令牌 以外的字符串。 line:1,column:9](通過引用鏈:com.example.core.webservicesrepositories.accounts.entities.Account [「name」]);嵌套的異常是com.fasterxml.jackson.databind.JsonMappingException:不能反序列化java.lang.String的實例超出START_ARRAY令牌 –

+0

我設法解決它通過使用postForEntity交換替換該POST。我會檢查你的答案,因爲你引導我解決這個問題太多了。非常感謝你! 我得到了你在我提出這個問題之前所建議的GET,它甚至沒有調到RestTemplate,你知道爲什麼嗎? –

相關問題