How do I make an http request using cookies on flutter?
Here's an example of how to grab a session cookie and return it on subsequent requests. You could easily adapt it to return multiple cookies. Make a Session
class and route all your GET
s and POST
s through it.
class Session {
Map<String, String> headers = {};
Future<Map> get(String url) async {
http.Response response = await http.get(url, headers: headers);
updateCookie(response);
return json.decode(response.body);
}
Future<Map> post(String url, dynamic data) async {
http.Response response = await http.post(url, body: data, headers: headers);
updateCookie(response);
return json.decode(response.body);
}
void updateCookie(http.Response response) {
String rawCookie = response.headers['set-cookie'];
if (rawCookie != null) {
int index = rawCookie.indexOf(';');
headers['cookie'] =
(index == -1) ? rawCookie : rawCookie.substring(0, index);
}
}
}
Dart - Request GET with cookie
You could use the http.get(Url, Headers Map)
function and manually create your cookies in the header map, but it is easier to make a request with cookies included by using HttpClient
:
import 'dart:convert';
import 'dart:io';
import 'package:html/dom.dart';
import 'package:html/parser.dart' as parser;
parseHtml() async {
HttpClient client = new HttpClient();
HttpClientRequest clientRequest =
await client.getUrl(Uri.parse("http: //www.example.com/"));
clientRequest.cookies.add(Cookie("sessionid", "asdasdasqqwd"));
HttpClientResponse clientResponse = await clientRequest.close();
clientResponse.transform(utf8.decoder).listen((body) {
Document document = parser.parse(body);
print(document.text);
});
}
How to get a cookie in Flutter Web from header?
The question was asked a month ago but my answer might be helpful for someone else.
Cookies in Flutter Web are managed by browser - they are automatically added to requests (to Cookie header), if the cookie was set by Set-Cookie previously - more precisely, it works correctly when you do release build.
In my case it didn't work during dev builds. My solution:
On server set headers:
Access-Control-Allow-Credentials: true
Access-Control-Allow-Origin: http://localhost:61656
// port number may be different
In flutter:
class member:
final http.Client _client = http.Client();
// example
Future<String> getTestString() async {
if (_client is BrowserClient)
(_client as BrowserClient).withCredentials = true;
await _client.get('https://localhost/api/login');
await _client.get('https://localhost/api/login');
return 'blah';
}
http.Client() creates an IOClient if dart:io is available and a BrowserClient if
dart:html is available - in Flutter Web dart:html is available.
Setting withCredentials to true makes cookies work.
Run your app:
flutter run -d chrome --web-port=61656
// the same port number that on server
Remember that in Flutter Web network requests are made with browser XMLHttpRequest.
How to POST in Flutter with cookie or session?
Check out requests
- as of now, it uses shared_preferences which is not the best practice (security-wise) to store sensitive data (session-ids etc) Issue #1
pubspec.yaml
dependencies:
requests: ^1.0.0
Usage:
import 'package:requests/requests.dart';
ajaxPost() async {
// this will persist cookies
await Requests.post("http://example.com/app/oauth/authorize", body: {"username":"...", "password":"..."} );
// next requests will re-use the persisted cookies
dynamic data = await Requests.get("http://example.com/app/foo", json: true);
}
Flutter http how to get header set-cookie from response?
try following
Map<String, List<String>> setCookie = response.headers.map['set-cookie'];
this will give you a map, you can then iterate and pick the relevant data
Related Topics
Android Sdk 22 - Searchview Rendering Problems
Refresh Fragment UI from Fragmentactivity
Quaternion Rotation Does Not Work as Excepted
How to Determine Which Dependency Causes Google Play Openssl Warning
Why Do Most Fields (Class Members) in Android Tutorial Start with 'M'
How to Have a Transparent Imagebutton: Android
How to Show an Empty View with a Recyclerview
Switching to Landscape Mode in Android Emulator
Android:Inapp Purchase Receipt Validation Google Play
How to Get Color-Int from Color Resource
Error: No Toolchains Found in the Ndk Toolchains Folder for Abi with Prefix: Llvm
Java.Lang.Noclassdeffounderror:Failed Resolution of :Lorg/Apache/Http/Protocolversion
Wrap_Content View Inside a Constraintlayout Stretches Outside the Screen
How to Export Library to Jar in Android Studio
How to Make Custom Dialog with Rounded Corners in Android
How to Use the Paid Version of My App as a "Key" to the Free Version