http请求方式GET,POST工具类RestTemplate

http请求方式GET,POST工具类RestTemplate

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.dianping.cat.Cat;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.ResponseEntity;
import org.springframework.web.client.RestTemplate;

import java.net.URLDecoder;
import java.net.URLEncoder;
import java.util.Map;

public class HttpUtils {
    private static final Logger logger = LoggerFactory.getLogger(HttpUtils.class);

    /**
     * 发送GET请求
     * @param url
     * @param param
     * @param responseClass
     * @param <T>
     * @return
     */
    public static <T> T doGet(String url, Object param, Class<T> responseClass) {
        Map<String, Object> map = com.alibaba.fastjson.JSONObject.parseObject(JSON.toJSONString(param));
        StringBuilder sb = new StringBuilder();
        for (String s : map.keySet()) {
            sb.append(s).append("=").append(map.get(s)).append("&");
        }
        String str = sb.substring(0, sb.length() - 1).toString();
        logger.info("doGet,url:{},param:{}", url, str);
        HttpHeaders httpHeaders = new HttpHeaders();
        try {
            RestTemplate restTemplate = new RestTemplate();
            ResponseEntity<String> responseEntity = restTemplate.postForEntity(url + "?" + str, new HttpEntity<>(str, httpHeaders), String.class);
            T t = JSON.parseObject(responseEntity.getBody(), responseClass);
            logger.info("doGet,url:{},result:{}", url, JSON.toJSONString(t));
            return t;
        } catch (Exception e) {
            logger.error("doGet,url:{},error:", url, e);
            Cat.logError(String.format("doGet,url:%s,error:", url), e);
            return null;
        }
    }

    public static <T> T doPost(String url, Object param, Class<T> responseClass) {

        //requestVO请求参数
        org.springframework.http.HttpHeaders requestHeaders = new HttpHeaders();
        requestHeaders.add("Content-Type", "application/json;charset=UTF-8");
        //            requestHeaders.add("User-Agent", "mysite_web");
        requestHeaders.add("connection", "Keep-Alive");
        //            requestHeaders.add("Accept", "application/json;version=3.0;compress=false");

        try {
            RestTemplate template = new RestTemplate();
            //设置参数,输出对象的所有字段,如果未设置则默认为""空格字符串。
            String jsonStr = JSON.toJSONString(param, SerializerFeature.WriteNullStringAsEmpty);
            HttpEntity<String> requestEntity = new HttpEntity<>(URLEncoder.encode(jsonStr), requestHeaders);

            ResponseEntity<String> response = template.exchange(url,
                    HttpMethod.POST, requestEntity, String.class);

            T t = JSON.parseObject(response.getBody(), responseClass);
            logger.info("doPost,url:{},params=[{}],result:{}", url, jsonStr,JSON.toJSONString(t));
            return t;
        } catch (Exception e) {
            logger.error("doPost,url:{},error:", url, e);
            Cat.logError(String.format("doPost,url:%s,error:", url), e);
            return null;
        }

    }

}

 

posted on 2022-11-02 11:44  oktokeep  阅读(292)  评论(0编辑  收藏  举报