SpringBoot 之 通过RestTemplate 方式发送http 请求

1.RestUtil:

package com.wzw.common.util;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.*;
import org.springframework.http.client.SimpleClientHttpRequestFactory;
import org.springframework.http.converter.StringHttpMessageConverter;
import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter;
import org.springframework.util.StringUtils;
import org.springframework.web.client.RestTemplate;
import java.nio.charset.StandardCharsets;
import java.util.Arrays;
import java.util.Iterator;
import java.util.Map;

/**
 * Rest 工具类
 */
public class RestUtil {
    
    
    private static final Logger log  =  LoggerFactory.getLogger(RestUtil.class);

    private final static String APPLICATION_JSON_UTF8_VALUE = "application/json; charset=UTF-8";

    /** RestAPI 调用器
     */
    private final static RestTemplate RT;

    static {
    
    
        SimpleClientHttpRequestFactory requestFactory = new SimpleClientHttpRequestFactory();
        requestFactory.setConnectTimeout(3000);
        requestFactory.setReadTimeout(3000);
        RT = new RestTemplate(requestFactory);
        // 手动添加text/plan,text/html格式
        MappingJackson2HttpMessageConverter mappingJackson2HttpMessageConverter = new MappingJackson2HttpMessageConverter();
        mappingJackson2HttpMessageConverter.setSupportedMediaTypes(Arrays.asList(
                MediaType.TEXT_HTML,
                MediaType.TEXT_PLAIN));
        RT.getMessageConverters().add(mappingJackson2HttpMessageConverter);
        // 解决乱码问题
        RT.getMessageConverters().set(1, new StringHttpMessageConverter(StandardCharsets.UTF_8));
    }

    /**
     * 发送请求
     *
     * @param url          请求地址
     * @param method       请求方式
     * @param headers      请求头  可空
     * @param variables    请求url参数 可空
     * @param params       请求body参数 可空
     * @param responseType 返回类型
     * @return ResponseEntity<responseType>
     */
    public static <T> ResponseEntity<T> request(String url, HttpMethod method, HttpHeaders headers, Map<String,Object> variables, String  params, Class<T> responseType) {
    
    
        log.info(" HttpEntityUtil  --- request ---  url = "+ url);
        if (StringUtils.isEmpty(url)) {
    
    
            throw new RuntimeException("url 不能为空");
        }
        if (method == null) {
    
    
            throw new RuntimeException("method 不能为空");
        }
        if (headers == null) {
    
    
            headers = new HttpHeaders();
        }
        // 请求体
        String body = params==null?"":params;
        // 拼接 url 参数
        if (variables != null) {
    
    
            url += ("?" + asUrlVariables(variables));
        }
        // 发送请求
        HttpEntity<String> request = new HttpEntity<>(body, headers);
        return RT.exchange(url, method, request, responseType);
    }

    /**
     * 获取JSON请求头
     */
    public static HttpHeaders getHeaderApplicationJson() {
    
    
        return getHeader(APPLICATION_JSON_UTF8_VALUE);
    }

    /**
     * 获取请求头
     */
    public static HttpHeaders getHeader(String mediaType) {
    
    
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.parseMediaType(mediaType));
        headers.add("Accept", mediaType);
        return headers;
    }

    /**
     * 将 JSONObject 转为 a=1&b=2&c=3...&n=n 的形式
     */
    public static String asUrlVariables(Map<String,Object> source) {
    
    
        Iterator<String> it = source.keySet().iterator();
        StringBuilder urlVariables = new StringBuilder();
        while (it.hasNext()) {
    
    
            String key = it.next();
            String value = "";
            Object object = source.get(key);
            if (object != null) {
    
    
                if (!StringUtils.isEmpty(object.toString())) {
    
    
                    value = object.toString();
                }
            }
            urlVariables.append("&").append(key).append("=").append(value);
        }
        // 去掉第一个&
        return urlVariables.substring(1);
    }
}

2. 使用

 public static String getAccessToken(){
    
    
        RedisService redisService = (RedisService)SpringUtil.getBean("redisService");
        if(!redisService.exists(InterfaceConfiguration.iotRedisKey+InterfaceConfiguration.username)){
    
    
            // 1、获取令牌所需参数
            Map<String,String> params = new HashMap<String,String>(2);
            params.put("username", InterfaceConfiguration.username);
            params.put("password", InterfaceConfiguration.password);
            HttpHeaders header = RestUtil.getHeaderApplicationJson();
            Map<String,String> res = RestUtil.request(InterfaceConfiguration.iotGetTokenUrl,HttpMethod.POST,
                    header,null,MapperUtil.objectToJson(params),Map.class).getBody();
            if(res!=null && res.containsKey("token")) {
    
    
                String token = AUTHORIZATION_PREFIX+res.get("token");
                redisService.set(InterfaceConfiguration.iotRedisKey + InterfaceConfiguration.username, token, InterfaceConfiguration.iotTokenRedisExpireTime);
                return token;
            }
            return null;
        }
        return  (String)redisService.get(InterfaceConfiguration.iotRedisKey+InterfaceConfiguration.username);
    }

猜你喜欢

转载自blog.csdn.net/u014212540/article/details/129534312