首页 > 解决方案 > Dart - 使用 cookie 请求 GET

问题描述

我正在尝试发出获取请求,但我需要放置 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);
}

有什么方法可以将 cookie 放在 Dart 中的 get 请求上?

标签: requestdartsetcookie

解决方案


为了补充答案:

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')) {
    ...
  }
}

推荐阅读