package com.gs.srmKingDee.service; import com.fasterxml.jackson.databind.DeserializationFeature; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.SerializationFeature; import com.gs.srmKingDee.dto.DeliveryResponse; import okhttp3.*; import org.springframework.stereotype.Service; import java.io.IOException; import java.text.SimpleDateFormat; 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(); objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); objectMapper.setDateFormat(new SimpleDateFormat("yyyy-MM-dd")); objectMapper.configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, false); } public DeliveryResponse sendListRequest(String url, String fbillno, Class responseType) throws IOException { // 创建请求体 FormBody.Builder formBodyBuilder = new FormBody.Builder() .add("fbillno", fbillno); RequestBody requestBody = formBodyBuilder.build(); // 创建请求 Request request = new Request.Builder() .url(url) .post(requestBody) .addHeader("Content-Type", "application/x-www-form-urlencoded") .build(); try (Response response = client.newCall(request).execute()) { if (response.isSuccessful()) { return objectMapper.readValue(response.body().string(), objectMapper.getTypeFactory().constructParametricType(DeliveryResponse.class, responseType)); } else { return handleErrorResponse(response); } } } private DeliveryResponse handleErrorResponse(Response response) throws IOException { DeliveryResponse errorResponse = new DeliveryResponse<>(); errorResponse.setState(String.valueOf(response.code())); // errorResponse.setError(response.message()); // Optionally set other fields like list or total return errorResponse; } }