AI-accounting-soft/src/main/java/com/accounting/service/K780ApiClient.java

51 lines
1.7 KiB
Java

package com.accounting.service;
import com.accounting.dto.K780Response;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;
@Slf4j
@Component
public class K780ApiClient {
private static final String API_BASE_URL = "https://sapi.k780.com";
private static final String APP = "finance.gold_price";
private static final String APP_KEY = "78346";
private static final String SIGN = "1b502c535927b66d9b888a6d4701bf72";
private static final String FORMAT = "json";
private final RestTemplate restTemplate;
private final ObjectMapper objectMapper;
public K780ApiClient() {
this.restTemplate = new RestTemplate();
this.objectMapper = new ObjectMapper();
}
/**
* 从K780 API获取黄金价格
* @param goldId 黄金品种ID
* @return K780Response
*/
public K780Response fetchGoldPrice(String goldId) {
try {
String url = String.format("%s/?app=%s&goldid=%s&appkey=%s&sign=%s&format=%s",
API_BASE_URL, APP, goldId, APP_KEY, SIGN, FORMAT);
log.info("Fetching gold price from K780 API: {}", url);
String response = restTemplate.getForObject(url, String.class);
K780Response k780Response = objectMapper.readValue(response, K780Response.class);
log.info("K780 API response: {}", k780Response);
return k780Response;
} catch (Exception e) {
log.error("Failed to fetch gold price from K780 API", e);
throw new RuntimeException("获取黄金价格失败: " + e.getMessage(), e);
}
}
}