Spring RestTemplate 调用https

Spring RestTemplate 调用REST API 给我们的开发工作带来了极大的方便, 默认的SimpleClientHttpRequestFactory 并不支持https的调用,我们可以通过引入Apache HttpClient实现对https的调用支持。

首先注册

package com.fly.config;

import org.apache.http.client.HttpClient;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.config.Registry;
import org.apache.http.config.RegistryBuilder;
import org.apache.http.conn.socket.ConnectionSocketFactory;
import org.apache.http.conn.socket.PlainConnectionSocketFactory;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.client.ClientHttpRequestFactory;
import org.springframework.http.client.HttpComponentsClientHttpRequestFactory;
import org.springframework.web.client.RestTemplate;

/**
 * 
 * 注册 RestTemplate
 * 
 * @author 00fly
 * @version [版本号, 2018年11月20日]
 * @see [相关类/方法]
 * @since [产品/模块版本]
 */
@Configuration
public class RestTemplateConfig
{
    @Bean
    public RestTemplate restTemplate()
    {
        ClientHttpRequestFactory requestFactory = new HttpComponentsClientHttpRequestFactory(httpClient());
        return new RestTemplate(requestFactory);
    }
    
    /**
     * Apache HttpClient
     * 
     * @return
     * @see [类、类#方法、类#成员]
     */
    private HttpClient httpClient()
    {
        // 支持HTTP、HTTPS
        Registry registry = RegistryBuilder. create()
            .register("http", PlainConnectionSocketFactory.getSocketFactory())
            .register("https", SSLConnectionSocketFactory.getSocketFactory())
            .build();
        PoolingHttpClientConnectionManager connectionManager = new PoolingHttpClientConnectionManager(registry);
        connectionManager.setMaxTotal(200);
        connectionManager.setDefaultMaxPerRoute(100);
        connectionManager.setValidateAfterInactivity(2000);
        RequestConfig requestConfig = RequestConfig.custom()
            .setSocketTimeout(65000) // 服务器返回数据(response)的时间,超时抛出read timeout
            .setConnectTimeout(5000) // 连接上服务器(握手成功)的时间,超时抛出connect timeout
            .setConnectionRequestTimeout(1000)// 从连接池中获取连接的超时时间,超时抛出ConnectionPoolTimeoutException
            .build();
        return HttpClientBuilder.create().setDefaultRequestConfig(requestConfig).setConnectionManager(connectionManager).build();
    }
}

Spring 配置文件




	
	
		
		
	


单元测试代码

package com.fly.rest;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestTemplate;

/**
 * 
 * RestTest
 * 
 * @author 00fly
 * @version [版本号, 2018年11月20日]
 * @see [相关类/方法]
 * @since [产品/模块版本]
 */
@RunWith(SpringRunner.class)
@ContextConfiguration({"/applicationContext.xml"})
public class RestTest
{
    private static final Logger LOGGER = LoggerFactory.getLogger(RestTest.class);
    
    @Autowired
    private RestTemplate restTemplate;
   
    
    @Test
    public void testHttps()
    {
        String url = "https://www.baidu.com/"; // 百度返回乱码
        url = "https://www.so.com/";
        String responseBody;
        
        responseBody = restTemplate.getForObject(url, String.class);
        LOGGER.info("responseBody={}", responseBody);
        
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON_UTF8);
        HttpEntity> requestEntity = new HttpEntity<>(headers);
        responseBody = restTemplate.postForObject(url, requestEntity, String.class);
        LOGGER.info("responseBody={}", responseBody);
    }
}

运行结果

2018-11-22 10:47:05 |INFO |main|Loaded default TestExecutionListener class names from location [META-INF/spring.factories]: [org.springframework.test.context.we
b.ServletTestExecutionListener, org.springframework.test.context.support.DirtiesContextBeforeModesTestExecutionListener, org.springframework.test.context.suppor
t.DependencyInjectionTestExecutionListener, org.springframework.test.context.support.DirtiesContextTestExecutionListener, org.springframework.test.context.trans
action.TransactionalTestExecutionListener, org.springframework.test.context.jdbc.SqlScriptsTestExecutionListener]|
2018-11-22 10:47:05 |INFO |main|Using TestExecutionListeners: [org.springframework.test.context.support.DirtiesContextBeforeModesTestExecutionListener@13c78c0b,
 org.springframework.test.context.support.DependencyInjectionTestExecutionListener@12843fce, org.springframework.test.context.support.DirtiesContextTestExecutio
nListener@3dd3bcd]|
2018-11-22 10:47:05 |INFO |main|Loading XML bean definitions from class path resource [applicationContext.xml]|
2018-11-22 10:47:06 |INFO |main|Refreshing org.springframework.context.support.GenericApplicationContext@6a41eaa2: startup date [Thu Nov 22 10:47:06 CST 2018]; 
root of context hierarchy|
2018-11-22 10:47:09 |INFO |main|responseBody=








360搜索,SO靠谱









                    
                    

你可能感兴趣的:(spring,java)