How do I make an http request using cookies on flutter?

后端 未结 4 936
花落未央
花落未央 2020-12-09 03:11

I\'d like to make an http request to a remote server while properly handling cookies (eg. storing cookies sent by the server, and sending those cookies when I make subsequen

4条回答
  •  伪装坚强ぢ
    2020-12-09 03:33

    Here's an example of how to grab a session cookie and return it on subsequent requests. You could easily adapt it to return multiple cookies. Make a Session class and route all your GETs and POSTs through it.

    class Session {
      Map headers = {};
    
      Future get(String url) async {
        http.Response response = await http.get(url, headers: headers);
        updateCookie(response);
        return json.decode(response.body);
      }
    
      Future post(String url, dynamic data) async {
        http.Response response = await http.post(url, body: data, headers: headers);
        updateCookie(response);
        return json.decode(response.body);
      }
    
      void updateCookie(http.Response response) {
        String rawCookie = response.headers['set-cookie'];
        if (rawCookie != null) {
          int index = rawCookie.indexOf(';');
          headers['cookie'] =
              (index == -1) ? rawCookie : rawCookie.substring(0, index);
        }
      }
    }
    

提交回复
热议问题