2013-07-24 162 views
2

是否可以使用Spring RestTemplate將原始JSON傳遞給Rest API?可能使用Spring RestTemplate將原始JSON傳遞給Rest API?

我試圖如下:

List<HttpMessageConverter<?>> httpMessageConverters = new ArrayList<HttpMessageConverter<?>>(); 
httpMessageConverters.add(new MappingJacksonHttpMessageConverter()); 
restTemplate.setMessageConverters(httpMessageConverters); 
String jsonText = // raw JSON 
httpHeaders.setContentType(MediaType.APPLICATION_JSON); 
HttpEntity<?> entity = new HttpEntity<Object>(jsonText, httpHeaders); 
restTemplate.exchange(url, HttpMethod.POST, entity, responseClass); 

當我調用這個要求,我得到一個HTTP 400錯誤響應,意思是錯誤的請求。但是,所有標題和JSON正文與使用我擁有的HTTP客戶端提交的相同。

相比之下,下面當我創建了MyRequest對象,並設置它的HttpEntity正常工作:

List<HttpMessageConverter<?>> httpMessageConverters = new ArrayList<HttpMessageConverter<?>>(); 
    httpMessageConverters.add(new MappingJacksonHttpMessageConverter()); 
    restTemplate.setMessageConverters(httpMessageConverters); 
    MyRequest myRequest = new MyRequest(); 
    httpHeaders.setContentType(MediaType.APPLICATION_JSON); 
    HttpEntity<?> entity = new HttpEntity<Object>(myRequest, httpHeaders); 
    restTemplate.exchange(url, HttpMethod.POST, entity, responseClass); 

因此,我想知道我怎麼能以String格式使用原始JSON調用我的REST API?

+0

你試過沒有設置信息轉換器,因爲您不希望您的信息被轉換成什麼做?另外,爲什麼不讓它成爲'HttpEntity '? –

回答

0

這是方法

  String url = String.format("https://SITE"); 
      RestTemplate template = new RestTemplate(); 
      template.getMessageConverters().add(new StringHttpMessageConverter()); 

      String valor ="{\"cmd\":\"123\", \"includeImei\":\"true\"}"; 

      HttpHeaders headers = new HttpHeaders(); 
      headers.setContentType(MediaType.APPLICATION_JSON); 
      headers.set("Authenticate", "TOKEN"); 


      HttpEntity<String> entity = new HttpEntity<String>(valor, headers); 
      URI valoresdevueltos = template.postForLocation(url, entity); 
+0

您能否詳細說明您的答案並添加一些細節? – abarisone

相關問題