WangHan
2024-09-12 d5855a4926926698b740bc6c7ba489de47adb68b
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
package tech.powerjob.client.service.impl;
 
import com.google.common.collect.Maps;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import okhttp3.*;
import tech.powerjob.client.ClientConfig;
import tech.powerjob.client.common.Protocol;
import tech.powerjob.client.service.HttpResponse;
import tech.powerjob.client.service.PowerRequestBody;
import tech.powerjob.common.OmsConstant;
import tech.powerjob.common.serialize.JsonUtils;
 
import javax.net.ssl.*;
import java.io.IOException;
import java.security.SecureRandom;
import java.util.Map;
import java.util.Optional;
import java.util.Set;
import java.util.concurrent.TimeUnit;
 
/**
 * desc
 *
 * @author tjq
 * @since 2024/2/20
 */
@Slf4j
public class ClusterRequestServiceOkHttp3Impl extends AppAuthClusterRequestService {
 
    private final OkHttpClient okHttpClient;
 
 
    public ClusterRequestServiceOkHttp3Impl(ClientConfig config) {
        super(config);
 
        // 初始化 HTTP 客户端
        if (Protocol.HTTPS.equals(config.getProtocol())) {
            okHttpClient = initHttpsNoVerifyClient();
        } else {
            okHttpClient = initHttpClient();
        }
    }
 
    @Override
    protected HttpResponse sendHttpRequest(String url, PowerRequestBody powerRequestBody) throws IOException {
 
        // 添加公共 header
        powerRequestBody.addHeaders(config.getDefaultHeaders());
 
        Object obj = powerRequestBody.getPayload();
 
        RequestBody requestBody = null;
 
        switch (powerRequestBody.getMime()) {
            case APPLICATION_JSON:
                MediaType jsonType = MediaType.parse(OmsConstant.JSON_MEDIA_TYPE);
                String body = obj instanceof String ? (String) obj : JsonUtils.toJSONStringUnsafe(obj);
                requestBody = RequestBody.create(jsonType, body);
 
                break;
            case APPLICATION_FORM:
                FormBody.Builder formBuilder = new FormBody.Builder();
                Map<String, String> formObj = (Map<String, String>) obj;
                formObj.forEach(formBuilder::add);
                requestBody = formBuilder.build();
        }
 
        Request request = new Request.Builder()
                .post(requestBody)
                .headers(Headers.of(powerRequestBody.getHeaders()))
                .url(url)
                .build();
 
        try (Response response = okHttpClient.newCall(request).execute()) {
 
            int code = response.code();
            HttpResponse httpResponse = new HttpResponse()
                    .setCode(code)
                    .setSuccess(code == HTTP_SUCCESS_CODE);
 
            ResponseBody body = response.body();
            if (body != null) {
                httpResponse.setResponse(body.string());
            }
 
            Headers respHeaders = response.headers();
            Set<String> headerNames = respHeaders.names();
            Map<String, String> respHeaderMap = Maps.newHashMap();
            headerNames.forEach(hdKey -> respHeaderMap.put(hdKey, respHeaders.get(hdKey)));
 
            httpResponse.setHeaders(respHeaderMap);
 
            return httpResponse;
        }
    }
 
    @SneakyThrows
    private OkHttpClient initHttpClient() {
        OkHttpClient.Builder okHttpBuilder = commonOkHttpBuilder();
        return okHttpBuilder.build();
    }
 
    @SneakyThrows
    private OkHttpClient initHttpsNoVerifyClient() {
 
        X509TrustManager trustManager = new NoVerifyX509TrustManager();
 
        SSLContext sslContext = SSLContext.getInstance("TLS");
        sslContext.init(null, new TrustManager[]{trustManager}, new SecureRandom());
        SSLSocketFactory sslSocketFactory = sslContext.getSocketFactory();
 
        OkHttpClient.Builder okHttpBuilder = commonOkHttpBuilder();
 
        // 不需要校验证书
        okHttpBuilder.sslSocketFactory(sslSocketFactory, trustManager);
        // 不校验 url中的 hostname
        okHttpBuilder.hostnameVerifier((String hostname, SSLSession session) -> true);
 
 
        return okHttpBuilder.build();
    }
 
    private OkHttpClient.Builder commonOkHttpBuilder() {
        return new OkHttpClient.Builder()
                // 设置读取超时时间
                .readTimeout(Optional.ofNullable(config.getReadTimeout()).orElse(DEFAULT_TIMEOUT_SECONDS), TimeUnit.SECONDS)
                // 设置写的超时时间
                .writeTimeout(Optional.ofNullable(config.getWriteTimeout()).orElse(DEFAULT_TIMEOUT_SECONDS), TimeUnit.SECONDS)
                // 设置连接超时时间
                .connectTimeout(Optional.ofNullable(config.getConnectionTimeout()).orElse(DEFAULT_TIMEOUT_SECONDS), TimeUnit.SECONDS)
                .callTimeout(Optional.ofNullable(config.getConnectionTimeout()).orElse(DEFAULT_TIMEOUT_SECONDS), TimeUnit.SECONDS);
    }
 
    @Override
    public void close() throws IOException {
 
        // 关闭 Dispatcher
        okHttpClient.dispatcher().executorService().shutdown();
        // 清理连接池
        okHttpClient.connectionPool().evictAll();
        // 清理缓存(如果有使用)
        Cache cache = okHttpClient.cache();
        if (cache != null) {
            cache.close();
        }
    }
}