2017-03-04 129 views
2

我有簡單的Java春方法用於創建對象如何通過spring RestTemplate在獲取請求中更改響應http頭?

RestTemplate restTemplate = new RestTemplate(); 
Address address = restTemplate.getForObject(url, Address.class); 

但是服務器我響應JSON字符串錯誤的Content-Type:文/平原代替應用/ JSON(在郵差選中) 。和我得到異常:

無法提取響應:沒有合適HttpMessageConverter找到的響應類型[類地址]和內容類型[text/plain的;字符集= UTF-8]

所以我認爲,我需要改變響應標題內容類型到右邊應用程序/ json,即MappingJackson2HttpMessageConverter找出JSON字符串和運行代碼以及。

回答

2

嘗試了一個小時後,我發現了一個簡短而簡單的方法。

默認Json轉換器只支持「application/json」。我們只是將其覆蓋以支持「text/plain」。

MappingJackson2HttpMessageConverter converter = new MappingJackson2HttpMessageConverter(); 

// support "text/plain" 
converter.setSupportedMediaTypes(Arrays.asList(TEXT_PLAIN, APPLICATION_JSON)); 

RestTemplate template = new RestTemplate(); 
template.getMessageConverters().add(converter); 

// It's ok now 
MyResult result = tmp.postForObject("http://url:8080/api", 
      new MyRequest("param value"), MyResult.class); 
0

要設置內容類型爲你的要求,你可以這樣做:

HttpHeaders headers = new HttpHeaders(); 
    headers.setContentType(MediaType.APPLICATION_JSON); 
    HttpEntity entity = new HttpEntity(headers); 
    ResponseEntity<Address> response = restTemplate.exchange(url, HttpMethod.GET, entity, Address.class); 
    Address address = response.getBody(); 
+1

不,它不起作用。它只是改變請求的標題,而不是響應。 –

+0

您無法更改Response的標頭,這些標頭是由服務器發送的,因此,除非您正在編寫服務器的代碼,否則無法做到您想要的內容。 –

+0

檢查這個類似的問題http://stackoverflow.com/questions/24723394/could-not-extract-response-no-suitable-httpmessageconverter-found-for-response –

1

感謝您的幫助! 如果我無法更改回應的標題。我用右頭創建新的響應對象。

  ClientHttpRequest clientHttpRequest = new SimpleClientHttpRequestFactory().createRequest(URI.create(str), org.springframework.http.HttpMethod.GET); 
      final ClientHttpResponse clientHttpResponse = clientHttpRequest.execute(); 
      MappingJackson2HttpMessageConverter converter = new MappingJackson2HttpMessageConverter(); 
      Address address = new Address(); 
      //It always true, because service always returns 200 OK 
      if (clientHttpResponse.getStatusCode() == HttpStatus.OK) { 
       address = (Address) converter.read(address.getClass(), new HttpInputMessage() { 
        public InputStream getBody() throws IOException { 
         return clientHttpResponse.getBody(); 
        } 

        public HttpHeaders getHeaders() { 
         HttpHeaders httpHeaders = new HttpHeaders(); 
         httpHeaders.putAll(clientHttpResponse.getHeaders()); 
         httpHeaders.put("Content-Type", Collections.singletonList(MediaType.APPLICATION_JSON_VALUE)); 
         return httpHeaders; 
        } 
       }); 
       busStop.setNearestAddress(address.toString()); 
      } 

我敢肯定這不是簡單和好的解決方案,但它的工作原理。