2017-05-01 127 views
0

我有這樣的代碼:如何添加MediaType.APPLICATION_JSON的頭和頭添加到restTemplate做getForObject

import org.springframework.boot.CommandLineRunner; 
import org.springframework.boot.SpringApplication; 
import org.springframework.boot.autoconfigure.SpringBootApplication; 
import org.springframework.boot.web.client.RestTemplateBuilder; 
import org.springframework.context.annotation.Bean; 
import org.springframework.http.HttpEntity; 
import org.springframework.http.HttpHeaders; 
import org.springframework.http.MediaType; 
import org.springframework.web.client.RestTemplate; 

@SpringBootApplication 
public class Application { 

    public static void main(String args[]) { 
     SpringApplication.run(Application.class); 

    } 

    @Bean 
    public RestTemplate restTemplate(RestTemplateBuilder builder) { 


     RestTemplate restTemplate = builder.rootUri("http://login.xxx.com/").basicAuthorization("user", "pass").build(); 
     return restTemplate; 
    } 

    @Bean 
    public CommandLineRunner run(RestTemplate restTemplate) throws Exception { 



     return args -> { 
      restTemplate.getForObject(
        "http://login.xxx.com/ws/YY/{id}", YY.class, 
        "123"); 

     }; 

    } 

} 

,但我得到這個錯誤: 產生的原因:org.springframework .web.client.RestClientException:無法提取響應:找不到適用於響應類型[class com.xxx.test.YY]和內容類型[application/xml; charset = ISO-8859-1]的HttpMessageConverter

我可以將MediaType.APPLICATION_JSON添加到標題並將標題添加到restTemplate並執行getForObject?

+0

你檢查,如果你有傑克遜2在你的類路徑? –

+0

檢查這個帖子設置標題在restTemplate:http://stackoverflow.com/questions/19238715/how-to-set-an-accept-header-on-spring-resttemplate-request –

回答

0

當使用任何get方法時,您不需要添加accept標頭,RestTemplate將自動執行。如果你看看RestTemplate's的構造函數,你會發現它會自動檢查類路徑並添加通用消息轉換器。所以你可能需要檢查你是否是類路徑(或者進入構造函數以查看它自動檢測哪些轉換器)

如果需要添加自定義標頭,如承載認證,則始終可以使用exchange方法來構建請求正是您想要的。這是應該工作的例子,我已經explicetly添加了傑克遜消息變換,所以你應該得到一個編譯錯誤,如果它是不是在你的類路徑中。

import java.net.URI; 
import java.util.Map; 

import com.google.common.collect.Lists; 
import org.springframework.http.*; 
import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter; 
import org.springframework.web.client.RestTemplate; 

public class Main { 

    public static void main(String[] args) throws Exception { 

     RestTemplate template = new RestTemplate(); 
     template.setMessageConverters(Lists.newArrayList(new MappingJackson2HttpMessageConverter())); 
     HttpHeaders headers = new HttpHeaders(); 
     headers.setAccept(Lists.newArrayList(MediaType.APPLICATION_JSON)); 
     ResponseEntity<Map> forEntity = template.exchange(new RequestEntity<>(null, headers, HttpMethod.GET, new URI("https://docs.tradable.com/v1/accounts")), Map.class); 
     System.out.println("forEntity.getBody() = " + forEntity.getBody()); 
    } 
}