앱과 서버가 데이터를 주고받기 위해서는 서로 어떻게 대화할지 정해둔 규칙과 방법이 있어야 하고, 그를 기반으로 네트워크 통신을 해야한다. 이런 규칙이 HTTP 와 API 다. 간단하게 요약하자면 다음과 같다.
HTTP : "어떻게 데이터를 보낼지"에 대한 규칙
API : "어떤 데이터를 보낼지"에 대한 규칙
import 'package:http/http.dart' as http;
void main() async {
var url = Uri.parse('https://example.com/data');
var response = await http.get(url);
if (response.statusCode == 200) {
print('Response data: ${response.body}');
} else {
print('Request failed with status: ${response.statusCode}');
}
}
Future와 async/await 구문을 사용하여 비동기 작업을 수행해야 한다. // 비동기 함수 생성
// 반환값 없이 단순하게 요청 응답여부만 확인하기 때문에 void
Future<void> fetchData() async {
// 문자열 형태의 URL을 Uri 객체로 변환
var url = Uri.parse('https://example.com/data');
// get 요청이 완료되면 Response 객체 반환
// Response 객체에는 statusCode, body, headers 등이 포함됨
var response = await http.get(url);
if (response.statusCode == 200) {
print('Response data: ${response.body}');
} else {
print('Request failed with status: ${response.statusCode}');
}
}
var url = Uri.parse('https://example.com/data');
var response = await http.get(
url,
headers: {'Authorization': 'Bearer your_token_here'},
);
var url = Uri.parse('https://example.com/data');
var response = await http.post(
url,
// 헤더 설정
headers: {'Content-Type': 'application/json'},
// 본문 데이터 전송
body: jsonEncode({'key': 'value'}),
);
import 'package:http/http.dart' as http;
import 'dart:convert';
void main() async {
var url = Uri.parse('https://jsonplaceholder.typicode.com/posts');
// GET 요청
var response = await http.get(url);
if (response.statusCode == 200) {
var data = jsonDecode(response.body);
print(data);
} else {
print('Failed to load data');
}
// POST 요청
var postResponse = await http.post(
url,
headers: {'Content-Type': 'application/json'},
body: jsonEncode({'title': 'foo', 'body': 'bar', 'userId': 1}),
);
if (postResponse.statusCode == 201) {
var postData = jsonDecode(postResponse.body);
print(postData);
} else {
print('Failed to post data');
}
}
Get 과 Post 의 차이
DB로 비유하면 GET은 SELECT에 가깝고, POST는 CREATE에 가깝다.
[web] Get과 Post의 차이를 알아보자
HTTP 메서드를 DB 에 비유하면
Get = read (= select)
Post = create
Put = update
Delete = delete
[HTTP] 주요 메서드 5가지 정리(GET / POST / PUT / PATCH / DELETE)
https://www.youtube.com/watch?v=kVKcCFdQAMo
https://www.youtube.com/watch?v=WdXcJdhWcEY&t=15s