[flutter] 플러터(Flutter)로 웹 서버와 통신하기
플러터(Flutter) 앱을 개발할 때 웹 서버와 통신해야 하는 경우가 많습니다. 이를 위해 플러터에서는 HTTP 패키지를 제공하고 있어, 웹 서버와의 통신을 쉽게 할 수 있습니다.
HTTP 패키지 설치하기
우선, HTTP 패키지를 플러터 프로젝트에 추가해야 합니다. pubspec.yaml
파일에 다음과 같이 패키지를 추가합니다.
dependencies:
flutter:
sdk: flutter
http: ^0.13.3
이후, 터미널에서 아래 명령어를 입력하여 패키지를 설치합니다.
flutter pub get
웹 서버와 GET 요청 보내기
import 'package:http/http.dart' as http;
void fetchPost() async {
var url = Uri.parse('https://jsonplaceholder.typicode.com/posts/1');
var response = await http.get(url);
print('Response status: ${response.statusCode}');
print('Response body: ${response.body}');
}
위의 예제는 http
패키지를 사용하여 웹 서버에 GET 요청을 보내고, 응답을 출력하는 예제입니다.
웹 서버와 POST 요청 보내기
import 'dart:convert';
import 'package:http/http.dart' as http;
void createPost() async {
var url = Uri.parse('https://jsonplaceholder.typicode.com/posts');
var response = await http.post(
url,
headers: <String, String>{
'Content-Type': 'application/json; charset=UTF-8',
},
body: jsonEncode(<String, String>{
'title': 'foo',
'body': 'bar',
'userId': '1',
}),
);
print('Response status: ${response.statusCode}');
print('Response body: ${response.body}');
}
위의 예제는 http
패키지를 사용하여 웹 서버에 POST 요청을 보내고, 응답을 출력하는 예제입니다.
위와 같이 flutter
에서 HTTP 패키지를 이용하여 웹 서버와 통신할 수 있습니다. API 통신 등의 작업을 할 때 매우 유용하니, 적극 활용해보시기 바랍니다.