Dart - Request GET with cookie

给你一囗甜甜゛ 提交于 2019-12-10 13:49:18

问题


I'm trying to make a get request but I need to put the cookie.

Using the curl works:

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

But the function below does not bring anything

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

Would there be any way to put the cookie on the get request in Dart?


回答1:


You could use the http.get(Url, Headers Map) function and manually create your cookies in the header map, but it is easier to make a request with cookies included by using HttpClient:

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



回答2:


To complement the answer:

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

The code above worked perfectly well as well as the code below works perfectly:

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


来源:https://stackoverflow.com/questions/51923063/dart-request-get-with-cookie

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!