diff --git a/AssetManager.Infrastructure/Services/TencentMarketService.cs b/AssetManager.Infrastructure/Services/TencentMarketService.cs index c8d2d80..f05a9c9 100644 --- a/AssetManager.Infrastructure/Services/TencentMarketService.cs +++ b/AssetManager.Infrastructure/Services/TencentMarketService.cs @@ -45,23 +45,38 @@ public class TencentMarketService : ITencentMarketService public async Task GetStockPriceAsync(string symbol) { - _logger.LogInformation("腾讯财经获取股票价格: {Symbol}", symbol); + _logger.LogInformation("[腾讯财经] 获取股票价格: {Symbol}", symbol); // 腾讯财经美股接口:前缀us,大写代码 var url = $"http://qt.gtimg.cn/q=us{symbol.ToUpper()}"; + _logger.LogInformation("[腾讯财经] 请求URL: {Url}", url); + var responseBytes = await _httpClient.GetByteArrayAsync(url); var response = Encoding.GetEncoding("GBK").GetString(responseBytes); + _logger.LogDebug("[腾讯财经] 原始响应: {Response}", response); - if (string.IsNullOrEmpty(response) || !response.Contains("~")) + if (string.IsNullOrEmpty(response)) { - throw new Exception($"腾讯财经接口返回无效数据,标的: {symbol}"); + throw new Exception($"腾讯财经接口返回空数据,标的: {symbol}"); } - // 解析返回数据 - var parts = response.Split('"')[1].Split('~'); - if (parts.Length < 36) + // 解析返回数据:v_usUPRO="200~..." 格式 + var quoteStart = response.IndexOf('"'); + var quoteEnd = response.LastIndexOf('"'); + + if (quoteStart < 0 || quoteEnd <= quoteStart) { - throw new Exception($"腾讯财经返回字段不足,标的: {symbol}"); + throw new Exception($"腾讯财经接口返回格式错误(无引号),标的: {symbol},响应: {response.Substring(0, Math.Min(200, response.Length))}"); + } + + var dataPart = response.Substring(quoteStart + 1, quoteEnd - quoteStart - 1); + var parts = dataPart.Split('~'); + + _logger.LogDebug("[腾讯财经] 字段数量: {Count}, parts[3]={Price}, parts[4]={PrevClose}", parts.Length, parts.Length > 3 ? parts[3] : "N/A", parts.Length > 4 ? parts[4] : "N/A"); + + if (parts.Length < 5) + { + throw new Exception($"腾讯财经返回字段不足,标的: {symbol},字段数: {parts.Length}"); } // 提取字段:[3]=最新价 [4]=昨收价 @@ -75,7 +90,7 @@ public class TencentMarketService : ITencentMarketService prevClose = currentPrice; // 解析失败用当前价当昨收 } - _logger.LogDebug("腾讯财经接口返回 {Symbol}:最新价 {CurrentPrice},昨收价 {PrevClose}", + _logger.LogInformation("[腾讯财经] 成功: {Symbol} 最新价={CurrentPrice},昨收价={PrevClose}", symbol, currentPrice, prevClose); return new MarketPriceResponse