前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >SpringBoot系列之RestTemplate调https接口

SpringBoot系列之RestTemplate调https接口

作者头像
烂猪皮
发布2020-12-15 10:03:36
2.3K0
发布2020-12-15 10:03:36
举报
文章被收录于专栏:JAVA烂猪皮

走过路过不要错过

点击蓝字关注我们

业务:本系统接口都是http的,调用第三方接口,因为做了安全性校验,所以不能通过RestTemplate调用

方法:重写覆盖SimpleClientHttpRequestFactory抽象类的prepareConnection方法

代码语言:javascript
复制
package com.minstone.apprBase.common.utils.http.rest;

import org.apache.http.conn.ssl.SSLContexts;
import org.apache.http.conn.ssl.TrustStrategy;
import org.springframework.http.client.SimpleClientHttpRequestFactory;

import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLContext;
import java.net.HttpURLConnection;
import java.security.KeyStore;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;

/**
 * 兼容调Https接口
 * @Author mazq
 * @Date 2020/06/04 17:16
 * @Param
 * @return
 */
public class HttpsClientRequestFactory extends SimpleClientHttpRequestFactory {
 
    @Override
    protected void prepareConnection(HttpURLConnection connection, String httpMethod) {
        try {
            if (!(connection instanceof HttpsURLConnection)) {// http协议
                //throw new RuntimeException("An instance of HttpsURLConnection is expected");
                super.prepareConnection(connection, httpMethod);
            }
            if (connection instanceof HttpsURLConnection) {// https协议,修改协议版本
                KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType());
                // 信任任何链接
                TrustStrategy anyTrustStrategy = new TrustStrategy() {
                    @Override
                    public boolean isTrusted(X509Certificate[] x509Certificates, String s) throws CertificateException {
                        return true;
                    }
                };
                SSLContext ctx = SSLContexts.custom().useTLS().loadTrustMaterial(trustStore, anyTrustStrategy).build();
                ((HttpsURLConnection) connection).setSSLSocketFactory(ctx.getSocketFactory());
                HttpsURLConnection httpsConnection = (HttpsURLConnection) connection;
                super.prepareConnection(httpsConnection, httpMethod);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

关键代码,new RestTemplate(new HttpsClientRequestFactory());,对应工具类参考:

代码语言:javascript
复制
package com.minstone.apprBase.common.utils.http.rest;

import com.minstone.apprBase.common.utils.web.WebUtil;
import org.springframework.http.*;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;

import java.util.Map;

/**
 * <pre>
 *      RestTemplate 远程调用工具类
 * </pre>
 *
 * <pre>
 * @author mazq
 * 修改记录
 *    修改后版本:     修改人:修改日期: 2020/06/01 11:38  修改内容:
 * </pre>
 */
@Component
public class RestTemplateUtils {


    public static RestTemplate geTemplate(){
        return new RestTemplate(new HttpsClientRequestFactory());
    }

    /**
     * GET请求调用方式
     * @Author mazq
     * @Date 2020/06/01 13:47
     * @Param [url, responseType, uriVariables]
     * @return org.springframework.http.ResponseEntity<T>
     */
    public static <T> ResponseEntity<T> getForEntity(String url, Class<T> responseType, Map<String, ?> uriVariables) {
        return geTemplate().getForEntity(url, responseType, uriVariables);
    }

    /**
     * POST请求调用方式
     * @Author mazq
     * @Date 2020/06/01 13:47
     * @Param [url, headers, body, responseType]
     * @return org.springframework.http.ResponseEntity<T>
     */
    public static <T> ResponseEntity<T> postForEntity(String url,HttpHeaders headers, Object requestBody , Class<T> responseType ){

        HttpEntity<Object> requestEntity = new HttpEntity<Object>(requestBody, headers);
        return  geTemplate().postForEntity(url, requestEntity, responseType);
    }

    /**
     * PUT请求调用方式
     * @Author mazq
     * @Date 2020/06/01 13:35
     * @param url 请求URL
     * @param headers 请求头参数
     * @param requestBody 请求参数体
     * @param responseType 返回对象类型
     * @param uriVariables URL中的变量,与Map中的key对应
     * @return ResponseEntity 响应对象封装类
     */
    public static <T> ResponseEntity<T> put(String url, HttpHeaders headers, Object requestBody, Class<T> responseType, Map<String, ?> uriVariables) {
        HttpEntity<Object> requestEntity = new HttpEntity<Object>(requestBody, headers);
        return geTemplate().exchange(url, HttpMethod.PUT, requestEntity, responseType, uriVariables);
    }

    /**
     * DELETE请求调用方式
     * @Author mazq
     * @Date 2020/06/01 13:37
     * @param url 请求URL
     * @param headers 请求头参数
     * @param requestBody 请求参数体
     * @param responseType 返回对象类型
     * @param uriVariables URL中的变量,按顺序依次对应
     * @return ResponseEntity 响应对象封装类
     */
    public static <T> ResponseEntity<T> delete(String url, HttpHeaders headers, Object requestBody, Class<T> responseType, Object... uriVariables) {
        HttpEntity<Object> requestEntity = new HttpEntity<Object>(requestBody, headers);
        return geTemplate().exchange(url, HttpMethod.DELETE, requestEntity, responseType, uriVariables);
    }

    /**
     * 通用调用方式
     * @Author mazq
     * @Date 2020/06/01 13:37
     * @Param [url, method, requestEntity, responseType, uriVariables]
     * @return org.springframework.http.ResponseEntity<T>
     */
    public static <T> ResponseEntity<T> exchange(String url, HttpMethod method, HttpEntity<?> requestEntity, Class<T> responseType, Map<String, ?> uriVariables) {
        return geTemplate().exchange(url, method, requestEntity, responseType, uriVariables);
    }
}


看完本文记得给作者点赞+在看哦~~~大家的支持,是作者源源不断出文的动力

作者:SmileNicky

出处:https://www.cnblogs.com/mzq123/p/13152885.html

本文参与 腾讯云自媒体同步曝光计划,分享自微信公众号。
原始发表:2020-12-05,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 JAVA烂猪皮 微信公众号,前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档