我正在使用Google Contacts Api。我不确定是否可以发送Auth Token
作为参数。
string _token = _google.Token;
RequestSettings requestSettings = new RequestSettings("AppName",_token);
ContactsRequest contactsRequest = new ContactsRequest(requestSettings);
// Get the feed
Feed<Contact> feed = contactsRequest.GetContacts();
我得到401 Unauthorised
作为此代码的回复,但如果我将用户名和密码作为参数发送,我就能得到回复。
答案 0 :(得分:4)
// 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);
}