【问题标题】:Dart basic auth not working (dart:io) (UPDATED to working code)Dart 基本身份验证不起作用(dart:io)(更新为工作代码)
【发布时间】:2014-02-07 02:54:20
【问题描述】:

我正在使用 Harvest API,这是一个非常标准的 Web 服务 API,我的 curl 请求运行良好,而我的 Dart HttpClient 请求却没有。这是我的 curl 请求(当然是伪装的敏感信息):

curl -H "Content-Type: application/json" \
  -H "Accept: application/json" \
  -u "address@domain.com:password" \
  https://my_domain.harvestapp.com/account/who_am_i

更新 --- 下面的代码现在可以工作了:

HttpClient client = new HttpClient();
client.addCredentials(
  Uri.parse('https://my_domain.harvestapp.com/account/who_am_i'),
  'realm',
  new HttpClientBasicCredentials('address@domain.com', 'password')
);
client.getUrl(Uri.parse('https://my_domain.harvestapp.com/account/who_am_i'))
  .then((HttpClientRequest req) {
    req.headers
      ..add(HttpHeaders.ACCEPT, 'application/json')
      ..add(HttpHeaders.CONTENT_TYPE, 'application/json');

    return req.close();
  })
  .then((HttpClientResponse res) {
    print(res);
    client.close();
  });
}

显然,我想做的不仅仅是print 响应,但无论如何,res 对象最终是null,这意味着请求在某些方面失败了。有什么看起来不对劲或不对劲吗?我现在很茫然。

【问题讨论】:

  • 在调用getUrl 之前尝试调用addCredentials。也可以试试return req.close()
  • @MarioP 从某种意义上说,它会返回一个非空的 res 变量和来自服务器的消息:You must be authenticated with Harvest to complete this request. 但不知何故,身份验证本身似乎并没有通过.
  • 嗯。 Uri.parse的参数不应该也匹配getUrl中的URL吗?
  • @MarioP 你是对的。那是复制和粘贴的错误。不幸的是,仍然不起作用:/
  • @MarioP 实际上,在返回并修复我的复制/粘贴错误时,我注意到一个小错字。上面的代码工作得很好。谢谢!

标签: dart dart-io


【解决方案1】:

总结从原始代码sn-p的变化:

  • 在拨打HttpClient.getUrl之前先拨打HttpClient.addCredentials
  • .then((HttpClientRequest)) 部分,确保return req.close()
  • 确保addCredentialsgetUrl 中的网址匹配。

【讨论】:

    猜你喜欢
    • 2014-09-06
    • 2014-01-22
    • 2016-01-11
    • 2014-12-31
    • 2016-11-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多