7

我正在尝试为特定网站制作一个网络爬虫API,该网站在登录后锁定了一些资源,并且登录在 Cookie 中提供了一个会话 ID。当我尝试发布我的登录信息时,会话 ID 没有保存到 CookieJar。

代码:

var dio = new Dio()
..interceptors.add(CookieManager(CookieJar()));

login(String username, String password) async{
    
    (dio.httpClientAdapter as DefaultHttpClientAdapter).onHttpClientCreate = (client) { client.badCertificateCallback = (X509Certificate cert, String host, int port) => true; return client; };
    var response1 =await dio.post("https://www.codestepbystep.com/login", data:{"usernameoremail": username, "password":password, "login":"Login", "userkeepmeloggedin":"on", "after" : "after", "timezone" : "America/Chicago", "timezoneoffset" : "-360"});
    debugPrint(response1.headers.toString());
    var response = await dio.get("https://www.codestepbystep.com/problem/view/c/basics/hello_world");
    debugPrint(response.headers.toString());
  }

POST 标头:

I/flutter (11736): set-cookie: JSESSIONID=60C35F7306479DCC3A6E33C675D05995; Path=/; Secure; HttpOnly
I/flutter (11736): cache-control: no-cache
I/flutter (11736): transfer-encoding: chunked
I/flutter (11736): date: Wed, 04 Sep 2019 22:25:26 GMT
I/flutter (11736): content-type: text/html;charset=ISO-8859-1
I/flutter (11736): server: Apache-Coyote/1.1
I/flutter (11736): expires: Thu, 01 Dec 1994 16:00:00 GMT

获取标题:

I/flutter (11736): content-type: text/html;charset=ISO-8859-1
I/flutter (11736): cache-control: no-cache
I/flutter (11736): date: Wed, 04 Sep 2019 22:25:26 GMT
I/flutter (11736): transfer-encoding: chunked
I/flutter (11736): server: Apache-Coyote/1.1
I/flutter (11736): expires: Thu, 01 Dec 1994 16:00:00 GMT

无论出于何种原因,cookie 不会出现在 GET 标头中,因为 cookie 没有保存。我尝试从 POST 复制标头并在我的 GET 请求中使用它们,但我仍然无法从 GET 访问网站上的特定资源。我怎样才能让cookies正确保存?

4

1 回答 1

0

您应该改用 PersistCookieJar。将 path_provider 和 dio_cookie_manager 包导入您的应用程序并使用如下:

     import 'package:path_provider/path_provider.dart';
     import 'package:dio_cookie_manager/dio_cookie_manager.dart';

     Directory appDocDir = await getApplicationDocumentsDirectory();
        String appDocPath = appDocDir.path;
    
        var cookieJar = PersistCookieJar(
            ignoreExpires: true, storage: FileStorage(appDocPath + "/.cookies/"));
    
        Constants.dio.interceptors.add(CookieManager(cookieJar));
于 2022-01-27T01:39:29.967 回答