优秀的编程知识分享平台

网站首页 > 技术文章 正文

Springboot中引入RestTemplate(springboot中引入jar包)

nanyue 2024-09-08 06:07:16 技术文章 9 ℃

利用@bean注解,首先创建ClientHttpRequestFactory实例,再创建RestTemplate实例。代码如下:

@Configuration
public class RestConnectionConfigure {
    /**
     * 单位毫秒
     */
    private static final int READ_TIMEOUT = 10000;
    private static final int CONNECT_TIMEOUT = 10000;

    @Bean(name = "clientHttpRequestFactory")
    public ClientHttpRequestFactory simpleClientHttpRequestFactory(ProxyConfig proxyConfig) {
        SimpleClientHttpRequestFactory factory = new SimpleClientHttpRequestFactory();
        factory.setReadTimeout(READ_TIMEOUT);
        factory.setConnectTimeout(CONNECT_TIMEOUT);
        if (proxyConfig != null && !StringUtils.isEmpty(proxyConfig.getHost())) {
            factory.setProxy(new Proxy(Proxy.Type.HTTP, new InetSocketAddress(proxyConfig.getHost(), proxyConfig.getPort())));
        }
        return factory;
    }

    @Bean
    public RestTemplate restTemplate(@Autowired ClientHttpRequestFactory clientHttpRequestFactory){
        RestTemplate restTemplate = new RestTemplate(clientHttpRequestFactory);
        restTemplate.getMessageConverters().add(new StringHttpMessageConverter(Charset.forName("UTF-8")));
        restTemplate.getMessageConverters().add(new DocMappingJackson2HttpMessageConverter());
        return restTemplate;
    }
}

其中proxyConfig是连接代理配置,host为代理服务器IP,port为端口

@Configuration
@ConfigurationProperties(prefix = "proxy")
public class ProxyConfig {
    String host;
    int port;
    public String getHost() {
        return host;
    }
    public void setHost(String host) {
        this.host = host;
    }
    public int getPort() {
        return port;
    }
    public void setPort(int port) {
        this.port = port;
    }
}

创建代理服务的配置文件如下:(如果使用代理的话)

proxy:
     host: xxx.xxx.xx.yy
     port: 3128


DocMappingJackson2HttpMessageConverter类为自定义的HttpMessageConverter,用来处理text/html 和text/plain的数据请求。

public class DocMappingJackson2HttpMessageConverter extends MappingJackson2HttpMessageConverter {

    public DocMappingJackson2HttpMessageConverter(){
        List<MediaType> mediaTypes = new ArrayList<>();
        mediaTypes.add(MediaType.TEXT_PLAIN);
        mediaTypes.add(MediaType.TEXT_HTML);
        setSupportedMediaTypes(mediaTypes);
    }
}

RestTemplate默认使用HttpUrlConnection来进行网络请求。参考下面的方式替换成HttpClient或者OkHttp3Client,使用不同的HttpRequestFactory即可。

new RestTemplate(new SimpleClientHttpRequestFactory());
 
new RestTemplate(new HttpComponentsClientHttpRequestFactory());
      
new RestTemplate(new OkHttp3ClientHttpRequestFactory());   
最近发表
标签列表