OpenDartHttp.cs 1.4 KB

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