package com.fs.baidu.utils;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import org.springframework.http.*;
import org.springframework.web.client.RestTemplate;

import java.util.Map;

public class HttpUtils {

    private static final RestTemplate restTemplate;

    static {
        restTemplate = new RestTemplate();
    }

    public static JSONObject sendGet(String url, Map<String, Object> params) {
        return sendGet(url, params, null);
    }
    public static JSONObject sendGet(String url, Map<String, Object> params, Map<String, String> headerList) {
        return send(url, HttpMethod.GET, params, headerList);
    }

    public static JSONObject sendPost(String url, Map<String, Object> params) {
        return sendPost(url, params, null);
    }
    public static JSONObject sendPost(String url, Map<String, Object> params, Map<String, String> headerList) {
        return send(url, HttpMethod.POST, params, headerList);
    }
    private static JSONObject send(String url, HttpMethod method, Map<String, Object> params, Map<String, String> headerList) {
        // 1. 创建 HttpHeaders 对象
        HttpHeaders headers = new HttpHeaders();
        headers.add("Content-Type", "application/json;charset:utf-8;");  // 添加认证头
        if(headerList != null && !headerList.isEmpty()) {
            headerList.forEach(headers::add);
        }
        // 2. 创建 HttpEntity 对象，将请求头放入其中
        HttpEntity<Map<String, Object>> entity = new HttpEntity<>(params, headers);
        // 3. 使用 RestTemplate 发送请求
        ResponseEntity<String> response = restTemplate.exchange(url, method, entity, String.class);
        return JSON.parseObject(response.getBody());
    }

}
