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"); } } }