1
wxr
2023-04-23 2cd55265ccff3b0a267d7953b2dd9e5dca437aa6
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
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
package com.ezviz.demo.common;
 
import com.google.gson.*;
 
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.concurrent.TimeUnit;
 
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;
import okhttp3.ResponseBody;
 
public class HdlHttp
{
    /// <summary>
    /// 请求地址
    /// </summary>
    public static String RequestHttpsHost = "https://test-gz.hdlcontrol.com";
 
    public String HeaderPrefix = "Bearer ";
    public static String HdlToken = "eyJ0eXAiOiJKV1QiLCJhbGciOiJSUzI1NiJ9.eyJqdGkiOiI2YTdlNzExOTAyNTQ0Y2FhOWQyMGVkMDMyNzRmNTE3OCIsInJvbGUiOiIiLCJoZWFkZXJQcmVmaXgiOiJCZWFyZXIgIiwidXNlckFjY291bnQiOiIxODgyNDg2NDE0MyIsInRlbmFudElkIjoiMjAiLCJ1c2VyVHlwZSI6IlVTRVJfQyIsInRva2VuVHlwZSI6ImFjY2Vzc190b2tlbiIsInVzZXJOYW1lIjoiTEUwMDAiLCJhcHBsaWNhdGlvbklkIjoiMCIsInVzZXJJZCI6IjEzMjg4ODYyNzMwMDM4NTU4NzQiLCJleHAiOjE2MTQ5MTM0MzksIm5iZiI6MTYxNDkwNjIzOX0.bx_z4weGI3HfehqKppM3nuegDgVOXvvKAOJFhArdhlO8pKjrnCMv-3t4xtzp8fORwGTjV_Mz4JESAicwsK0tgtkrnUonNqmSizkq2ZyaETiriZFt6333-hi-pyqNoKHTow6-rVIrJHVePOiecS1VGLND0TZ3gMR82KZHrqKmwQ4";
 
    public String RequestResponseFromZigbeeHttps(String i_RequestName, HashMap<String, Object> i_pra) {
        byte[] result = RequestResultFromZigbeeHttps(i_RequestName, i_pra);
        if (result == null) {
            return null;
        }
        String resultData = new String(result);
 
        String code = "";
        String data = "";
        try {
            JsonParser jsonParser = new JsonParser();
            JsonElement element = jsonParser.parse(resultData);
            JsonObject jsonObj = element.getAsJsonObject();
            code = jsonObj.get("code").toString();
            data = jsonObj.get("data").toString();
        } catch (Exception e) {
 
        }
        if (code.equals("0") == false) {
            return null;
        }
        return data;
    }
 
    private byte[] CheckTokenIsTimeOut(byte[] i_result, String i_RequestName, HashMap<String, Object> i_pra)
    {
        if (i_result == null || i_result.length == 0 || i_result[0] != '{' || i_result[i_result.length - 1] != '}')
        {
            //以上都不是正规的json
            return i_result;
        }
        String resultData = new String(i_result);
        String code = "";
        String data = "";
        try {
            JsonParser jsonParser = new JsonParser();
            JsonElement element = jsonParser.parse(resultData);
            JsonObject jsonObj = element.getAsJsonObject();
            code = jsonObj.get("code").toString();
            data = jsonObj.get("data").toString();
        } catch (Exception e) {
 
        }
 
        if (code.equals("-1")  || code.equals("-2"))
        {
            //系统繁忙,请稍后再试
            return null;
        }
        if (code.equals("40001")  || code.equals("10006") )
        {
            return null;
        }
        return i_result;
    }
 
 
    public byte[] RequestResultFromZigbeeHttps(String i_RequestName, HashMap<String, Object> i_pra)
    {
//        Token=MainActivity.token;
        //请求Url的完成路径
        String fullUrl = RequestHttpsHost + "/" + i_RequestName;
        OkHttpClient client = new OkHttpClient.Builder().connectTimeout(30, TimeUnit.SECONDS).build();
 
        MediaType mediaType = MediaType.parse("application/json");
 
        String strBody = this.GetSignRequestJson(new Gson().toJson(i_pra));
 
        RequestBody body = RequestBody.create(mediaType, strBody);
 
        Request request = new Request.Builder().url(fullUrl).post(body)
                .addHeader("Content-Type", "application/json")
                .addHeader("authorization", HeaderPrefix + HdlToken)
                .addHeader("clientType", "2")
                .build();
 
        try
        {
            Response response = client.newCall(request).execute();
            ResponseBody responseBody = response.body();
            InputStream inputStream = responseBody.byteStream();
            byte[] bytes = readInputStream(inputStream);
 
            return CheckTokenIsTimeOut(bytes, i_RequestName, i_pra);
        }
        catch (Exception e)
        {
            e.printStackTrace();
            return null;
        }
    }
 
