啊鑫
2025-08-20 721bd249ecfda100ed275c9e9688fdf72adafd4a
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
package com.gs.xiaomi.service;
 
import com.fasterxml.jackson.databind.ObjectMapper;
import com.gs.xiaomi.config.DataAcquisitionConfiguration;
import com.gs.xiaomi.dto.BCS101Request;
import com.gs.xiaomi.util.X5StringUtils;
import okhttp3.*;
import org.springframework.stereotype.Service;
 
import java.io.IOException;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.concurrent.TimeUnit;
 
@Service
public class BCS101ApiService {
 
    private final OkHttpClient client;
    private final ObjectMapper objectMapper;
 
    public BCS101ApiService() {
        this.client = new OkHttpClient.Builder()
                .connectTimeout(3000, TimeUnit.SECONDS)
                .readTimeout(90, TimeUnit.SECONDS)
                .build();
        this.objectMapper = new ObjectMapper();
    }
 
    /**
     * 获取BCS101数据
     *
     * @param request BCS101请求参数
     * @return API响应
     * @throws IOException 网络异常
     */
    public String getBCS101Data(BCS101Request request) throws IOException {
        // 直接将请求对象转换为JSON字符串
        String jsonData = objectMapper.writeValueAsString(request);
 
        // Base64编码
        String base64Data = X5StringUtils.encodeBase64(jsonData);
 
        // URL编码
        String urlEncodedData = URLEncoder.encode(base64Data, String.valueOf(StandardCharsets.UTF_8));
 
        // 构建form表单数据
        String formData = "data=" + urlEncodedData;
 
        // 构建Authorization header
        String credentials = DataAcquisitionConfiguration.BCS_USER_NAME + ":" + DataAcquisitionConfiguration.BCS_PWD;
        String auth = X5StringUtils.encodeBase64(credentials);
 
        // 构建请求体
        RequestBody body = RequestBody.create(formData, MediaType.parse("application/x-www-form-urlencoded"));
 
        // 构建请求
        Request httpRequest = new Request.Builder()
                .url(DataAcquisitionConfiguration.BCS_101_URL)
                .method("POST", body)
                .addHeader("Content-Type", "application/x-www-form-urlencoded")
                .addHeader("Authorization", "Basic " + auth)
                .build();
 
        // 执行请求
        try (Response response = client.newCall(httpRequest).execute()) {
            if (response.body() != null) {
                return response.body().string();
            }
            throw new IOException("Empty response body");
        }
    }
}