【spring boot】RestTemplate支持https配置方式及封裝使用

最近運維突然抽風,把服務端訪問方式改成https,但是RestTemplate默認是不支持https的,造成所有接口調用失敗,經過一翻折騰後終於支持HTTPS,現將spring boot配置resttemplate及支持HTTPS的方法整理如下:

1.spring boot中集成resttemplate

在項目中導入如下的RestTemplate加載類

@Configuration
public class RestTemplateConfig {
    private Logger logger = LoggerFactory.getLogger(getClass().getName());
    @Bean
    public RestTemplate restTemplate(ClientHttpRequestFactory factory) {
        RestTemplate restTemplate = new RestTemplate(factory);
        restTemplate.setErrorHandler(new ResponseErrorHandler() {
            @Override
            public boolean hasError(ClientHttpResponse clientHttpResponse) throws IOException {
                return false;
            }

            @Override
            public void handleError(ClientHttpResponse clientHttpResponse) throws IOException {

            }
        });
        return restTemplate;
    }
    @Bean
    public ClientHttpRequestFactory simpleClientHttpRequestFactory() {
        SimpleClientHttpRequestFactory factory = new SimpleClientHttpRequestFactory();
        factory.setReadTimeout(15000);//讀超時時間,單位爲ms
        factory.setConnectTimeout(10000);//連接超時時間,單位爲ms
        return factory;
    }
}

導入該配置類後,就可以在項目中正常使用restTmeplate了

一般的使用方法如下:

//get請求
public String getO(String url, Map<String, ?> paramMap) {
    logger.info("get-> url = " + url + " params: " + paramMap.toString());
    String s = restTemplate.getForObject(url, String.class, paramMap);
    logger.info("res->" + s);
    return s;
}

//pos請求
public String postO(String url, MultiValueMap paramMap) {
    HttpHeaders headers = new HttpHeaders();
    headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
    HttpEntity<MultiValueMap<String, Object>> httpEntity = new HttpEntity<>(paramMap, headers);
    logger.info("post-> url = " + url + " params: " + paramMap.toString());
    String s = restTemplateConfig.restTemplate(restTemplateConfig.simpleClientHttpRequestFactory())
        .postForObject(url, httpEntity, String.class);
    logger.info("res->" + s);
    return s;
    }

2.支持https的配置方式

RestTemplateConfig中使用的是simpleClientHttpRequestFactory來構造RestTemplate實例的,但它是不支持https,要支持https需要替換simpleClientHttpRequestFactory爲HttpComponentsClientHttpRequestFactory

第一步:引入依賴

<dependency>
    <groupId>org.apache.httpcomponents</groupId>
    <artifactId>httpclient</artifactId>
    <version>4.5.6</version>
</dependency>

第二步:修改後的RestTemplateConfig文件如下

@Configuration
public class RestTemplateConfig {
    private Logger logger = LoggerFactory.getLogger(getClass().getName());
    @Bean
    public RestTemplate restTemplate(ClientHttpRequestFactory factory) {
        RestTemplate restTemplate = new RestTemplate(factory);
        restTemplate.setErrorHandler(new ResponseErrorHandler() {
            @Override
            public boolean hasError(ClientHttpResponse clientHttpResponse) throws IOException {
                return false;
            }
            @Override
            public void handleError(ClientHttpResponse clientHttpResponse) throws IOException {
            }
        });
        return restTemplate;
    }
//爲了支持https 改爲下面的factory
    @Bean(name = "httpsFactory")
    public HttpComponentsClientHttpRequestFactory httpComponentsClientHttpRequestFactory()
              {
                  try {
                      CloseableHttpClient httpClient = HttpClientUtils.acceptsUntrustedCertsHttpClient();
                      HttpComponentsClientHttpRequestFactory httpsFactory =
                              new HttpComponentsClientHttpRequestFactory(httpClient);
                      httpsFactory.setReadTimeout(40000);
                      httpsFactory.setConnectTimeout(40000);
                      return httpsFactory;
                  }
                  catch (Exception e ){
                      logger.info(e.getMessage());
                      return  null;
                  }
    }
}

