Flutter无法在HTTP响应中访问Cookie

时间:2019-10-14 14:34:00

标签: http cookies flutter dart

我正在使用Flutter一款将使用基于Express的REST api的应用程序。在实施基于Cookie的会话时,我想从具有基本身份验证请求的应用程序中检索Cookie,但是以某种方式我无法以响应方式检索Cookie。当我从邮递员发出相同的请求时,没有问题,cookie会自动设置。

我正在使用HTTP程序包发出请求,并且代码非常简单,如下所示。

void login(String username, String password) async {
var url = 'http://$username:$password@111.222.333.444:3333/auth';
var response = await http.get(url);
print('Response header: ${response.headers}');
print('Response status: ${response.statusCode}');
print('Response body: ${response.body}');
}

响应的标题或正文中没有cookie。

2 个答案:

答案 0 :(得分:0)

您必须在标头中调用“ set-cookie”:

var cookies = response.headers['set-cookie'];

答案 1 :(得分:0)

http package get和post操作正在发送不包含Cookie的请求,因此您应该像这样手动放置Cookie:

Response response = await get(url, headers: {'cookie': 'session_id=ufe1nfq69mdi67pnql6n1cs3cv; path=/; HttpOnly='});

但是有一种简单的方法,而无需requests package

手动放置cookie
import 'package:requests/requests.dart';
// ...

// For example post some login request
  var url = "http://yourApilink";
  var body = Map<String, dynamic>();
  body["username"] = username;
  body["password"] = password;
  var request = await Requests.post(url, body: body);
  request.raiseForStatus();
  if(request.statusCode==200) {
    //Successful
    var statusJson = json.decode(utf8.decode(request.bytes()));
//....

// Example for get some other actions
  var url = "http://yourApilink";
  var request = await Requests.get(url);
  request.raiseForStatus();
  print(request.json()['userid']);
  if(request.statusCode==200) {
    //Successful
    var statusJson = json.decode(utf8.decode(request.bytes()));
//....