我有這樣的代碼:如何添加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?
你檢查,如果你有傑克遜2在你的類路徑? –
檢查這個帖子設置標題在restTemplate:http://stackoverflow.com/questions/19238715/how-to-set-an-accept-header-on-spring-resttemplate-request –