Dart basic auth not working (dart:io) (UPDATED to working code)

北城余情 提交于 2020-01-05 04:43:07

问题


I'm working with the Harvest API, a pretty standard web service API, and my curl requests are working just fine while my Dart HttpClient requests are not. Here is my curl request (with sensitive information disguised, of course):

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

UPDATE --- The following code now works:

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

Obviously I would like to do more than simply print the response, but no matter what, the res object ends up being null, which means that the request is failing in some respect. Does anything seem awry or amiss? I'm at a loss for now.


回答1:


To summarize the changes from the original code snippet:

  • Call HttpClient.addCredentials before calling HttpClient.getUrl
  • In the .then((HttpClientRequest)) part, make sure to return req.close()
  • Make sure the URLs in addCredentials and getUrl match.


来源:https://stackoverflow.com/questions/21618416/dart-basic-auth-not-working-dartio-updated-to-working-code

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