如何将MediaType.APPLICATION_JSON添加到标头并将标头添加到restTemplate并执行getForObject

时间:2017-05-01 15:46:44

标签: java spring rest

我有这段代码:

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:无法提取响应:没有为响应类型[类com.xxx.test.YY]找到合适的HttpMessageConverter和内容类型[application / xml; charset = ISO-8859-1 ]

如何将MediaType.APPLICATION_JSON添加到标头并将标头添加到restTemplate并执行getForObject?

1 个答案:

答案 0 :(得分:0)

使用任何get方法时,您不需要添加accept标头,RestTemplate会自动执行此操作。如果查看RestTemplate's构造函数,可以看到它会自动检查类路径并添加公共消息转换器。所以你可能需要检查你的类路径(或者进入构造函数以查看它自动检测哪些转换器。

如果您需要添加自定义标头,例如Bearer身份验证,您始终可以使用exchange方法完全按照您的意愿构建请求。这是一个应该工作的示例,我已经明确地添加了Jackson消息转换器,因此如果它不在您的类路径中,您应该得到编译错误。

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());
    }
}