|
|
package com.deepchart.utils;
import com.deepchart.entity.StockDailyData;import com.deepchart.entity.StockInfo;import com.fasterxml.jackson.databind.ObjectMapper;import org.springframework.stereotype.Component;
import java.io.BufferedReader;import java.io.InputStreamReader;import java.io.OutputStream;import java.net.HttpURLConnection;import java.net.URL;import java.nio.charset.StandardCharsets;import java.time.LocalDate;import java.time.format.DateTimeFormatter;import java.util.ArrayList;import java.util.HashMap;import java.util.List;import java.util.Map;
/** * 股票行情基本数据工具类 */@Componentpublic class StockDataUtil { private static final String STOCK_DATA_PREFIX = "https://api.homilychart.com/link"; private static final String TOKEN = "8nkj4QBV1RPIb4CzoRTnbZi0+fEeMx8pywnIlrmTxdwROKkuwWqAWu9orpkpeXVqL98DPfeonNYpHv+mucA"; private static final ObjectMapper objectMapper = new ObjectMapper();
public List<StockDailyData> getStockData(StockInfo stock) {
List<List<Object>> kLine20 = List.of();
try { // 1. 构建请求URL
String url = STOCK_DATA_PREFIX + "/api/superBrainData";
// 2. 使用Map构造请求体参数
Map<String, Object> requestBody = new HashMap<>(); requestBody.put("brainPrivilegeState", 1); requestBody.put("marketList", "can,usa,hk,vi,sg,th,in,cn,gb,my"); requestBody.put("market", stock.getMarket()); requestBody.put("code", stock.getCode());
// 3. 将Map转换为JSON字符串
String jsonInputString = objectMapper.writeValueAsString(requestBody);
// 4. 创建HTTP连接
HttpURLConnection connection = (HttpURLConnection) new URL(url).openConnection(); connection.setRequestMethod("POST"); connection.setRequestProperty("Content-Type", "application/json"); connection.setRequestProperty("token", TOKEN); connection.setDoOutput(true);
// 5. 发送请求数据
try (OutputStream os = connection.getOutputStream()) { byte[] input = jsonInputString.getBytes(StandardCharsets.UTF_8); os.write(input, 0, input.length); }
// 6. 解析响应
if (connection.getResponseCode() == 200) { try (BufferedReader br = new BufferedReader( new InputStreamReader(connection.getInputStream(), StandardCharsets.UTF_8))) { StringBuilder response = new StringBuilder(); String responseLine; while ((responseLine = br.readLine()) != null) { response.append(responseLine.trim()); }
// 解析JSON响应
Map<String, Object> jsonResponse = objectMapper.readValue(response.toString(), Map.class); Map<String, Object> data = (Map<String, Object>) jsonResponse.get("data"); Map<String, Object> brain = (Map<String, Object>) data.get("Brain"); kLine20 = (List<List<Object>>) brain.get("KLine20"); } }
// 7. 关闭连接
connection.disconnect();
} catch (Exception e) { e.printStackTrace(); }
List<StockDailyData> list = new ArrayList<>();
for (List<Object> v : kLine20) { StockDailyData s = new StockDailyData(); s.setDate(LocalDate.parse((String) v.get(0), DateTimeFormatter.ofPattern("yyyy/MM/dd"))); s.setOpenPrice((double)v.get(1)); s.setClosePrice((double)v.get(2)); s.setLowPrice((double)v.get(3)); s.setHighPrice((double)v.get(4)); list.add(s); }
return list; }}
|