RestTemplate使用笔记

常用使用模板

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 params = new LinkedMultiValueMap<>();
// 除了map以外,也可以使用string,根据请求头类型来确认
// 这里的请求头是Content-Type: application/x-www-form-urlencoded; charset=UTF-8

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


示例封装的方法:

 public String doPostForBody(String url, MultiValueMap body) {
        HttpHeaders headers = new HttpHeaders();
        // 设置请求类型,根据需要设置
        headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
        // 设置请求头的方式,根据需要设置
        List cookies = new ArrayList<>();
        cookies.add(expendParam.getCookiesStr());
        headers.put(HttpHeaders.COOKIE, cookies);
        // 设置请求boby
        HttpEntity> entity = new HttpEntity<>(body, headers);
        ResponseEntity 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 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 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 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 hearderMap, MultiValueMap 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 hearderMap, MultiValueMap 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 hearderMap,String contentType) {
        HttpHeaders httpHeaders = new HttpHeaders();
        if (hearderMap != null && hearderMap.entrySet() != null){
            for (Map.Entry stringStringEntry:hearderMap.entrySet()){
                httpHeaders.add(stringStringEntry.getKey(),stringStringEntry.getValue());
            }
        }else {
            httpHeaders.add("Content-Type",contentType);
        }
        return httpHeaders;
    }


    public Object doPostForEntity(String path, Map 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 uriParams, JSONObject jsonObject) {
        path = checkPath(path);
        JSONObject forObject = restTemplate.getForObject(path, JSONObject.class, uriParams);
        return forObject;
    }

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

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

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

    //响应请求体,将string格式的请求体转换为实体类
    
    private  T parseResponseData(ResponseEntity responseEntity, TypeReference 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博客

你可能感兴趣的:(http)