| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142 |
- using System.Collections.Generic;
- using System.Text;
- using System.Text.Json;
- using System.Text.Json.Serialization;
- namespace economy.Models.Lotto
- {
- public class LottoModel
- {
- private readonly DhlotteryCoKR _dhlotteryCoKR;
- public LottoModel(DhlotteryCoKR dhlotteryCoKR)
- {
- _dhlotteryCoKR = dhlotteryCoKR;
- }
- // 로또 당첨 번호 조회
- /*
- public async Task<Response> GetLottoNumber(Request request)
- {
- Response parseData = new();
- try
- {
- var uriBuilder = new UriBuilder(_dhlotteryCoKR.APIUrl)
- {
- Path = "/common.do",
- Query = $"method=getLottoNumber&drwNo={request.Number}"
- };
- var response = await _dhlotteryCoKR.httpClient.GetAsync(uriBuilder.Uri);
- // 요청 실패면 바로 예외 발생 -> 아래 파싱 로직으로 진행하지 않음
- response.EnsureSuccessStatusCode();
- var bytes = await response.Content.ReadAsByteArrayAsync();
- // 가능한 경우 서버가 반환한 charset 사용, 없으면 euc-kr를 기본으로 시도
- string? charset = response.Content.Headers.ContentType?.CharSet;
- Encoding encoding;
- try
- {
- encoding = !string.IsNullOrWhiteSpace(charset) ? Encoding.GetEncoding(charset) : Encoding.GetEncoding("euc-kr");
- }
- catch
- {
- // 지원하지 않는 인코딩이면 UTF8로 폴백
- encoding = Encoding.UTF8;
- }
- var content = encoding.GetString(bytes);
- // 응답이 HTML(예: 에러 페이지)로 왔는지 간단히 검사
- var firstNonWhitespace = content?.TrimStart().FirstOrDefault();
- if (firstNonWhitespace == '<')
- {
- Console.WriteLine("API 응답이 JSON이 아닌 HTML로 반환되었습니다. 원본 응답(일부):");
- Console.WriteLine(content.Length > 2000 ? content[..2000] : content);
- return new Response();
- }
- try
- {
- parseData = JsonSerializer.Deserialize<Response>(content) ?? new Response();
- }
- catch (JsonException je)
- {
- // JSON 파싱 에러 시 원본 응답을 로그에 남기고 안전하게 빈 결과 반환
- Console.WriteLine("JSON 파싱 실패. 응답 내용(일부):");
- Console.WriteLine(content.Length > 2000 ? content[..2000] : content);
- Console.WriteLine($"파싱 예외: {je.Message}");
- return new Response();
- }
- }
- catch (HttpRequestException e)
- {
- Console.WriteLine($"Request error: {e.Message}");
- }
- return parseData;
- }
- */
- public async Task<Response> GetLottoNumber(Request request)
- {
- Response parseData = new();
- try
- {
- var uriBuilder = new UriBuilder(_dhlotteryCoKR.APIUrl)
- {
- Path = "/lt645/selectPstLt645Info.do",
- Query = $"srchStrLtEpsd={request.Number}&srchEndLtEpsd={request.Number}"
- };
- var response = await _dhlotteryCoKR.httpClient.GetAsync(uriBuilder.Uri);
- // 요청 실패면 바로 예외 발생 -> 아래 파싱 로직으로 진행하지 않음
- response.EnsureSuccessStatusCode();
- var bytes = await response.Content.ReadAsByteArrayAsync();
- // 가능한 경우 서버가 반환한 charset 사용, 없으면 euc-kr를 기본으로 시도
- string? charset = response.Content.Headers.ContentType?.CharSet;
- Encoding encoding;
- try
- {
- encoding = !string.IsNullOrWhiteSpace(charset) ? Encoding.GetEncoding(charset) : Encoding.GetEncoding("euc-kr");
- } catch {
- encoding = Encoding.UTF8; // 지원하지 않는 인코딩이면 UTF8로 폴백
- }
- var content = encoding.GetString(bytes);
- var jsonOptions = new JsonSerializerOptions
- {
- PropertyNameCaseInsensitive = true,
- NumberHandling = JsonNumberHandling.AllowReadingFromString
- };
- try
- {
- parseData = JsonSerializer.Deserialize<Response>(content, jsonOptions) ?? new Response();
- }
- catch (JsonException je)
- {
- // JSON 파싱 에러 시 원본 응답을 로그에 남기고 안전하게 빈 결과 반환
- Console.WriteLine("JSON 파싱 실패. 응답 내용(일부):");
- Console.WriteLine(content.Length > 2000 ? content[..2000] : content);
- Console.WriteLine($"파싱 예외: {je.Message}");
- return new Response();
- }
- }
- catch (HttpRequestException e)
- {
- Console.WriteLine($"Request error: {e.Message}");
- }
- return parseData;
- }
- }
- }
|