RestTemplate使用笔记

本文详细介绍了Spring的RestTemplate如何进行GET和POST请求,包括设置请求头、传递参数。推荐使用exchange方法进行请求,特别是处理GET请求的JSON参数和POST请求的多种形式。还提供了示例代码展示如何封装RESTful API调用,并给出了忽略HTTPS证书认证的配置。此外,文章提及了将响应数据转换为自定义对象的方法。
摘要由CSDN通过智能技术生成

常用使用模板

RestTemplate常用于请求第三方接口

一般有get,post,exchange等多种方式

在请求时,可以自己设置请求头等。

注意get请求的getForObject等构造方法不能设置请求头,只能使用exchange设置get请求来设置请求头。

post请求的几个构造方法可以设置请求头。

同时get请求设置使用json请求体的方式传参比较麻烦,推荐使用exchange的方式使用get请求添加json参数来代替

推荐使用exchange进行请求

RestTemplate的使用

参考:RestTemplate | 使用详解_    (重点参考) 

RestTemplate的请求参数传递问题 RestTemplate发送Get请求通过body传参问题

RestTemplate中postForEntity其中参数为数组或者List_

restTemplate模拟浏览器登录携带cookie请求接口_

注意:

get方式是将请求参数设置到url上的,有时候也会使用请求体

post方式是将参数设置到body里面

post设置请求体的访问方式一般使用:

设置请求体的访问方式一般使用map:
MultiValueMap<String, String> params = new LinkedMultiValueMap<>();
// 除了map以外,也可以使用string,根据请求头类型来确认
// 这里的请求头是Content-Type: application/x-www-form-urlencoded; charset=UTF-8

// 如果使用请求头是json的话,请求数据就可以使用json字符串


示例封装的方法:

 public String doPostForBody(String url, MultiValueMap<String, String> body) {
        HttpHeaders headers = new HttpHeaders();
        // 设置请求类型,根据需要设置
        headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
        // 设置请求头的方式,根据需要设置
        List<String> cookies = new ArrayList<>();
        cookies.add(expendParam.getCookiesStr());
        headers.put(HttpHeaders.COOKIE, cookies);
        // 设置请求boby
        HttpEntity<MultiValueMap<String, String>> entity = new HttpEntity<>(body, headers);
        ResponseEntity<String> resp = null;
        try {
            resp = restTemplate.postForEntity(url, entity, String.class);
        } catch (RestClientException e) {
            logger.error("请求失败:{}", url);
            logger.error("请求失败:", e);
        }
        return resp.getBody();
    }

// 使用完成后一般将string转换为json数据

 JSONObject jsonObject =  JSON.parseObject(doPostForBody(url,body));

// 注意,存在多个值时,即为数组,获取数组循环转换,

JSONArray jsonArray = jsonObject.getJSONArray("rows");


如果要将返回的数据设置成自己的实现类,因为json数据是key-value形式,即map形式,一般使用Json格式化工具类转换  ,直接将返回的string使用工具类转换  

@Data
public class Pojo01 {
      private String field1;
      private String field2;
      private String field3;
      private String field4;
      private String field5;
}

public class Test01 {
      public static void main(String[] args)   {
            Map<String, String> hashMap = new HashMap<>();
            hashMap.put("field1", "value1");
            hashMap.put("field2", "value2");
            hashMap.put("field3", "value3");
            hashMap.put("field4", "value4");
            hashMap.put("field5", "value5");
 
            //将HashMap转为JSON,在转为Pojo01对象:
            String toJSON = JSONObject.toJSONString(hashMap);
            Pojo01 pojo01 = JSONObject.toJavaObject(JSON.parseObject(toJSON), Pojo01.class);
            System.out.println(" pojo01 = " + pojo01.toString());
      }
}

常用工具类代码:


@Component
public class RestTemplateUtil {

    public static final String FORM_DATA = "application/form-data";

    public static final String MULTIPART_FORM_DATA = "multipart/form-data";

    public static final String FORM_URLENCODED = "application/x-www-form-urlencoded";

    public static final String JSON = "application/json";

    private RestTemplate restTemplate = new RestTemplate();
    @Autowired
    private LocalAgentProperties localAgentProperties;

    public Object doGet(String path, Map<String,String> hearderMap, Class<?> resp){
        HttpHeaders httpHeaders = getHttpHeaders(hearderMap,null);
        HttpEntity httpEntity = new HttpEntity(httpHeaders);
        path = checkPath(path);
        ResponseEntity<?> result = restTemplate.exchange(path, HttpMethod.GET,httpEntity,resp);
        return result.getBody();
    }

    private String checkPath(String path) {
        if (StringUtils.isNotBlank(path) && path.contains("http")){
            return path;
        }
        return localAgentProperties.getAgent().getApiBaseUrl() + "/" +path;
    }

    public JSONObject doPostForJson(String path, Map<String,String> hearderMap, JSONObject jsonObject){
        HttpHeaders httpHeaders = getHttpHeaders(hearderMap,RestTemplateUtil.JSON);
        HttpEntity httpEntity = new HttpEntity(jsonObject,httpHeaders);
        path = checkPath(path);
        JSONObject result = restTemplate.postForObject(path,httpEntity,JSONObject.class);
        checkResult(result);
        return result;
    }

