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 ApiResponse sendListRequest(XkyCommonParam requestBody, Class 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 ApiResponse handleErrorResponse(Response response) throws IOException { ApiResponse errorResponse = new ApiResponse<>(); errorResponse.setResult(response.code()); // errorResponse.setError(response.message()); // Optionally set other fields like list or total return errorResponse; } }