It is true that there is no cookie-jar implementation in the dart:io HttpClient.
If you want to have cookie handling you will have to provide your own cookie handling.
Here is a simple example which just blindle forwards the cookies from the redirect response to the next request. Of course this should check whether the cookies match and the redirect chain could be longer than just one redirect.
import 'dart:async';
import 'dart:io';
var client;
Future<HttpClientResponse> makeRequest(Uri uri, List<Cookie> cookies) {
return client.openUrl('GET', uri)
.then((HttpClientRequest request) {
request.cookies.addAll(cookies);
request.followRedirects = false;
return request.close();
}).then((HttpClientResponse response) {
return response;
});
}
main() {
client = new HttpClient();
.then((HttpClientResponse response) {
print(response.statusCode);
print(response.headers);
print(response.cookies);
if (response.statusCode == HttpStatus.FOUND) {
Uri location = Uri.parse(response.headers[HttpHeaders.LOCATION][0]);
print('Redirecting to $location');
makeRequest(location, response.cookies)
.then((HttpClientResponse response) {
print(response.statusCode);
print(response.headers);
print(response.cookies);
});
}
});
}
Same code using async and await (pass --enable-async to the dart executable) - a bit more readable.
import 'dart:async';
import 'dart:io';
var client;
Future<HttpClientResponse> makeRequest(Uri uri, List<Cookie> cookies) async {
var request = await client.openUrl('GET', uri);
request.cookies.addAll(cookies);
request.followRedirects = false;
return await request.close();
}
main() async {
client = new HttpClient();
print(response.statusCode);
print(response.headers);
print(response.cookies);
if (response.statusCode == HttpStatus.FOUND) {
Uri location = Uri.parse(response.headers[HttpHeaders.LOCATION][0]);
print('Redirecting to $location');
response = await makeRequest(location, response.cookies);
print(response.statusCode);
print(response.headers);
print(response.cookies);
}
}
Regards,
Søren Gjesse