Spring RestTemplate的使用注意

导包

RestTemplate HTTP客户端工具是Spring框架提供的,不需要导入额外的依赖坐标,只需要在项目中引入Web的依赖即可。

<dependency>
       <groupId>org.springframework.boot</groupId>
       <artifactId>spring-boot-starter-web</artifactId>
</dependency>

 

 

注入RestTemplate

默认好像是不可以直接在项目中注入使用RestTemplate的,需要我们注入

@Configuration
public class RestConfig {

    @Bean("restTemplate")
    public RestTemplate restTemplate(ClientHttpRequestFactory factory){
        RestTemplate restTemplate = new RestTemplate(factory);
        MappingJackson2HttpMessageConverter mappingJackson2HttpMessageConverter = new MappingJackson2HttpMessageConverter();
        mappingJackson2HttpMessageConverter.setSupportedMediaTypes(Arrays.asList(
                MediaType.TEXT_HTML,
                MediaType.TEXT_PLAIN));
        restTemplate.getMessageConverters().add(mappingJackson2HttpMessageConverter);

        return restTemplate;
    }

    @Bean
    public ClientHttpRequestFactory simpleClientHttpRequestFactory() {
        SimpleClientHttpRequestFactory factory = new SimpleClientHttpRequestFactory();
        factory.setReadTimeout(5000);
        factory.setConnectTimeout(15000);
        // 设置代理
        //factory.setProxy(null);
        return factory;
    }
}

 

RestTemplate请求不支持content type [text/html;charset=UTF-8]类型,以上代码可以解决这个问题:Could not extract response: no suitable HttpMessageConverter found for response type.... content type [text/html;charset=UTF-8]

发送GET请求注意事项

String url=http://test.com/url?param1={param1}&param2={param2};
Map<String, Object> params = new HashMap<>();
params.put("param1", "value1");
params.put("param2", "value2");
JSONObject mutiData = restTemplate.getForObject(url, JSONObject.class, params);

 

 

需要注意的是:

?param1={param1}&param2={param2};

参数需要写在url上,并且保证占位符param与map中的key一致!

 

 

 

阅读剩余
THE END