其中HttpClientUtils的代碼如下:

public class HttpClientUtils {

    public static CloseableHttpClient acceptsUntrustedCertsHttpClient() throws KeyStoreException, NoSuchAlgorithmException, KeyManagementException {
        HttpClientBuilder b = HttpClientBuilder.create();

        // setup a Trust Strategy that allows all certificates.
        SSLContext sslContext = new SSLContextBuilder().loadTrustMaterial(null, new TrustStrategy() {
            @Override
            public boolean isTrusted(X509Certificate[] arg0, String arg1) throws CertificateException {
                return true;
            }
        }).build();
        b.setSSLContext(sslContext);

        // don't check Hostnames, either.
        //      -- use SSLConnectionSocketFactory.getDefaultHostnameVerifier(), if you don't want to weaken
        HostnameVerifier hostnameVerifier = NoopHostnameVerifier.INSTANCE;

        // here's the special part:
        //      -- need to create an SSL Socket Factory, to use our weakened "trust strategy";
        //      -- and create a Registry, to register it.
        //
        SSLConnectionSocketFactory sslSocketFactory = new SSLConnectionSocketFactory(sslContext, hostnameVerifier);
        Registry<ConnectionSocketFactory> socketFactoryRegistry = RegistryBuilder.<ConnectionSocketFactory>create()
                .register("http", PlainConnectionSocketFactory.getSocketFactory())
                .register("https", sslSocketFactory)
                .build();

        // now, we create connection-manager using our Registry.
        //      -- allows multi-threaded use
        PoolingHttpClientConnectionManager connMgr = new PoolingHttpClientConnectionManager( socketFactoryRegistry);
        connMgr.setMaxTotal(200);
        connMgr.setDefaultMaxPerRoute(100);
        b.setConnectionManager( connMgr);

        // finally, build the HttpClient;
        //      -- done!
        CloseableHttpClient client = b.build();

        return client;
    }

}

經過上述修改後,RestTmplate就能同時支持http和https了

3.RestTemplate常用方法的簡單封裝

下面這個HttpClient是我對RestTemplate常用調用方法的一個封裝,喜歡的直接拿去。。。。

@Component
public class HttpClient {
    private Logger logger = LoggerFactory.getLogger(getClass().getName());
    @Autowired
    private RestTemplate restTemplate;
    @Autowired
    private RestTemplateConfig restTemplateConfig;

    public HttpClient() {
        //this.restTemplate = new RestTemplate();
    }
     /////////////////////////////////////////get//////////////////////////////////////////////

    /**
     * 一般的GET請求,封裝getForEntity接口
     * */
    public <T> ResponseEntity<T> getE(String url, Class<T> responseType, Object... uriVariables) {
        return restTemplate.getForEntity(url, responseType, uriVariables);
    }

    /**
    * 一般的GET請求
    * */
    public String getO(String url, Map<String, ?> paramMap) {
        logger.info("get-> url = " + url + " params: " + paramMap.toString());
        String s = restTemplate.getForObject(url, String.class, paramMap);
        logger.info("res->" + s);
        return s;
    }
    /**
     * 一般的GET請求,並返回header
     * */
    public String getWithHeader(String url, Map<String, ?> paramMap,HttpHeaders headers ) {
        logger.info("get-> url = " + url + " params: " + paramMap.toString());
        HttpEntity<String> entity = new HttpEntity<String>("parameters", headers);
        ResponseEntity<String> results =  restTemplate.exchange(url,HttpMethod.GET, entity, String.class, paramMap);
        String s = results.getBody();
        logger.info("res->" + s);
        return s;
    }
    
