Created
April 18, 2017 20:30
-
-
Save thosakwe/76ce2e37e504d0b36962fbf593bb51c8 to your computer and use it in GitHub Desktop.
Cookies with Dart
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| import 'dart:convert'; | |
| import 'dart:io'; | |
| main() async { | |
| var client = new HttpClient(); | |
| List<Cookies> sessionCookies = []; // Store our cookies here | |
| // Let's login | |
| var rq = await client.openUrl('POST', 'http://foo.com/login'); | |
| rq.write('username=foo&password=bar'); | |
| var rs = await rq.close(); // Response from server | |
| sessionCookies.addAll(rs.cookies); // Save copies of all cookies from the server. Usually includes a session id token. | |
| rq = await client.openUrl('GET', 'http://foo.com/protected-resource'); | |
| rq.cookies.addAll(sessionCookies); // Send the cookies we've saved | |
| rs = await rq.close(); | |
| String body = await rs.transform(UTF8.decoder).join(); | |
| print('Protected resource contents: $body'); | |
| client.close(); | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Thanks for the useful code.