    private void checkResult(JSONObject result) {
        if (!result.getString("code").equals("0")){
            throw new BaseException(result.getString("msg"),ErrorCode.SYSTEM_ERROR.getCode());
        }
    }

    public JSONObject doPostForFormData(String path, Map<String,String> hearderMap, MultiValueMap<String,Object> object){
        HttpHeaders httpHeaders = getHttpHeaders(hearderMap,RestTemplateUtil.FORM_DATA);
        HttpEntity httpEntity = new HttpEntity(object,httpHeaders);
        path = checkPath(path);
        JSONObject result = restTemplate.postForObject(path,httpEntity,JSONObject.class);
        checkResult(result);
        return result;
    }

    public JSONObject doPostForMultiFormData(String path, Map<String,String> hearderMap, MultiValueMap<String,Object> object){
        HttpHeaders httpHeaders = getHttpHeaders(hearderMap,RestTemplateUtil.MULTIPART_FORM_DATA);
        HttpEntity httpEntity = new HttpEntity(object,httpHeaders);
        path = checkPath(path);
        JSONObject result = restTemplate.postForObject(path,httpEntity,JSONObject.class);
        checkResult(result);
        return result;
    }

    private HttpHeaders getHttpHeaders(Map<String, String> hearderMap,String contentType) {
        HttpHeaders httpHeaders = new HttpHeaders();
        if (hearderMap != null && hearderMap.entrySet() != null){
            for (Map.Entry<String,String> stringStringEntry:hearderMap.entrySet()){
                httpHeaders.add(stringStringEntry.getKey(),stringStringEntry.getValue());
            }
        }else {
            httpHeaders.add("Content-Type",contentType);
        }
        return httpHeaders;
    }


    public Object doPostForEntity(String path, Map<String,String> hearderMap,JSONObject jsonObject, Class<?> resp){
        HttpHeaders httpHeaders = getHttpHeaders(hearderMap,RestTemplateUtil.JSON);
        HttpEntity httpEntity = new HttpEntity(jsonObject,httpHeaders);
        path = checkPath(path);
        ResponseEntity<?> result = restTemplate.postForEntity(path,httpEntity,resp);
        return result.getBody();
    }

    public JSONObject doGetForJson(String path, Map<String,Object> uriParams, JSONObject jsonObject) {
        path = checkPath(path);
        JSONObject forObject = restTemplate.getForObject(path, JSONObject.class, uriParams);
        return forObject;
    }

    public Object doGetForEntity(String path, Map<String,Object> uriParams, Class<?> resp) {
        path = checkPath(path);
        ResponseEntity<?> forEntity = restTemplate.getForEntity(path, resp, uriParams);
        return forEntity.getBody();
    }

    public JSONObject doRequestForPath(String path, Map<String,String> hearderMap, HttpMethod method) {
        HttpHeaders httpHeaders = getHttpHeaders(hearderMap,null);
        HttpEntity httpEntity = new HttpEntity(httpHeaders);
        path = checkPath(path);
        ResponseEntity<JSONObject> result = restTemplate.exchange(path,method,httpEntity,JSONObject.class);
        return result.getBody();
    }

      // 最好使用exchange来发起请求
    public ResponseEntity<String> doRequestForJson(String path, Map<String,String> hearderMap, JSONObject jsonObject, HttpMethod method){
        HttpHeaders httpHeaders = getHttpHeaders(hearderMap,RestTemplateUtil.JSON);
        HttpEntity httpEntity = new HttpEntity(jsonObject,httpHeaders);
        path = checkPath(path);
        ResponseEntity<String> result = restTemplate.exchange(path,method,httpEntity,String.class);
        return result;
    }

    //响应请求体,将string格式的请求体转换为实体类
    
    private <T> T parseResponseData(ResponseEntity<String> responseEntity, TypeReference<T> typeReference) {
        if (responseEntity == null || responseEntity.getBody() == null) {
            throw new BaseException("请求失败,响应数据为空。", ErrorCode.SYSTEM_ERROR.getCode());
        }
        
        String resp = responseEntity.getBody();
        T parsed = JSONObject.parseObject(resp, typeReference);
        return parsed;
    }
   


}

RestTemplate发送请求,配置HTTPS请求忽略SSL证书

/**
 * RestTemplate配置类
 */
@Slf4j
@Configuration
public class RestTemplateConfig {

    /**
     * 忽略Https证书认证RestTemplate
     * @return unSSLRestTemplate
     */
    @Bean("unSSLRestTemplate")
    public RestTemplate unSSLRestTemplate() throws UnSSLRestTemplateCreateException {
        try{
            RestTemplate restTemplate = new RestTemplate(RestTemplateConfig.generateHttpRequestFactory());
            return restTemplate;
        }catch (Exception e){
            log.error(e.getMessage());
            throw new UnSSLRestTemplateCreateException("unSSLRestTemplate bean创建失败,原因为:" + e.getMessage());
        }
    }

    /**
     * 通过该工厂类创建的RestTemplate发送请求时,可忽略https证书认证
     * @return 工厂
     */
    private static HttpComponentsClientHttpRequestFactory generateHttpRequestFactory() throws Exception{
        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;
    }
}

参考:RestTemplate发送请求,配置HTTPS请求忽略SSL证书_普通网友的博客-CSDN博客_resttemplate 忽略证书


RestTemplate Https请求忽略SSL证书_CarsonBigData的博客-CSDN博客

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值