RestTemplate 封装 - RestUtils

1、引入依赖

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
  <groupId>org.apache.httpcomponents</groupId>
  <artifactId>httpclient</artifactId>
</dependency>

2、配置restTemplate

@Bean
public RestTemplate getRestTemplate() {
    try {
        // 配置后可以使用 https
        TrustStrategy acceptingTrustStrategy = (x509Certificates, em) -> true;
        SSLContext sslContext = org.apache.http.ssl.SSLContexts.custom().loadTrustMaterial(null, acceptingTrustStrategy).build();
        SSLConnectionSocketFactory csf = new SSLConnectionSocketFactory(sslContext, new NoopHostnameVerifier());
        CloseableHttpClient httpClient = HttpClients.custom().setSSLSocketFactory(csf).build();
        HttpComponentsClientHttpRequestFactory requestFactory = new HttpComponentsClientHttpRequestFactory();
        requestFactory.setHttpClient(httpClient);
        return new RestTemplate(requestFactory);
    } catch (Exception e) {
        log.error("getRestTemplate error.", e);
    }
    return new RestTemplate();
}

3、创建工具类

@Component
public class RestUtils {
    @Autowired
    private RestTemplate restTemplate;

    /**
     * 发送 get 请求
     *     默认:客户端接受 json 类型数据
     */
    public <T> T get(String url, Class<T> responseType) {
        // 设置默认请求头
        Map<String, String> httpHeaderMap = new HashMap<>();
        httpHeaderMap.put(HttpHeaders.ACCEPT, MediaType.APPLICATION_JSON_VALUE);
        return sendRequest(url, HttpMethod.GET, null, responseType, httpHeaderMap);
    }

    /**
     * 发送 post 请求
     *    默认:服务器接受 json 类型数据,客户端接受 json 类型数据
     */
    public <T> T post(String url, Object requestBody, Class<T> responseType) {
        Map<String, String> httpHeaderMap = new HashMap<>();
        httpHeaderMap.put(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE);
        httpHeaderMap.put(HttpHeaders.ACCEPT, MediaType.APPLICATION_JSON_VALUE);
        return sendRequest(url, HttpMethod.POST, requestBody, responseType, httpHeaderMap);
    }


    /**
     * 发送请求
     * @param method 请求方式
     */
    public <T> T sendRequest(String url, HttpMethod method, Object requestBody, Class<T> responseType, Map<String, String> httpHeaderMap) {
        HttpHeaders headers = new HttpHeaders();
        // 设置请求头
        httpHeaderMap.keySet().forEach(key -> {
            headers.add(key,httpHeaderMap.get(key));
        });
        HttpEntity<Object> entity = new HttpEntity<>(requestBody, headers);
        return restTemplate.exchange(url, method, entity, responseType).getBody();
    }


    /**
     * 在 url 后面拼接参数
     * @param url 原请求路径
     * @param paramMap 参数map
     */
    public String getParamUrl(String url, Map<String, String> paramMap) {
        StringBuilder sb = new StringBuilder(url);
        if (paramMap != null && !paramMap.isEmpty()) {
            sb.append("?");
            for (Map.Entry<String, String> entry : paramMap.entrySet()) {
                String key = entry.getKey();
                String value = entry.getValue();
                sb.append(key).append("=").append(value).append("&");
            }
            sb.deleteCharAt(sb.length() - 1); // 移除最后一个多余的"&"
        }
        return sb.toString();
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值