我正在尝试获取请求,但我需要放入cookie。
使用卷曲功能:
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请求上?
答案 0 :(得分:1)
您可以使用http.get(Url, Headers Map)
函数并在页眉图中手动创建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);
});
}
答案 1 :(得分:1)
补充答案:
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')) {
...
}
}
答案 2 :(得分:0)
除了上面的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) });