package cn.cecep.talroad.util;

import cn.cecep.talroad.common.core.utils.SpringUtils;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
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.HttpClientErrorException;
import org.springframework.web.client.RestTemplate;

import java.util.HashMap;
import java.util.Map;

public class HttpUtils {

    /**
     * post 请求
     */
    public static String post(String url, Map<String, Object> param,String token) {
        RestTemplate restTemplate = SpringUtils.getBean(RestTemplate.class);

        HttpHeaders headers = new HttpHeaders();
        if(token!=null){
            headers.add("Authorization", token);
        }
        headers.add("Accept", "application/json");
        headers.add("Content-Encoding", "UTF-8");
        headers.add("Content-Type", "application/json; charset=UTF-8");

        String body = param == null ? "{}" : JSON.toJSONString(param);
        HttpEntity<String> requestEntity = new HttpEntity<>(body, headers);
        return restTemplate.postForObject(url, requestEntity, String.class);
    }

    /**
     * get 请求
     */
    public static ResponseEntity<String> get(String url,String token) {
        RestTemplate restTemplate = SpringUtils.getBean(RestTemplate.class);

        HttpHeaders headers = new HttpHeaders();
        if(token!=null){
            headers.add("Authorization", token);
        }
        headers.add("Accept", "application/json");
        headers.add("Content-Encoding", "UTF-8");
        headers.add("Content-Type", "application/json; charset=UTF-8");

        HttpEntity<String> requestEntity = new HttpEntity<>(null, headers);

        try {
            return restTemplate.exchange(url, HttpMethod.GET, requestEntity, String.class);
        } catch (HttpClientErrorException e) {
            String bodyAsString = e.getResponseBodyAsString();
            return new ResponseEntity<>(bodyAsString, e.getStatusCode());
        }
    }

}
