[dart] HTTP 요청 시에 자동 리다이렉트 처리하기
예를 들어, 다음과 같이 http
패키지를 사용하여 GET 요청을 보내고 있습니다.
import 'package:http/http.dart' as http;
void main() async {
var response = await http.get('https://example.com');
print('Response status: ${response.statusCode}');
print('Response body: ${response.body}');
}
이제 이 요청에 대한 리다이렉트 처리를 추가해 보겠습니다.
import 'package:http/http.dart' as http;
void main() async {
var client = http.Client();
client.head('https://example.com')
.then((response) {
return client.get(response.headers['location']); // 리다이렉트된 URL로 GET 요청을 보냄
})
.then((response) {
print('Response status: ${response.statusCode}');
print('Response body: ${response.body}');
})
.whenComplete(() {
client.close();
});
}
위의 예제에서는 HEAD 요청을 먼저 보내어 리다이렉트된 URL을 가져온 후, 해당 URL에 대해 GET 요청을 보내는 방식으로 자동 리다이렉트를 처리하고 있습니다.
followRedirects
옵션은 기본값이 true
로 설정되어 있어서 리다이렉트를 자동으로 따라갑니다. maxRedirects
옵션은 최대 리다이렉트 횟수를 제어할 수 있는데, 이 값은 디폴트로 5로 설정되어 있습니다.
이와 같이 Dart에서 HTTP 요청 시에 자동 리다이렉트를 처리하는 방법에 대해 간단히 살펴보았습니다.
참고 문서:
- https://pub.dev/documentation/http/latest/http/http-library.html