    public ResponseEntity<String> getE2(String url, Map<String, ?> paramMap ) {
        logger.info("get-> url = " + url + " params: " + paramMap.toString());
        HttpEntity<String> entity = new HttpEntity<String>("parameters");
        ResponseEntity<String> results =  restTemplate.exchange(url,HttpMethod.GET, entity, String.class, paramMap);
        String s = results.getBody();
        logger.info("res->" + s);
        return results;
    }
    
    /**
     * 一般的GET請求,請求信息附帶cookies
     * */
    public String getOCookie(String url, Map<String, ?> paramMap,List<String> cookies ) {
        logger.info("get-> url = " + url + " params: " + paramMap.toString() + " cookies: "+ cookies.toString());
        HttpHeaders headers = new HttpHeaders();
        headers.put(HttpHeaders.COOKIE,cookies);
        //headers.setAccept(Arrays.asList(MediaType.APPLICATION_JSON));
        HttpEntity<String> entity = new HttpEntity<String>("parameters", headers);
        ResponseEntity<String> results =  restTemplate.exchange(url,HttpMethod.GET, entity, String.class, paramMap);

        String s = results.getBody();
        //String s = restTemplate.getForObject(url, String.class, paramMap);
        logger.info("res->" + s);
        return s;
    }
    
    /////////////////////////////////////////post//////////////////////////////////////////////
     /**
     * 一般的POST請求
     * */
    public String postO(String url, MultiValueMap paramMap) {
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
        HttpEntity<MultiValueMap<String, Object>> httpEntity = new HttpEntity<>(paramMap, headers);

        logger.info("post-> url = " + url + " params: " + paramMap.toString());
        String s = restTemplateConfig.restTemplate(restTemplateConfig.httpComponentsClientHttpRequestFactory()).postForObject(url, httpEntity, String.class);
        logger.info("res->" + s);
        //logger.info("res->" + JsonFormatUtil.formatJson(s));
        return s;
    }
    /**
     * 一般的POST請求,請求信息爲JSONObject
     * */
    public String post_json(String url,JSONObject msg)
    {
        RestTemplate restTemplate = new RestTemplate();
        //請求頭
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON_UTF8);
        //請求體
        //封裝成一個請求對象
        HttpEntity entity = new HttpEntity(msg.toJSONString(), headers);
        String result = restTemplateConfig.restTemplate(restTemplateConfig.httpComponentsClientHttpRequestFactory()).postForObject(url, entity, String.class);
        return result;
    }

    /**
     * 一般的POST請求,請求信息附帶cookies
     * */
    public String postOCookie(String url, MultiValueMap paramMap, List<String> cookies ) {
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
        headers.put(HttpHeaders.COOKIE,cookies);
        HttpEntity<MultiValueMap<String, Object>> httpEntity = new HttpEntity<>(paramMap, headers);

        logger.info("post-> url = " + url + " params: " + paramMap.toString());
        String s = restTemplateConfig.restTemplate(restTemplateConfig.httpComponentsClientHttpRequestFactory()).postForObject(url, httpEntity, String.class);
        logger.info("res->" + JsonFormatUtil.formatJson(s));
        return s;
    }
}

4.簡單使用

    @Autowired
    private HttpClient httpClient;

get請求:

public JSONObject getUserInfo(String userName,Long userId){
	String url = "http://localhost/demo/getUserInfo?userId={userId}&userName={userName}";
	HashMap<String, String> param = new HashMap<String, String>();
	param.put("userName", userName);
	param.put("userId", 14587);
	String re = httpClient.getO(url, param);
	JSONObject r = JSON.parseObject(re);
    return r;
}

post請求:

    public String updateUserInfo(Long userId,String nickName) {
        String url = "http://localhost/demo/updateNickName";
        MultiValueMap<String, Object> param = new LinkedMultiValueMap<String, Object>();
        param.add("nickName", nickName);
        param.add("userId", userId);
        String re = httpClient.postO(url, param);
        re = JSON.parseObject(re).get("result").toString();
        return re;
    }
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章