Dart - 使用 cookie 请求 GET

Dart - Request GET with cookie

我正在尝试发出获取请求,但我需要放置 cookie。

使用 curl 有效:

curl -v --cookie "sessionid=asdasdasqqwd" <my_site>

但是下面的函数没有带来任何东西

import 'dart:async';
import 'package:http/http.dart' as http;
import 'package:html/parser.dart' as parser;
import 'package:html/dom.dart';

...
parseHtml() async {
   http.Response response = await http.get (
     <my_site>,
     headers: {"sessionid": "asdasdasqqwd"}
   );
   Document document = parser.parse (response.body);
   print(document.text);
}

有什么办法可以在 Dart 中将 cookie 放在 get 请求中吗?

您可以使用 http.get(Url, Headers Map) 函数并在 header 映射中手动创建您的 cookie,但使用 HttpClient 来发出包含 cookie 的请求会更容易:

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);
  });
}

补充答案:

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); // null

    for(Element element in document.getElementsByClassName('your_class')) {
      ...
    }
  });
}

上面的代码工作得很好,下面的代码也工作得很好:

parseHtml() async {
  http.Response response = await http.get(
    'http://www.example.com/',
    headers: {'Cookie': 'sessionid=asdasdasqqwd'}
  );
  Document document = parser.parse(response.body);
  print(document.text); // null

  for(Element element in document.getElementsByClassName('your_class')) {
    ...
  }
}

除了上面rafaelcb21的回答,我还用了下面的方法:

String stringifyCookies(Map<String, String> cookies) =>
      cookies.entries.map((e) => '${e.key}=${e.value}').join('; ');

// Used like so..
http.response response = await http.get(
      'https://google.com', 
      headers: { 'Cookie': stringifyCookies(cookies) });