教育训练处考试制证系统后端
zf
2023-09-11 154bb6bf7f098a6076dd1bab9f5b304cc17bbed6
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
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
package com.ruoyi.common.signature;
 
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.URLEncoder;
import java.util.Calendar;
import java.util.HashMap;
import java.util.Map;
import org.apache.commons.lang3.RandomStringUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.http.HttpStatus;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPut;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.google.gson.Gson;
 
/**
 * @email 1603559716@qq.com
 * @author: zf
 * @date: 2023/9/7
 * @time: 11:06
 */
public class Signature {
    private static final Logger logger = LoggerFactory.getLogger(Signature.class);
    // 接口服务地址
    static String restSever = "https://inspurtestcx.saws.org.cn/sjjh/api/v1/exam/plan/enroll/download";
    // 应用标识
    static String appKey = "hj92qe";
    // 加密算法
    static String signMethod = "SHA-256";
    // 身份系统签发给应用对接的密钥
    static String appPwd = "dxep6j";
 
    public static void main(String[] args) {
        // 时间戳
        Long ts = Calendar.getInstance().getTime().getTime();
        // 随机数
        String once = RandomStringUtils.randomAlphanumeric(32);
        // 接口header 中的公共参数
        String commonParamUrl = String.format("appKey=%s" + "&" + "ts=%s" + "&" + "once=%s" + "&" + "signMethod=%s", appKey, ts, once, signMethod);
        // 创建HttpClient 对象
        CloseableHttpClient httpclient = (CloseableHttpClient) SkipHttpsUtils.wrapClient();
        /**
         * GET 查询接口演示代码
         */
        String startTime = "2023-05-25 00:00:00";
        String endTime = "2023-06-01 21:00:00";
        try {
            startTime = URLEncoder.encode(startTime, "UTF-8");
            endTime = URLEncoder.encode(endTime, "UTF-8");
        } catch (UnsupportedEncodingException e) {
            throw new RuntimeException(e.getCause());
        }
        String getQueryParam = "startTime=" + startTime + "&endTime=" + endTime;
        System.out.println(getQueryParam);
        String getFullUrl = restSever + "?" + getQueryParam;
        HttpGet httpGet = new HttpGet(getFullUrl);
        // get 请求查询参数, 用在 URL 上的, 这里若是通过 ID 查询的, 接口中 ID 是作为路径存在的, 所以需要将 ID 组合成
        String getAllParamUrl = commonParamUrl + "&" + getQueryParam;
        // 对参数签名, 并放入请求 header 中的 signData 参数中
        try {
            // 签名数据
            String signData = TokenUtils.getSignature(appPwd, getAllParamUrl);
            // 添加 header 参数 appCode、timestamp、signatureNonce、signature
            httpGet.addHeader("appKey", appKey);
            httpGet.addHeader("ts", ts.toString());
            httpGet.addHeader("once", once);
            httpGet.addHeader("signMethod", signMethod);
            System.out.println("once:" + once);
            httpGet.addHeader("signData", signData);
            System.out.println("headers:" + httpGet.getAllHeaders());
            String urlStr = httpGet.getURI().toString();
            // 公共参数 URL
            System.out.println("commonParamter:" + urlStr);
            if (StringUtils.endsWith(urlStr, "/")) {
                urlStr = StringUtils.removeEnd(urlStr, "/");
            }
            httpGet.setURI(new URI(urlStr));
            RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(3000).setConnectionRequestTimeout(3000).setSocketTimeout(3000).build();
            httpGet.setConfig(requestConfig);
            System.out.println("urlStr in request:" + httpGet.getURI().toString());
            // 执行请求
            CloseableHttpResponse response = httpclient.execute(httpGet);
            // 取响应的结果
            int statusCode = response.getStatusLine().getStatusCode();
            // 打印响应结果
            if (statusCode == HttpStatus.SC_OK) {
                String resp = EntityUtils.toString(response.getEntity(), "utf-8");
                System.out.println("status:" + statusCode);
                System.out.println("result:" + resp);
            }
        } catch (URISyntaxException e) {
            logger.error("签名失败: ", e);
        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        /**
         * PUT 修改接口的演示代码,POST 与 PUT 类似
         */
        String ID = "aa03a5c692cf480b87887e0ff8cfe566";
        // 这里若是通过 ID 查询的, 接口中 ID 是作为路径存在的, 所以需要将 ID 组合成
        String putQueryParam = "ID=" + ID;
 
        String putFullUrl = restSever + "/" + ID;
        // 访问用户接口
        HttpPut httpPut = new HttpPut(putFullUrl);
        // 模拟 POST/PUT 的 body 中数据, 需转为 JSON 进行签名。GET 则没有这部分内容。
        Map<String, Object> dataMap = new HashMap<String, Object>();
        dataMap.put("USER_NAME", "张三");
        String bodyParam = new Gson().toJson(dataMap);
        String postAllParamUrl = commonParamUrl + "&" + putQueryParam + "&bodyData=" + bodyParam;
        StringEntity bodyData = new StringEntity(bodyParam.toString(), "UTF-8");
        httpPut.setEntity(bodyData);
        // 对参数签名, 并放入请求 header 中的 signData 参数中
        try {
            // 签名数据
            String signData = TokenUtils.getSignature(appPwd, postAllParamUrl);
            // 添加 header 参数 appCode、timestamp、signatureNonce、signature
            httpPut.addHeader("appKey", appKey);
            httpPut.addHeader("ts", ts.toString());
            httpPut.addHeader("once", once);
            System.out.println("once:" + once);
            httpPut.addHeader("signData", signData);
            System.out.println("headers:" + httpPut.getAllHeaders());
            String urlStr = httpPut.getURI().toString();
            // 公共参数 URL
            System.out.println("commonParamter:" + urlStr);
            if (StringUtils.endsWith(urlStr, "/")) {
                urlStr = StringUtils.removeEnd(urlStr, "/");
            }
            httpPut.setURI(new URI(urlStr));
            RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(3000).setConnectionRequestTimeout(3000).setSocketTimeout(3000).build();
            httpPut.setConfig(requestConfig);
            System.out.println("urlStr in request:" + httpPut.getURI().toString());
            // 执行请求
            CloseableHttpResponse response = httpclient.execute(httpPut);
            // 取响应的结果
            int statusCode = response.getStatusLine().getStatusCode();
            // 打印响应结果
            if (statusCode == HttpStatus.SC_OK) {
                String resp = EntityUtils.toString(response.getEntity(), "utf-8");
                System.out.println("status:" + statusCode);
                System.out.println("result:" + resp);
            }
        } catch (URISyntaxException e) {
            logger.error("签名失败: ", e);
 
        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}