啊鑫
2025-02-25 dc88fd0913da95610d7d67f668357c21f692f55d
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
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 <T> DeliveryResponse<T> sendListRequest(String url, String fbillno, Class<T> 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 <T> DeliveryResponse<T> handleErrorResponse(Response response) throws IOException {
        DeliveryResponse<T> errorResponse = new DeliveryResponse<>();
        errorResponse.setState(String.valueOf(response.code()));
//        errorResponse.setError(response.message());
        // Optionally set other fields like list or total
        return errorResponse;
    }
}