2017-06-12 112 views
0

有一個外部服務稱爲當我在RestTemplate通過POST請求發送陣列I收到錯誤400

http://externalServer:9000/pathServer/serviceCalled

作爲輸入參數接收對象的列表此服務。

Request 
    [ 
     { "atr1" : "value" }, 
     { "atr1" : "value" }, 
     { "atr1" : "value" }, 
     { "atr1" : "value" } 
    ] 

在我的後端我撥打電話到該服務,因爲它不是在我的域名。爲此,我使用Spring的RestTemplate。

我已經使用過這個,但是當我打電話時,它給了我一個400錯誤的請求錯誤。

這是我的代碼。

String jsonValue= "[{ \"atr1\" : \"value\" },{ \"atr1\" : \"value\" },{ \"atr1\" : \"value\" },{ \"atr1\" : \"value\" }]"; 

HttpHeaders headers = new HttpHeaders(); 
headers.setContentType(MediaType.APPLICATION_JSON); 

HttpEntity<String> entity = new HttpEntity<>(jsonValue,headers); 

String url = "http://externalServer:9000/pathServer/serviceCalled"; 

ResponseEntity<String> STRresponse = restTemplate.exchange(url, HttpMethod.POST, entity, String.class); 

輸出打印到STResponse是

enter image description here

我知道請求是正確的,因爲當我跟郵遞員送它,它工作正常。

enter image description here

我在做什麼錯?

+0

我嘗試但我收到錯誤 org.springframework.http.converter.HttpMessageNotReadableException:無法讀取文檔:無法將java.util.ArrayList的實例反序列化爲START_OBJECT標記 at [Source:[email protected];行:1,列:1];嵌套的例外是com.fasterxml.jackson.databind.JsonMappingException:無法反序列化的java.util.ArrayList的實例進行START_OBJECT令牌 –

+0

的你沒有根據的消息,而不是一個列表 – 2017-06-13 05:14:34

+0

發佈一個對象,但該服務接收列表,即我不能改變它 –

回答

0

在評論前面已經說了,可以嘗試使用一些類Request有一個名爲atr1場,和其他一些類Result兩個字段命名爲codemessage

class Request { 
    private String atr1; 
    // getter, setter 
} 

class Result { 
    private String code; 
    private String message; 
    // getter, setter 
} 

然後

List<Request> data = new ArrayList<>(); 
Request req1 = new Request(); 
req1.setAtr1("value"); 
data.add(req1); 
Request req2 = new Request(); 
req2.setAtr1("value"); 
data.add(req2); 

String url = "http://externalServer:9000/pathServer/serviceCalled"; 
ResponseEntity<Result> response = restTemplate.postForEntity(url, data, Result.class); 
+0

我recievied這個錯誤無法讀取文件:無法反序列化java.lang.String中的實例進行START_OBJECT令牌\ n個在[來源:JAVA。 [email protected];行:1,列:1];嵌套的異常是com.fasterxml.jackson.databind.JsonMappingException:無法在[Source:[email protected];中的START_OBJECT標記\ n中反序列化java.lang.String的實例。行:1,列:1] –

+0

@EliasVargas我不好的結果是一個對象不是字符串(我沒有複製你的代碼),看我的編輯 – 2017-06-14 19:02:24