maven
10 小时以前 fb3794144800ee442bd632528d16afb14cab891c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
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<String, Object> 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<String, String> 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();
    }
}