KoreaEximHttp.cs 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738
  1. using System.Net.Http.Headers;
  2. using Microsoft.Extensions.Logging;
  3. namespace Infrastructure.StockData;
  4. /// <summary>
  5. /// 한국수출입은행(koreaexim.go.kr) OpenAPI 호출 공통 — 인증은 URL query param authkey (헤더 아님, OpenDART 와 동일 방식).
  6. /// 호출부가 authkey + searchdate + data 를 붙인 완성 URL 을 넘기며, 여기선 Accept json + 간단 3회 재시도(2s/4s 백오프)만 담당.
  7. /// </summary>
  8. internal static class KoreaEximHttp
  9. {
  10. public const string ClientName = "KoreaExim";
  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. // 일부 공공 게이트웨이는 UA 없는 요청을 봇으로 차단(OpenDART 사례) — 방어적으로 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, "[KoreaExim] HTTP 실패 — 재시도 {Attempt}/{Max}", attempt, MaxAttempts);
  29. await Task.Delay(TimeSpan.FromSeconds(2 * attempt), ct);
  30. }
  31. }
  32. }
  33. }