hxb
2022-11-22 b3513b1713bb979d0a69c5a8c4ddcd038f184e6e
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
package com.mm.android.deviceaddmodule.openapi;
 
import android.net.Uri;
import android.text.TextUtils;
 
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import com.google.gson.reflect.TypeToken;
import com.mm.android.deviceaddmodule.mobilecommon.utils.LogUtil;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URL;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;
 
import javax.net.ssl.HttpsURLConnection;
 
public class HttpClient {
    private static final String TAG=HttpClient.class.getSimpleName();
    /**
     * post
     *
     * @param urlStr
     * @param paramStr
     * @param contentType
     * @param debugTag
     * @return
     */
    public static String post(String urlStr, String paramStr, String contentType, String debugTag,int timeOut) throws IOException {
        LogUtil.debugLog(TAG,urlStr+"..."+paramStr);
        HttpsURLConnection conn = null;
        String resultData = "";
        OutputStream outputStream = null;
        InputStream inputStream = null;
        ByteArrayOutputStream baos = null;
        try {
            URL url = new URL(urlStr);
            conn = (HttpsURLConnection) url.openConnection();
            conn.setHostnameVerifier(SSLSocketClient.getHostnameVerifier());
            conn.setConnectTimeout(timeOut);
            conn.setReadTimeout(timeOut);
            conn.setDoOutput(true);
            conn.setDoInput(true);
            conn.setRequestMethod("POST");
            conn.setUseCaches(false);
            conn.setInstanceFollowRedirects(true);
            conn.setRequestProperty("Content-Type", contentType);
            conn.setRequestProperty("Authorization","Bearer eyJ0eXAiOiJKV1QiLCJhbGciOiJSUzI1NiJ9.eyJqdGkiOiI5MWFjM2FlOWVlMDY0MDY4OWU2NmQzMjQ3MzkxZmQ3MiIsImNvbXBhbnlJZCI6IjIwMiIsInJvbGUiOiIiLCJoZWFkZXJQcmVmaXgiOiJCZWFyZXIgIiwidXNlckFjY291bnQiOiJ3eHIiLCJ0ZW5hbnRJZCI6IjIwIiwidXNlclR5cGUiOiJVU0VSX0IiLCJ0b2tlblR5cGUiOiJhY2Nlc3NfdG9rZW4iLCJ1c2VyTmFtZSI6Ind4ciIsIm9wZW5BcHBsaWNhdGlvbklkIjoiMCIsInVzZXJJZCI6IjEzOTIwMzU1NjgyMDQ0MjMxNjkiLCJleHAiOjE2NjkxMDE2NTEsIm5iZiI6MTY2OTA5NDQ1MX0.BhY5cZDds87lpCOVscCjiH-EnvFSuOFjgXvVkWvGr4elUHFwFTNumhtvfCcQY4Nbu0MNTaPbb36ydNPtXHLAZrXVPdijk_WvnhoTBvA_RUOZOrQ1G4Iep3ZjgHuHam1bsCmgATQqDJR66q3ZiLwe5o_Snce2rAK4aI2Das9uN_M");
            conn.connect();
            outputStream = conn.getOutputStream();
            outputStream.write(paramStr.getBytes());
            outputStream.flush();
            outputStream.close();
            int responseCode = conn.getResponseCode();
            if (debugTag != null)
                LogUtil.debugLog(debugTag, "response code " + responseCode);
            if (200 == responseCode) {
                inputStream = conn.getInputStream();
                byte[] buffer = new byte[1024];
                baos = new ByteArrayOutputStream();
                boolean var13 = true;
                int len;
                while ((len = inputStream.read(buffer)) != -1) {
                    baos.write(buffer, 0, len);
                }
                byte[] b = baos.toByteArray();
                resultData = new String(b, "utf-8");
                baos.flush();
                if (debugTag != null)
                    LogUtil.debugLog(debugTag, "request data " + resultData);
            } else
                throw new IOException(String.format("http_get failed: status=%d", responseCode));
        } catch (IOException e) {
            throw e;
        } catch (Throwable e) {
            throw new IOException(e);
        } finally {
            try {
                if (outputStream != null) {
                    outputStream.close();
                }
                if (baos != null) {
                    baos.close();
                }
                if (inputStream != null) {
                    inputStream.close();
                }
            } catch (IOException e) {
            }
            if (conn != null) {
                conn.disconnect();
            }
        }
        return resultData;
    }
 
 
    /**
     * 需要按字母排序
     *
     * @param json 所有字段使用urlParameter拼接,除了appSecret
     */
    public static String getSign(JsonObject json, String appSecret) {
        String builder = jsonToUrlParameter(json) +
                appSecret;
        return HDLMD5Utils.encodeMD5(builder);
    }
 
 
    private static JsonObject getBodyJson(Map<String,Object> map) {
 
        JsonObject object = new JsonObject();
 
        for (Map.Entry<String, Object> entry : map.entrySet()) {
            object.addProperty(entry.getKey(), entry.getValue().toString());
        }
        return object;
    }
 
 
 
 
    /**
     * 添加sign字段
     */
    public static JsonObject encrypt(Map<String,Object> map ) {
        final String timestamp = String.valueOf(System.currentTimeMillis());
        final String appKey ="HDL-HOME-APP-TEST";
        final String appSecret ="WeJ8TY88vbakCcnvH8G1tDUqzLWY8yss";
        final JsonObject json = getBodyJson(map);
        if (json != null) {
            json.addProperty("appKey", appKey);
            json.addProperty("timestamp", timestamp);
            json.addProperty("sign", getSign(json, appSecret));
        }
        return json;
    }
 
 
 
    private static String jsonToUrlParameter(JsonObject object) {
        final Map<String, String> map = new Gson().fromJson(object, new TypeToken<Map<String, String>>() {
        }.getType());
        final Uri.Builder builder = new Uri.Builder();
        List<String> list = new ArrayList<>(map.keySet());
        Collections.sort(list);
        for (String key : list) {
            //判断当前值是否需要参与签名,保持跟云端一致
            if (IfValueNeedSign(map.get(key))) {
                builder.appendQueryParameter(key, map.get(key));
//                HDLSDKLog.e("要签名:" + key + " :" + map.get(key));
            } else {
//                HDLSDKLog.e("不需要签名:" + key + " :" + map.get(key));
            }
        }
        return builder.build().getQuery();
    }
 
    /**
     * 判断当前值是否需要参与签名,保持跟云端一致
     * 空字符串不参与
     * 数组,集合,对象不参与
     *
     * @param valueStr
     * @return
     */
    private static boolean IfValueNeedSign(String valueStr) {
        if (TextUtils.isEmpty(valueStr))
            return false;
        final char[] strChar = valueStr.substring(0, 1).toCharArray();
        final char firstChar = strChar[0];
        //System.out.println("getJSONType firstChar = "+firstChar);
        if (firstChar != '{' && firstChar != '[')
            return true;
 
        return false;
    }
 
}