package com.ruoyi.api; import cn.hutool.http.Header; import cn.hutool.http.HttpRequest; import cn.hutool.json.JSONUtil; import com.alibaba.fastjson2.JSON; import com.alibaba.fastjson2.JSONObject; import lombok.Data; import lombok.extern.slf4j.Slf4j; import org.springframework.beans.factory.annotation.Value; import org.springframework.stereotype.Component; import java.util.HashMap; import java.util.Map; @Data @Slf4j @Component //榆林市工业和信息化局数据推送 public class Api { @Value("${api.ip}") private String ip; @Value("${api.appid}") private String appid; @Value("${api.secret}") private String secret; //获取token public String getToken(){ try { Map map = new HashMap<>(); map.put("appid", appid); map.put("secret", secret); map.put("grantType", "client_credential"); String result = HttpRequest.get(ip + "/oauth2/client/v1/accessToken") .contentType("none") .form(map).execute().body(); JSONObject jsonObject = JSONObject.parseObject(result); return jsonObject.getString("accessToken"); } catch (Exception e) { throw new RuntimeException("token获取异常"); } } //推送数据 public String pushData(String urlApi,Object data){ String url = ip + urlApi; Map heads = new HashMap<>(); heads.put("Content-Type", "application/json;charset=UTF-8"); heads.put("authorization", "Bearer " + getToken()); String body = HttpRequest.post(url) .headerMap(heads, false) .body(JSONUtil.toJsonStr(data)).execute().body(); return JSON.parseObject(body).get("code").toString(); } }