RestTemplate工具类(发送Get、Post请求)

1.依赖

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

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

2.配置类

import java.security.KeyManagementException;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;

import javax.net.ssl.SSLContext;

import org.apache.http.conn.ssl.NoopHostnameVerifier;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.ssl.SSLContexts;
import org.apache.http.ssl.TrustStrategy;
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;

@Configuration
public class RestTemplateConfig {

    @Bean
    public RestTemplate restTemplate(ClientHttpRequestFactory factory) {
        return new RestTemplate(factory);
    }

    @Bean
    public ClientHttpRequestFactory simpleClientHttpRequestFactory() {
        HttpComponentsClientHttpRequestFactory factory = new HttpComponentsClientHttpRequestFactory();
        factory.setConnectTimeout(3000);
        factory.setReadTimeout(5000);
        return factory;
    }

    /**
     * 忽略证书配置
     */
    public static HttpComponentsClientHttpRequestFactory generateHttpRequestFactory()
            throws NoSuchAlgorithmException, KeyManagementException, KeyStoreException {
        TrustStrategy acceptingTrustStrategy = (x509Certificates, authType) -> true;
        SSLContext sslContext = SSLContexts.custom().loadTrustMaterial(null, acceptingTrustStrategy).build();
        SSLConnectionSocketFactory connectionSocketFactory = new SSLConnectionSocketFactory(sslContext,
                new NoopHostnameVerifier());
        HttpClientBuilder httpClientBuilder = HttpClients.custom();
        httpClientBuilder.setSSLSocketFactory(connectionSocketFactory);
        CloseableHttpClient httpClient = httpClientBuilder.build();
        HttpComponentsClientHttpRequestFactory factory = new HttpComponentsClientHttpRequestFactory();
        factory.setHttpClient(httpClient);
        return factory;
    }

}

3.工具类:

import com.alibaba.fastjson2.JSON;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;

import javax.servlet.http.HttpServletRequest;
import java.security.KeyManagementException;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;
import java.util.HashMap;
import java.util.Map;

/**
 * Http请求工具类
 *
 * @author djh
 * @since 2023-09-28
 */
@Component
@Slf4j
public class HttpUtil {
    /**
     * 跳过证书验证
     */
    RestTemplate restTemplateHttps = new RestTemplate(RestTemplateConfig.generateHttpRequestFactory());

    @Autowired
    private HttpServletRequest request;

    public HttpUtil() throws NoSuchAlgorithmException, KeyStoreException, KeyManagementException {
    }

    /**
     * 模拟Post请求
     */
    public void postTest() {
        // 从请求头获取token
        String token = request.getHeader("token");

        // 请求地址
        String url = "http://xxx/xxx";

        // 构建请求body参数,即请求体的JSON实体类,这里简单模拟
        HashMap<String, String> map = new HashMap<>();
        map.put("id", "1");
        map.put("name", "tom");

        // 添加请求头
        HttpHeaders headers = new HttpHeaders();
        headers.add("Content-Type", "application/json");

        // 组装请求头和参数
        HttpEntity<Map<String, String>> formEntity = new HttpEntity<>(map, headers);

        // 发起post请求
        ResponseEntity<String> stringResponseEntity = post(url, formEntity);

        // 获取返回体,这个就是请求接口返回的JSON数据
        String body = stringResponseEntity.getBody();

        // 解析body,反序列化成需要的对象即可
        Map mapResponse = JSON.parseObject(body, Map.class);
    }

    /**
     * 发送Post请求
     */
    private ResponseEntity<String> post(String url, HttpEntity formEntity) {
        ResponseEntity<String> stringResponseEntity = null;

        log.info("调用{}接口的请求参数为:{}", url, JSON.toJSONString(formEntity));
        try {
            stringResponseEntity = restTemplateHttps.postForEntity(url, formEntity, String.class);
        } catch (Exception e) {
            log.error("HttpUtil请求{}接口失败,失败原因:{}", url, e.toString());
        }
        log.info("调用{}接口的响应结果为:{}", url, JSON.toJSONString(stringResponseEntity));

        return stringResponseEntity;
    }

    /**
     * 模拟Get请求
     */
    public void getTest() {
        String url = "https://xxx";

        // 获得的String 对象就是接口返回的JSON数据
        String forObject = restTemplateHttps.getForObject(url, String.class);

        // 解析JSON
        Map map = JSON.parseObject(forObject, Map.class);
    }
}

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值