lmw
2023-03-11 4df5bb59e5fe9f9d140e5610f7772dd8a05a28d4
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
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
package com.fuban.driver.netUtls;
 
 
import android.util.Log;
 
import com.fuban.driver.utils.LogUtils;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
 
import org.json.JSONObject;
 
import java.io.File;
import java.io.IOException;
import java.lang.reflect.Type;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;
 
import io.reactivex.Observer;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.schedulers.Schedulers;
import okhttp3.Interceptor;
import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;
import okhttp3.ResponseBody;
import okio.Buffer;
import retrofit2.Retrofit;
import retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory;
import retrofit2.converter.gson.GsonConverterFactory;
 
import static com.fuban.driver.netUtls.NetKitKt.getToken;
 
 
/**
 * 网络请求管理类
 * Created by Administrator on 2018/1/25.
 */
 
public class HttpManager {
    private static HttpManager httpManager;
    private Gson gson;
    private Map<String, String> headerParams;
    private HashMap<String, Object> map;
 
    public static synchronized HttpManager getInstance() {
        if (httpManager == null) synchronized (HttpManager.class) {
            if (httpManager == null) {
                httpManager = new HttpManager();
            }
        }
        return httpManager;
    }
 
 
    /**
     * 初始化请求头,具体情况根据需求设置
     */
    public void initHeader() {
        headerParams = new HashMap<>();
        map = new HashMap<>();
        // 传参方式为json
//        headerParams.put("Content-Type", "application/json");
        headerParams.put("Authorization", "Bearer "+getToken());
    }
 
    public HashMap<String, Object> getMap() {
        if (map == null) {
            map = new HashMap<>();
        }
        map.clear();
        return map;
    }
 
    private static String bodyToString(final RequestBody request) {
        try {
            final RequestBody copy = request;
            final Buffer buffer = new Buffer();
            if (copy != null) {
                copy.writeTo(buffer);
            } else {
                return "";
            }
            return buffer.readUtf8();
        } catch (final IOException e) {
            return "did not work";
        }
    }
 
    /**
     * 初始化数据
     *
     * @param action 当前请求的尾址
     */
    private Retrofit initBaseData(final String action) {
        initHeader();
        // 监听请求条件
        OkHttpClient.Builder builder = new OkHttpClient.Builder();
        builder.connectTimeout(20, TimeUnit.SECONDS);
//        builder.addInterceptor(new Interceptor() {
//            @Override
//            public Response intercept(Chain chain) throws IOException {
//                Request request = chain.request();
//                Request.Builder requestBuilder = request.newBuilder();
//                request = requestBuilder.post(RequestBody.create(MediaType.parse("application/x-www-form-urlencoded;charset=GBK"),
//                        URLDecoder.decode(bodyToString(request.body()), "UTF-8")))
//                        .build();
//                return chain.proceed(request);
//            }
//        });
        builder.addInterceptor(new Interceptor() {
            @Override
            public Response intercept(Chain chain) throws IOException {
                Request request = chain.request();
                Response proceed = chain.proceed(request);
                return proceed;
            }
        });
 
        Retrofit.Builder builder1 = new Retrofit.Builder()
                .client(builder.build())                                    // 配置监听请求
                .addConverterFactory(GsonConverterFactory.create())         // 请求结果转换(当前为GSON)
                .addCallAdapterFactory(RxJava2CallAdapterFactory.create()); // 请求接受工具(当前为RxJava2)
//        builder1.baseUrl(BASE_URL + action.substring(0, action.lastIndexOf("/") + 1));
        builder1.baseUrl(Api.BASE_URL);
 
        return builder1.build();
    }
 
