OpenDartHttp.cs 1.6 KB

1234567891011121314151617181920212223242526272829303132333435363738
  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. // OpenDART 는 User-Agent 없는 요청을 302 → /error1.html 로 튕긴다(봇 차단). UA 필수.
  21. request.Headers.UserAgent.ParseAdd("antooza/1.0 (+https://antooza.com)");
  22. using var response = await client.SendAsync(request, ct);
  23. response.EnsureSuccessStatusCode();
  24. return await response.Content.ReadAsStringAsync(ct);
  25. }
  26. catch (Exception ex) when (ex is not OperationCanceledException && attempt < MaxAttempts)
  27. {
  28. logger.LogWarning(ex, "[OpenDart] HTTP 실패 — 재시도 {Attempt}/{Max}", attempt, MaxAttempts);
  29. await Task.Delay(TimeSpan.FromSeconds(2 * attempt), ct);
  30. }
  31. }
  32. }
  33. }