Dart - Request GET with cookie

前端 未结 3 1452
伪装坚强ぢ
伪装坚强ぢ 2021-01-05 21:32

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

Using the curl works:

curl -v --cookie \"sessionid=asdasdasqqwd\"

相关标签:
3条回答
  • 2021-01-05 21:53

    I used the following method, in addition to rafaelcb21's answer above:

    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) });
    
    0 讨论(0)
  • 2021-01-05 21:56

    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);
      });
    }
    
    0 讨论(0)
  • 2021-01-05 22:14

    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')) {
        ...
      }
    }
    
    0 讨论(0)
提交回复
热议问题