哎呀,对不起,我第一次没有完全正确。我在一个真正的应用程序中使用这个代码,我只是在我的代码中做一些不同的事情,因为我不断地刷新令牌。
无论如何,这是正确的逻辑:
// get this information from Google's API Console after registering your app
var parameters = new OAuth2Parameters
{
ClientId = @"",
ClientSecret = @"",
RedirectUri = @"",
Scope = @"https://www.google.com/m8/feeds/",
};
// generate the authorization url
string url = OAuthUtil.CreateOAuth2AuthorizationUrl(parameters);
// now use the url to authorize the app in the browser and get the access code
(...)
// get this information from Google's API Console after registering your app
parameters.AccessCode = @"<from previous step>";
// get an access token
OAuthUtil.GetAccessToken(parameters);
// setup connection to contacts service
var contacts = new ContactsRequest(new RequestSettings("<appname>", parameters));
// get each contact
foreach (var contact in contacts.GetContacts().Entries)
{
System.Diagnostics.Debug.WriteLine(contact.ContactEntry.Name.FullName);
}
仅供参考,在您调用GetAccessToken()
访问代码后,您的参数数据结构将包括AccessToken
和RefreshToken
字段。如果您存储这两个值,您可以在后续调用中将它们设置在参数结构中(允许您将来跳过请求授权),而不是GetAccessToken()
简单地调用RefreshAccessToken(parameters)
,您将始终可以访问联系人。说得通?在这里,看看:
// get this information from Google's API Console after registering your app
var parameters = new OAuth2Parameters
{
ClientId = @"",
ClientSecret = @"",
RedirectUri = @"",
Scope = @"https://www.google.com/m8/feeds/",
AccessCode = "",
AccessToken = "", /* use the value returned from the old call to GetAccessToken here */
RefreshToken = "", /* use the value returned from the old call to GetAccessToken here */
};
// get an access token
OAuthUtil.RefreshAccessToken(parameters);
// setup connection to contacts service
var contacts = new ContactsRequest(new RequestSettings("<appname>", parameters));
// get each contact
foreach (var contact in contacts.GetContacts().Entries)
{
System.Diagnostics.Debug.WriteLine(contact.ContactEntry.Name.FullName);
}
编辑:
// generate the authorization url
string url = OAuthUtil.CreateOAuth2AuthorizationUrl(parameters);
// now use the url to authorize the app in the browser and get the access code
(...)
// get this information from Google's API Console after registering your app
var parameters = new OAuth2Parameters
{
ClientId = @"",
ClientSecret = @"",
RedirectUri = @"",
Scope = @"https://www.google.com/m8/feeds/",
AccessCode = @"<from previous step>",
};
// get an access token
OAuthUtil.GetAccessToken(parameters);
// setup connection to contacts service
var contacts = new ContactsRequest(new RequestSettings("<appname>", parameters));
// get each contact
foreach (var contact in contacts.GetContacts().Entries)
{
System.Diagnostics.Debug.WriteLine(contact.ContactEntry.Name.FullName);
}