乐闻世界logo
搜索文章和话题

How do I make an http request using cookies on flutter?

1个答案

1

In Flutter, to send cookies when making HTTP requests, you typically need to use the http package along with cookie_jar to manage cookies. You can follow these steps to implement it:

  1. Add dependencies: First, ensure that your pubspec.yaml file includes the http and cookie_jar dependencies.
yaml
dependencies: flutter: sdk: flutter http: ^0.13.3 cookie_jar: ^3.0.1
  1. Manage cookies: Use the CookieJar class from the cookie_jar package to manage cookies.

  2. Send cookies when making requests: Before making the request, add the required cookies to the request's headers.

Here is a specific implementation example:

dart
import 'package:http/http.dart' as http; import 'package:cookie_jar/cookie_jar.dart'; // Create a CookieJar instance to manage cookies final cookieJar = CookieJar(); Future<void> fetchResource(String url) async { // Retrieve previously saved cookies List<Cookie> cookies = await cookieJar.loadForRequest(Uri.parse(url)); // Format cookies to match the header format String cookieHeader = cookies.map((cookie) => '${cookie.name}=${cookie.value}').join('; '); // Make HTTP request with cookies final response = await http.get( Uri.parse(url), // Include cookies as headers headers: { 'Cookie': cookieHeader, }, ); // If the response contains a Set-Cookie header, update cookies in cookieJar if (response.headers['set-cookie'] != null) { var setCookies = response.headers['set-cookie']!; cookieJar.saveFromResponse(Uri.parse(url), [Cookie.fromSetCookieValue(setCookies)]); } // Handle response... }

In the above example, we first retrieve all cookies associated with the specified URL using the cookieJar.loadForRequest method. Then, we format these cookies into a string that matches the Cookie header format in HTTP headers. Subsequently, when making the HTTP request, we add this string to the request's headers.

After receiving the server response, if the response contains the Set-Cookie header, we update the cookies in the cookieJar, allowing subsequent requests to use the updated cookies.

It is important to note that since Flutter's HTTP library does not automatically manage cookies, you must manually set the Cookie header for each request and update the cookieJar after the request. This ensures the persistence and validity of the cookies.

2024年6月29日 12:07 回复

你的答案