| 123456789101112131415161718192021222324252627282930313233343536 |
- using System.Net.Http.Headers;
- using Microsoft.Extensions.Logging;
- namespace Infrastructure.StockData;
- /// <summary>
- /// OpenDART(opendart.fss.or.kr) 호출 공통 — 인증은 URL query param crtfc_key (헤더 아님, KRX 와 다름).
- /// 호출부가 crtfc_key 를 붙인 완성 URL 을 넘기며, 여기선 Accept json + 간단 3회 재시도(2s/4s 백오프)만 담당.
- /// </summary>
- internal static class OpenDartHttp
- {
- public const string ClientName = "OpenDart";
- private const int MaxAttempts = 3;
- public static async Task<string> GetStringWithRetryAsync(HttpClient client, string url, ILogger logger, CancellationToken ct)
- {
- for (var attempt = 1; ; attempt++)
- {
- try
- {
- using var request = new HttpRequestMessage(HttpMethod.Get, url);
- request.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
- using var response = await client.SendAsync(request, ct);
- response.EnsureSuccessStatusCode();
- return await response.Content.ReadAsStringAsync(ct);
- }
- catch (Exception ex) when (ex is not OperationCanceledException && attempt < MaxAttempts)
- {
- logger.LogWarning(ex, "[OpenDart] HTTP 실패 — 재시도 {Attempt}/{Max}", attempt, MaxAttempts);
- await Task.Delay(TimeSpan.FromSeconds(2 * attempt), ct);
- }
- }
- }
- }
|