    /**
     * Get请求
     *
     * @param action   请求接口的尾址
     * @param params   请求参数
     * @param observer observer
     */
    //                                         public <T extends BaseBean> void get(final String action,
    public  void get(final String action, Map<String, String> params, Observer<ResponseBody> observer) {
        if (params == null) {
            params = new HashMap<>();
        }
        if (gson == null) {
            gson = new Gson();
        }
 
        ApiServics getService = initBaseData(action).create(ApiServics.class);
        Log.i("zzz", "request====" + new JSONObject(params));
 
//        getService.getResult(action.substring(action.lastIndexOf("/") + 1), headerParams, params)
        getService.getResult(action, headerParams, params)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(observer);
    }
 
 
    /**
     * Post请求
     *
     * @param action 请求接口的尾址
     * @param params 请求参数
     */
//    public <T extends BaseBean> void post(final String action, Map<String, Object> params,
    public void post(final String action, Map<String, Object> params,
                                          Observer<ResponseBody> observer) {
        if (params == null) {
            params = new HashMap<>();
        }
        StringBuilder pwd = new StringBuilder();
        pwd.append(action);
        if (params.size() != 0){
            pwd.append("?");
        }
        Iterator<Map.Entry<String,Object>> iterator = params.entrySet().iterator();
        while (iterator.hasNext()){
            Map.Entry<String, Object> entry = iterator.next();
            pwd.append(entry.getKey()).append("=").append(entry.getValue());
            if (iterator.hasNext()){
                pwd.append("&");
            }
        }
 
        Map<String, Object> par = new HashMap<>();
        ApiServics jsonService = initBaseData(action).create(ApiServics.class);
        LogUtils.d("post", params.toString());
        jsonService.postResult(action,headerParams, params)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(observer);
    }
 
    /**
     * 将map数据转换为 普通的 json RequestBody
     * @param map 以前的请求参数
     * @return
     */
    public static RequestBody convertMapToBody(Map<?,?> map) {
        return RequestBody.create(MediaType.parse("application/json; charset=utf-8"), new JSONObject(map).toString());
    }
 
 
    /**
     * Post请求
     *
     * @param action   请求接口的尾址
     * @param fileName 文件名
     */
    public <T extends BaseBean> void post(final String action, File fileName,
                                          Observer<ResponseBody> observer) {
 
 
        ApiServics service = initBaseData(action).create(ApiServics.class);
 
        // https://github.com/iPaulPro/aFileChooser/blob/master/aFileChooser/src/com/ipaulpro/afilechooser/utils/FileUtils.java
        // use the FileUtils to get the actual file by uri
        File file = fileName;
 
        // create RequestBody instance from file
        RequestBody requestFile =
                RequestBody.create(MediaType.parse("multipart/form-data"), file);
 
        // MultipartBody.Part is used to send also the actual file name
        MultipartBody.Part body =
                MultipartBody.Part.createFormData("picture", file.getName(), requestFile);
        service.upload(action, body)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(observer);
 
    }
 
 
    /**
     * 将json数据转换为map集合
     *
     * @param gsonStr
     * @return
     */
    public Map<String, Object> gsonToMap(String gsonStr) {
        Gson gson = new Gson();
        Type type = new TypeToken<Map<String, Object>>() {
        }.getType();
        Map<String, Object> map = gson.fromJson(gsonStr, type);
        return map;
    }
 
 
    /**
     * 将map集合转为json
     *
     * @param map
     * @return
     */
    public String mapToJson(Map<String, Object> map) {
        String tab_str = "";
        String json = tab_str + "{";
        int i = 0;
        for (String key : map.keySet()) {
            if (i >= map.size())
                break;
            String content = "";
            try {
                List<Map<String, Object>> list = (List<Map<String, Object>>) map.get(key);
                content += "[";
                int j = 0;
                for (Map<String, Object> map2 : list) {
                    if (j == list.size())
                        break;
                    content += mapToJson(map2) + (j++ == list.size() - 1 ? "" : ",");
                }
                content += tab_str + "]"/* + (i == (map.size() - 1) ? "" : ",")*/;
            } catch (Exception e) {
                content = "\"" + map.get(key).toString() + "\"";
            }
            json += tab_str + "\"" + key + "\":" + content + (i++ == map.size() - 1 ? "" : ",");
        }
        json += tab_str + "}";
        return json;
    }
 
}