restTemplate 工具類

比本身封裝的http工具靠譜,畢竟feign和ribbon也用這個,沒有那麼多須要考慮的地方,apollo也基於restTemplate封裝了一個工具類。默認用的是HttpURLConnection。和okhttp比起來也差不了多少,本人在本地測了一下java

import com.alibaba.fastjson.JSON;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.*;
import org.springframework.util.CollectionUtils;
import org.springframework.util.MultiValueMap;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.client.RestTemplate;

import java.util.Map;

/**
 * @author liyhu
 * @date 2019年09月06日
 */
@Slf4j
public class RestTemplateUtil {
    /**
     * 實際執行請求的template
     */
    private static RestTemplate restTemplate = new RestTemplate();
    public static String put( Object entity,String url){
        return put(entity,url,String.class);
    }

    public static  <T>T put(Object entity,String url, Class<T> cls){
        logParams(RequestMethod.PUT,url,entity);
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON_UTF8);
        HttpEntity<Object> request = new HttpEntity<>(entity,headers);
        ResponseEntity<T> exchange = restTemplate.exchange(url, HttpMethod.PUT, request, cls);
        T result = exchange.getBody();
        log.info("put result:{}",result);
        return result;
    }

    public static String post( Object entity,String url){
        return post(url,entity,String.class);
    }

    /**
     * 獲得 參數的字符串
     * @param entity
     * @return
     */
    private static String getStringParams(Object entity){
        if(entity instanceof String){
            return entity.toString();
        }
        return JSON.toJSONString(entity);
    }

    private static void logParams(RequestMethod method, String url, Object entity){
        String params=getStringParams(entity);
        log.info("{} url:{}  params:{}",method,url,params);
    }
    /**
     * json請求
     */
    public static <T>T post(String url, Object entity, Class<T> cls){
        logParams(RequestMethod.POST,url,entity);
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON_UTF8);
        HttpEntity<Object> request = new HttpEntity<>(entity,headers);
        return executePost(url,request,cls);
    }

    /**
     * 表單請求
     */
    public static <T>T formPost(String url, MultiValueMap<String, Object> params, Class<T> cls){
        logParams(RequestMethod.POST,url,params);
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
        HttpEntity<Object> request = new HttpEntity<>(params,headers);
        return executePost(url,request,cls);
    }

    /**
     * post 請求
     */
    private static <T>T executePost(String url,HttpEntity<Object> request, Class<T> cls){
        ResponseEntity<T> exchange = restTemplate.exchange(url, HttpMethod.POST, request, cls);
        T body = exchange.getBody();
        log.info("post result:{}", body);
        return body;
    }


    public static  String get(String url){
        return get(url,null,String.class);
    }
    /**
     * get 請求
     */
    public static  <T>T get(String url, Map<String,Object> params, Class<T> cls){
        StringBuilder urlBuiler=new StringBuilder(url);
        if(!url.contains("?")){
            urlBuiler.append("?");
        }
        if(!CollectionUtils.isEmpty(params)){
            for (Map.Entry<String, Object> entry : params.entrySet()) {
                urlBuiler.append(entry.getKey()).append("=").append(entry.getValue()).append("&");
            }
        }
        String reqUrl = urlBuiler.toString();
        log.info("get url:{}",reqUrl);
        T result = restTemplate.getForObject(reqUrl, cls);
        log.info("get result:{}", getStringParams(result));
        return result;
    }


}
相關文章
相關標籤/搜索