wjc
2023-06-29 4a209c4c6ef8b4402114ca26b45dd4bbe869190b
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
package com.hdl.photovoltaic.internet;
 
import android.net.Uri;
import android.text.TextUtils;
 
import androidx.annotation.NonNull;
 
import com.google.gson.Gson;
import com.google.gson.JsonObject;
import com.google.gson.reflect.TypeToken;
import com.hdl.hdlhttp.utils.GsonConvert;
import com.hdl.photovoltaic.bean.HttpResponsePack;
import com.hdl.photovoltaic.config.AppConfigManage;
import com.hdl.photovoltaic.config.UserConfigManage;
import com.hdl.photovoltaic.listener.BaseSuccessFailureCallBeak;
import com.hdl.photovoltaic.other.HdlLogLogic;
import com.hdl.photovoltaic.utils.HDLMD5Utils;
 
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.Objects;
 
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.FormBody;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;
 
public class HttpClient {
 
    private static volatile HttpClient sHttpClient;
 
    public static synchronized HttpClient getInstance() {
        if (sHttpClient == null) {
            synchronized (HttpClient.class) {
                if (sHttpClient == null) {
                    sHttpClient = new HttpClient();
                }
            }
 
        }
        return sHttpClient;
    }
 
    /**
     * 请求服务器的方法
     *
     * @param requestUrl     请求接口
     * @param json           请求数据
     * @param isBasicService 是否是基础服务的接口(基础服务的接口需要 appKey,timestamp,sign这三个参数,当为true时,内部会自动添加)
     * @param isExecute      是否是同步(true=同步,false=异步)
     */
    public void requestHttp(String requestUrl, String json, boolean isBasicService, boolean isExecute, BaseSuccessFailureCallBeak baseSuccessCallBeak) {
        String fullUrl = AppConfigManage.getUserRegionUrl() + requestUrl;
        this.requestHttps(fullUrl, json, isBasicService, isExecute, baseSuccessCallBeak);
    }
 
    /**
     * 请求服务器的方法(目前只用在获取获取账号区域信息)
     *
     * @param fullUrl        绝对地址(地址+接口)
     * @param json           请求数据
     * @param isBasicService 是否是基础服务的接口(基础服务的接口需要 appKey,timestamp,sign这三个参数,当为true时,内部会自动添加)
     * @param isExecute      是否是同步(true=同步,false=异步)
     */
    public void requestFullHttp(String fullUrl, String json, boolean isBasicService, boolean isExecute, BaseSuccessFailureCallBeak baseSuccessCallBeak) {
        this.requestHttps(fullUrl, json, isBasicService, isExecute, baseSuccessCallBeak);
    }
 
    /**
     * 请求服务器的方法
     *
     * @param fullUrl        绝对请求地址
     * @param json           请求数据
     * @param isBasicService 是否是基础服务的接口(基础服务的接口需要 appKey,timestamp,sign这三个参数,当为true时,内部会自动添加)
     * @param isExecute      是否是同步(true=同步,false=异步)
     */
    private void requestHttps(String fullUrl, String json, boolean isBasicService, boolean isExecute, BaseSuccessFailureCallBeak baseSuccessCallBeak) {
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    HdlLogLogic.print("http->发送->", fullUrl + "\r\n" + json);
                    OkHttpClient okHttpClient = new OkHttpClient();
                    RequestBody requestBody = FormBody.create(MediaType.parse("application/json; charset=utf-8"), getJson(json));
                    final Request request = new Request.Builder()
                            .url(fullUrl)//请求的url
                            .addHeader("Authorization", UserConfigManage.getInstance().getHeaderPrefix() + UserConfigManage.getInstance().getToken())
                            .post(requestBody)
                            .build();
                    if (isExecute) {
                        Response response = okHttpClient.newCall(request).execute();//同步
                        if (response.isSuccessful()) {
                            String s = Objects.requireNonNull(response.body()).string();
                            HttpResponsePack httpResponsePack = new Gson().fromJson(s, HttpResponsePack.class);
                            baseSuccessCallBeak.onSuccess(httpResponsePack);
                            HdlLogLogic.print("http->回复->", response.request().url() + "\r\n" + s);
                        } else {
                            //throw new IOException("Unexpected code " + response);
                            baseSuccessCallBeak.onFailure(new Exception());
                        }
                    } else {
 
                        Call call = okHttpClient.newCall(request);
                        call.enqueue(new Callback() {//异步
                            @Override
                            public void onFailure(@NonNull Call call, @NonNull IOException e) {
                                HdlLogLogic.print("http->回复->", "\r\n" + e.getMessage());
                            }
 
                            @Override
                            public void onResponse(@NonNull Call call, @NonNull Response response) throws IOException {
                                System.out.println("url连接信息" + response.code());
                                if (response.code() == 200) {
                                    String s = Objects.requireNonNull(response.body()).string();
                                    HttpResponsePack httpResponsePack = new Gson().fromJson(s, HttpResponsePack.class);
                                    baseSuccessCallBeak.onSuccess(httpResponsePack);
                                    HdlLogLogic.print("http->回复->", "\r\n" + s);
                                } else {
                                    baseSuccessCallBeak.onFailure(new Exception());
                                }
                            }
                        });
                    }
                } catch (Exception e) {
                    baseSuccessCallBeak.onFailure(e);
                    HdlLogLogic.print("http->回复->", "\r\n" + e.getMessage());
                }
 
            }
        }).start();
    }
 
    /**
     * 添加sign字段
     */
    private String getJson(String json) {
        final String timestamp = String.valueOf(System.currentTimeMillis());
        final String appKey = AppConfigManage.getAppKey();
        final String appSecret = AppConfigManage.getAppSecret();
        JsonObject jsonObject = new Gson().fromJson(json, JsonObject.class);
        if (jsonObject == null) {
            jsonObject = new JsonObject();
        }
        jsonObject.addProperty("appKey", appKey);
        jsonObject.addProperty("timestamp", timestamp);
        jsonObject.addProperty("sign", getSign(jsonObject, appSecret));
 
        return jsonObject.toString();
    }
 
    /**
     * 需要按字母排序
     *
     * @param json 所有字段使用urlParameter拼接,除了appSecret
     */
    private String getSign(JsonObject json, String appSecret) {
        String builder = jsonToUrlParameter(json) +
                appSecret;
        return HDLMD5Utils.encodeMD5(builder);
    }
 
 
    private String jsonToUrlParameter(JsonObject object) {
        final Map<String, String> map = GsonConvert.getGson().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 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;
    }
}