LottoModel.cs 5.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142
  1. using System.Collections.Generic;
  2. using System.Text;
  3. using System.Text.Json;
  4. using System.Text.Json.Serialization;
  5. namespace economy.Models.Lotto
  6. {
  7. public class LottoModel
  8. {
  9. private readonly DhlotteryCoKR _dhlotteryCoKR;
  10. public LottoModel(DhlotteryCoKR dhlotteryCoKR)
  11. {
  12. _dhlotteryCoKR = dhlotteryCoKR;
  13. }
  14. // 로또 당첨 번호 조회
  15. /*
  16. public async Task<Response> GetLottoNumber(Request request)
  17. {
  18. Response parseData = new();
  19. try
  20. {
  21. var uriBuilder = new UriBuilder(_dhlotteryCoKR.APIUrl)
  22. {
  23. Path = "/common.do",
  24. Query = $"method=getLottoNumber&drwNo={request.Number}"
  25. };
  26. var response = await _dhlotteryCoKR.httpClient.GetAsync(uriBuilder.Uri);
  27. // 요청 실패면 바로 예외 발생 -> 아래 파싱 로직으로 진행하지 않음
  28. response.EnsureSuccessStatusCode();
  29. var bytes = await response.Content.ReadAsByteArrayAsync();
  30. // 가능한 경우 서버가 반환한 charset 사용, 없으면 euc-kr를 기본으로 시도
  31. string? charset = response.Content.Headers.ContentType?.CharSet;
  32. Encoding encoding;
  33. try
  34. {
  35. encoding = !string.IsNullOrWhiteSpace(charset) ? Encoding.GetEncoding(charset) : Encoding.GetEncoding("euc-kr");
  36. }
  37. catch
  38. {
  39. // 지원하지 않는 인코딩이면 UTF8로 폴백
  40. encoding = Encoding.UTF8;
  41. }
  42. var content = encoding.GetString(bytes);
  43. // 응답이 HTML(예: 에러 페이지)로 왔는지 간단히 검사
  44. var firstNonWhitespace = content?.TrimStart().FirstOrDefault();
  45. if (firstNonWhitespace == '<')
  46. {
  47. Console.WriteLine("API 응답이 JSON이 아닌 HTML로 반환되었습니다. 원본 응답(일부):");
  48. Console.WriteLine(content.Length > 2000 ? content[..2000] : content);
  49. return new Response();
  50. }
  51. try
  52. {
  53. parseData = JsonSerializer.Deserialize<Response>(content) ?? new Response();
  54. }
  55. catch (JsonException je)
  56. {
  57. // JSON 파싱 에러 시 원본 응답을 로그에 남기고 안전하게 빈 결과 반환
  58. Console.WriteLine("JSON 파싱 실패. 응답 내용(일부):");
  59. Console.WriteLine(content.Length > 2000 ? content[..2000] : content);
  60. Console.WriteLine($"파싱 예외: {je.Message}");
  61. return new Response();
  62. }
  63. }
  64. catch (HttpRequestException e)
  65. {
  66. Console.WriteLine($"Request error: {e.Message}");
  67. }
  68. return parseData;
  69. }
  70. */
  71. public async Task<Response> GetLottoNumber(Request request)
  72. {
  73. Response parseData = new();
  74. try
  75. {
  76. var uriBuilder = new UriBuilder(_dhlotteryCoKR.APIUrl)
  77. {
  78. Path = "/lt645/selectPstLt645Info.do",
  79. Query = $"srchStrLtEpsd={request.Number}&srchEndLtEpsd={request.Number}"
  80. };
  81. var response = await _dhlotteryCoKR.httpClient.GetAsync(uriBuilder.Uri);
  82. // 요청 실패면 바로 예외 발생 -> 아래 파싱 로직으로 진행하지 않음
  83. response.EnsureSuccessStatusCode();
  84. var bytes = await response.Content.ReadAsByteArrayAsync();
  85. // 가능한 경우 서버가 반환한 charset 사용, 없으면 euc-kr를 기본으로 시도
  86. string? charset = response.Content.Headers.ContentType?.CharSet;
  87. Encoding encoding;
  88. try
  89. {
  90. encoding = !string.IsNullOrWhiteSpace(charset) ? Encoding.GetEncoding(charset) : Encoding.GetEncoding("euc-kr");
  91. } catch {
  92. encoding = Encoding.UTF8; // 지원하지 않는 인코딩이면 UTF8로 폴백
  93. }
  94. var content = encoding.GetString(bytes);
  95. var jsonOptions = new JsonSerializerOptions
  96. {
  97. PropertyNameCaseInsensitive = true,
  98. NumberHandling = JsonNumberHandling.AllowReadingFromString
  99. };
  100. try
  101. {
  102. parseData = JsonSerializer.Deserialize<Response>(content, jsonOptions) ?? new Response();
  103. }
  104. catch (JsonException je)
  105. {
  106. // JSON 파싱 에러 시 원본 응답을 로그에 남기고 안전하게 빈 결과 반환
  107. Console.WriteLine("JSON 파싱 실패. 응답 내용(일부):");
  108. Console.WriteLine(content.Length > 2000 ? content[..2000] : content);
  109. Console.WriteLine($"파싱 예외: {je.Message}");
  110. return new Response();
  111. }
  112. }
  113. catch (HttpRequestException e)
  114. {
  115. Console.WriteLine($"Request error: {e.Message}");
  116. }
  117. return parseData;
  118. }
  119. }
  120. }