package com.zehong.common.utils; import com.alibaba.fastjson.JSONObject; import com.zehong.common.core.redis.RedisCache; import com.zehong.common.exception.CustomException; import com.zehong.common.utils.http.HttpClientUtils; import org.springframework.beans.factory.annotation.Value; import org.springframework.stereotype.Component; import javax.annotation.Resource; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.concurrent.TimeUnit; @Component public class GovernmentDataUtil { @Resource private RedisCache redisCache; @Value("${zhengfu.appId}") private String appId; @Value("${zhengfu.appSecret}") private String appSecret; @Value("${zhengfu.tokenUrl}") private String tokenUrl; @Value("${zhengfu.apiUrl}") private String apiUrl; /** * 获取token * @return token * @throws Exception */ public String getToken()throws Exception{ String token = redisCache.getCacheObject("apiToken"); if(StringUtils.isEmpty(token)){ token = getNewToken(); } return token; } /** * 获取接口参数 * @return dataInfo * @throws Exception */ public JSONObject getInfo(String domain, String methodType, Map<String,Object> map)throws Exception{ String token = getToken(); JSONObject param = new JSONObject(); param.put("domain", domain); param.put("method", methodType); param.put("condition", map); Map<String,Object> head = new HashMap<>(); head.put("authorization",token); String result = HttpClientUtils.doPost(apiUrl,param.toJSONString(),head); if(StringUtils.isEmpty(result)) throw new CustomException("获取市局数据失败!"); return JSONObject.parseObject(result); } /** * 上传数据 * @param methodType * @param list * @return * @throws Exception */ public JSONObject setInfo(String domain, String methodType, List list)throws Exception{ String token = getToken(); JSONObject param = new JSONObject(); param.put("domain", domain); param.put("method", methodType); param.put("data", list); Map<String,Object> head = new HashMap<>(); head.put("authorization",token); String result = HttpClientUtils.doPost(apiUrl,param.toJSONString(),head); if(StringUtils.isEmpty(result)) throw new CustomException("上传市局数据失败!"); return JSONObject.parseObject(result); } /** * 刷新token * @return token * @throws Exception */ public String getNewToken()throws Exception{ JSONObject param = new JSONObject(); param.put("appId",appId); param.put("appSecret",appSecret); String result = HttpClientUtils.doPost(tokenUrl,param.toJSONString(),null); if(StringUtils.isEmpty(result)) throw new CustomException("获取上报市局token接口失败!"); JSONObject resultJson = JSONObject.parseObject(result); redisCache.setCacheObject("apiToken", resultJson.getJSONObject("data").getString("accessToken"),7000, TimeUnit.SECONDS); return resultJson.getJSONObject("data").getString("accessToken"); } }