啊鑫
2025-02-12 076dd23c615e66b2c495bb123aadf041940f03b2
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
package com.gs.xky.service;
 
import com.fasterxml.jackson.databind.ObjectMapper;
import com.gs.xky.config.ApiResponse;
import com.gs.xky.config.XkyCommonParam;
import okhttp3.*;
import org.springframework.stereotype.Service;
 
import java.io.IOException;
import java.util.concurrent.TimeUnit;
 
@Service
public class ApiService {
    private final OkHttpClient client;
    private final ObjectMapper objectMapper;
 
    public ApiService() {
        this.client = new OkHttpClient.Builder().connectTimeout(90, TimeUnit.SECONDS) // Set connection timeout
                .readTimeout(90, TimeUnit.SECONDS)    // Set read timeout
                .build();
        this.objectMapper = new ObjectMapper();
    }
 
    public <T> ApiResponse<T> sendListRequest(XkyCommonParam requestBody, Class<T> responseType, String url) throws IOException {
        // 设置请求体的媒体类型为 application/json
        MediaType mediaType = MediaType.parse("application/json");
 
        // 将 ApiCommonParam 对象转换为 JSON 字符串
        String jsonBody = objectMapper.writeValueAsString(requestBody);
 
        // 创建请求体
        RequestBody body = RequestBody.create(mediaType, jsonBody);
 
        Request request = new Request.Builder()
                .url(url)
                .method("POST", body)
                .addHeader("Content-Type", "application/json")
                .addHeader("Accept", "*/*")
                .addHeader("Connection", "keep-alive")
                .build();
 
        try (Response response = client.newCall(request).execute()) {
            if (response.isSuccessful()) {
                return objectMapper.readValue(response.body().string(), objectMapper.getTypeFactory().constructParametricType(ApiResponse.class, responseType));
            } else {
                return handleErrorResponse(response);
            }
        }
    }
 
    private <T> ApiResponse<T> handleErrorResponse(Response response) throws IOException {
        ApiResponse<T> errorResponse = new ApiResponse<>();
        errorResponse.setResult(response.code());
//        errorResponse.setError(response.message());
        // Optionally set other fields like list or total
        return errorResponse;
    }
}