    private byte[] readInputStream(InputStream inputStream)
    {
        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        byte[] buffer = new byte[1024];
        int len = 0;
        try
        {
            while ((len = inputStream.read(buffer)) != -1)
            {
                outputStream.write(buffer, 0, len);
            }
            byte[] data = outputStream.toByteArray();
            outputStream.close();
            inputStream.close();
            return data;
        }
        catch (IOException e)
        {
            return null;
        }
    }
 
 
    /// <summary>
    /// appKey(访问云端固定的东西)
    /// </summary>
    private String APP_KEY = "HDL-HOME-APP-TEST";
    /// <summary>
    /// 我也不知道这是什么鬼东西
    /// </summary>
    private String SECRET_KEY = "WeJ8TY88vbakCcnvH8G1tDUqzLWY8yss";
 
    /// <summary>
    /// 获取当前时间戳值(访问云端使用)
    /// </summary>
    /// <returns></returns>
    private String GetTimestamp()
    {
        // 相差秒数
        return String.valueOf(System.currentTimeMillis());
    }
 
    /// <summary>
    /// MD5加密
    /// </summary>
    /// <param name="signstr"></param>
    /// <returns></returns>
    private String SignMD5Encrypt(String s)
    {
        try
        {
            byte[] btInput = s.getBytes("utf-8");
            MessageDigest mdInst = MessageDigest.getInstance("MD5");
            mdInst.update(btInput);
            byte[] sign = mdInst.digest();
 
            String signstr = "";
            for (int i = 0; i < sign.length; i++)
            {
                String stmp = Integer.toHexString(sign[i] & 0xff);
                if (stmp.length() == 1)
                {
                    signstr += "0" + stmp;
                }
                else
                {
                    signstr += stmp;
                }
            }
            return signstr.toLowerCase();
        }
        catch (IOException | NoSuchAlgorithmException e)
        {
            return null;
        }
    }
 
    /// <summary>
    /// 基础服务的接口都要校验sign,计算sign签名
    /// </summary>
    /// <param name="i_BodyData">body的数据</param>
    /// <returns></returns>
    private String GetSignRequestJson(String i_BodyData)
    {
        //1. 将model实体转为Dictionary<string, object>
        HashMap<String, Object> paramDictionary = new Gson().fromJson(i_BodyData, HashMap.class);
        //2. 计算sign
        if (paramDictionary != null)
        {
            paramDictionary.put("appKey", APP_KEY);
            paramDictionary.put("timestamp", GetTimestamp());
            //2.1 字典升序
            List<String> listkey = new ArrayList<String>(paramDictionary.keySet());
            Collections.sort(listkey);
 
            //2.2 拼接按URL键值对
            String str = "";
            for (int i = 0; i < listkey.size(); i++)
            {
                String strkey = listkey.get(i);
                Object obj = paramDictionary.get(strkey);
                if (obj == null)
                {
                    //不校验
                    continue;
                }
                String myValue = obj.toString();
                if (myValue == "")
                {
                    //空字符也不校验
                    continue;
                }
                if (obj.getClass() == boolean.class)
                {
                    //云端那帮沙雕说bool类型必须用小写
                    myValue = myValue.toLowerCase();
                }
                str += strkey + "=" + myValue + "&";
            }
            //2.3 拼接SECRET_KEY
            str = str.substring(0, str.length() - 1) + SECRET_KEY;
            //2.4 MD5转换+转小写
            String signstr = SignMD5Encrypt(str);
            paramDictionary.put("sign", signstr);
            return new Gson().toJson(paramDictionary).toString();
        }
        else
        {
            return "";
        }
    }
}