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

2019-08-04 11:59发布

问题:

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.


标签: dart dart-io