투케이2K

88. (Flutter/플러터) [Mac] : [Dart] : 다트 - Http 요청 시 TimeOut 타임 아웃 지정 방법 및 에러 발생 예외 처리 본문

Flutter

88. (Flutter/플러터) [Mac] : [Dart] : 다트 - Http 요청 시 TimeOut 타임 아웃 지정 방법 및 에러 발생 예외 처리

투케이2K 2024. 5. 31. 18:20
반응형

[개발 환경 설정]

개발 툴 : AndroidStudio

개발 언어 : Dart

 

[소스 코드]

import 'package:flutter/material.dart';
import 'dart:developer';
import 'dart:core';
import 'dart:convert';
import 'package:http/http.dart' as http;


// -----------------------------------------------------------------------------------------
// TODO [main] : [application 의 진입점 역할]
// -----------------------------------------------------------------------------------------
void main() async {

  /**
   * ------------------------------------------------
   * [요약 설명]
   * ------------------------------------------------
   * 1. 필요 import : import 'package:http/http.dart' as http;
   * ------------------------------------------------
   * 2. 패키지 및 라이브러리 설치 방법 참고 사이트 :
   *
   * https://blog.naver.com/kkh0977/223464472300
   * ------------------------------------------------
   * 3. http 라이브러리 설치 사이트 :
   *
   * https://pub.dev/packages/http/install
   * ------------------------------------------------
   * 4. 참고 : http 요청 수행을 하기 위해 main 함수 async 지정
   * ------------------------------------------------
   * */

  // [로직 처리 수행]
  try {

    // [HTTP 요청 URL 주소 정의]
    var url = "https://jsonplaceholder.typicode.com/posts?userId=1&id=1";

    // [HTTP 요청 헤더 지정]
    var headers = Map<String, String>();
    headers["Content-Type"] = "application/x-www-form-urlencoded;";

    var response = await http
        .get(Uri.parse(url), headers: headers) // [http 요청 주소 및 헤더 정의]
        .timeout(const Duration(seconds: 5), // [타임 아웃 지정]
        onTimeout: () {
          throw Exception("Http TimeOut Exception");
        });

    // [response 응답 확인]
    var statusCode = response.statusCode;
    var responseHeaders = response.headers;
    var responseBody = response.body;

    // [로그 출력 수행]
    log("");
    log("-------------------------------------------------------");
    log("requestUrl :: ${url}");
    log("-------------------------------------------------------");
    log("responseStatusCode :: ${statusCode}");
    log("-------------------------------------------------------");
    log("responseHeaders :: ${responseHeaders}");
    log("-------------------------------------------------------");
    log("responseBody :: ${responseBody}");
    log("-------------------------------------------------------");
    log("");

  }
  catch (e) {
    log("");
    log("-------------------------------------------------------");
    log("Catch :: ${e}");
    log("-------------------------------------------------------");
    log("");
  }

}
 

[결과 출력]

 

 

반응형
Comments