Flutter에서 HTTP 요청 사용하기

남예지·2024년 3월 29일
0

Flutter

목록 보기
5/6

HTTP 요청을 Flutter에서 사용하려면 http 패키지를 사용할 수 있습니다. 이 패키지를 사용하면 간단하게 HTTP GET, POST 등의 요청을 보낼 수 있습니다.

먼저 pubspec.yaml 파일에 http 패키지를 추가해야 합니다.

dependencies:
  flutter:
    sdk: flutter

  http: ^0.12.2

CLI는 요걸루

flutter pub add http

그 다음에는 HTTP GET 요청을 보내는 예제 코드를 살펴봅시다.

import 'package:http/http.dart' as http;

void fetchData() async {
  final response = await http.get('<https://jsonplaceholder.typicode.com/posts/1>');

  if (response.statusCode == 200) {
    // 서버가 200 OK 응답을 반환하면, JSON을 파싱합니다.
  } else {
    // 만약 응답이 성공적이지 않다면, 에러를 던집니다.
    throw Exception('Failed to load data');
  }
}

response


Future<http.Response> fetchAlbum() {
  return http.get(Uri.parse('https://jsonplaceholder.typicode.com/albums/1'));
}

해당 함수는 Future<http.Response> 객체를 반환하는 fetchAlbum 함수입니다. 이 함수는 http.get 메서드를 사용하여 https://jsonplaceholder.typicode.com/albums/1 URL로 HTTP GET 요청을 보내고, 이 요청의 응답을 Future로 반환합니다. 이 Future는 요청이 완료되면 완료됩니다.

HTTP POST 요청을 보내는 예제 코드는 아래와 같습니다.

import 'package:http/http.dart' as http;

void postData() async {
  final response = await http.post(
    '<https://jsonplaceholder.typicode.com/posts>',
    headers: <String, String>{
      'Content-Type': 'application/json; charset=UTF-8',
    },
    body: jsonEncode(<String, String>{
      'title': 'My title',
      'body': 'My text body.',
      'userId': '1',
    }),
  );

  if (response.statusCode == 201) {
    // 서버가 생성된 리소스에 대한 201 CREATED 응답을 반환하면, JSON을 파싱합니다.
  } else {
    // 만약 응답이 성공적이지 않다면, 에러를 던집니다.
    throw Exception('Failed to post data');
  }
}

위의 코드에서는 http.gethttp.post 메서드를 사용하여 HTTP 요청을 보냅니다. 이 요청은 비동기적이므로 asyncawait를 사용하여 요청이 완료될 때까지 기다립니다. 요청이 완료되면 Response 객체를 반환하며, 이 객체에서 응답 데이터를 가져올 수 있습니다.

이거 활용은 오늘 더 해보고 어떻게 응답을 받고 사용하는지 실습해봐야겠다.

profile
총총

0개의 댓글