Hunter0x7c7
2023-08-11 198dd6e1b210758867eed417bf6e00ba733d47c0
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
package com.github.hunter0x7c7.sync.model.server.net.interceptors;
 
 
import com.github.hunter0x7c7.sync.model.server.BaseServiceClient;
import okhttp3.HttpUrl;
import okhttp3.Interceptor;
import okhttp3.Request;
import okhttp3.Response;
 
import java.io.IOException;
import java.util.List;
import java.util.Set;
 
public class HeaderInterceptors implements Interceptor {
    @Override
    public Response intercept(Chain chain) throws IOException {
        //打印日志
        if (BaseServiceClient.isDebugMode()) {
            printLog(chain.request().url());
        }
        try {
            return chain.proceed(chain.request());
        } catch (Exception e) {
            e.printStackTrace();
        }
        return new Response.Builder().build();
//        return addHeader(chain);    //添加header
    }
 
    /**
     * 使用拦截器,统一添加header
     */
    private Response addHeader(Chain chain) throws IOException {
        Request original = chain.request();
        Request request = original.newBuilder()
                .header("token", "0df80200-5b21-44b7-a515-a93eafa6227a636598210104279494")
                .method(original.method(), original.body())
                .build();
        return chain.proceed(request);
    }
 
    /**
     * 打印日志
     */
    private void printLog(HttpUrl url) {
        Set<String> stringSet = url.queryParameterNames();
 
        StringBuilder sb = new StringBuilder();
        sb.append("{");
        for (String key : stringSet) {
            if (sb.length() > 1) {
                sb.append(",");
            }
            sb.append("\"").append(key).append("\":");
            List<String> values = url.queryParameterValues(key);
            if (values != null) {
                if (values.size() > 0) {
                    String str = values.get(0);
                    if ((str.startsWith("[") && str.endsWith("]")) || (str.startsWith("{") && str.endsWith("}"))) {
                        sb.append(str);
                    } else {
                        sb.append("\"");
                        sb.append(str);
                        sb.append("\"");
                    }
                }
            }
            if (String.valueOf(sb).endsWith(":")) {
                sb.append("\"\"");
            }
        }
        sb.append("}");
        if (BaseServiceClient.isDebugMode()) {
            System.out.println("intercept request:" + sb.toString() + " url:" + url);
        }
    }
 
}