前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >Demo直接拿来用:兼容https的"restful外部api调用工具"

Demo直接拿来用:兼容https的"restful外部api调用工具"

作者头像
浩说编程
发布2021-10-20 15:04:19
1.2K0
发布2021-10-20 15:04:19
举报
文章被收录于专栏:Java经验之谈Java经验之谈

关于"Demo拿来直接用"

本系列文章为大家提供常用小工具的Demo

侧重点并非代码如何实现,因为大家都能写

目的是为大家节省开发时间,力求“拿来直接就能用

用最快的时间完成开发任务

兼容https的"restful外部api调用工具"

01 | 应用场景

在应用内部需要调用外部的api时使用

同时兼容https类型请求

(正常在调用https类型请求时会报以下异常,该工具解决了该问题)

还是老话:方法有很多,效率至上即可。

02 | 拿来吧你

源码分为三部分:

  1. 重写SimpleClientHttpRequestFactory抽象类的prepareConnection方法
  2. 封装各类型请求
  3. 测试Demo

大家只需关注第三部分,了解使用方式,前两部分直接复制粘贴即可。

以下为各部分源码,具体说明已写在注释中,应该无需我多言了:

Part 1

代码语言:javascript
复制
/**
 * 兼容调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();
        }
    }
}     

Part 2

代码语言:javascript
复制
/**
 * <pre>
 *      RestTemplate 远程调用工具类
 * </pre>
 *
 * <pre>
 * @author mazq
 * </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);
    }
}

Part 3

代码语言:javascript
复制
MultiValueMap<String, String> map= new LinkedMultiValueMap<String, String>();
map.add("username","");
map.add("password","");
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
log.info("远程调用传递参数:");
log.info("headers:" + headers);
log.info("body:" + map);
ResponseEntity<String> responseEntity = RestTemplateUtils.postForEntity("https://....",headers,map,String.class);
log.info("远程调用返回结果:" + responseEntity);
本文参与 腾讯云自媒体分享计划,分享自微信公众号。
原始发表:2021-10-13,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 浩说编程 微信公众号,前往查看

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

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

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