我正在使用 OAuth2 在 Windows Phone 7 中使用 Google API 做一些工作。
在调用 API 之前,我需要更新访问令牌(如果需要)。
我遇到的问题是等待更新令牌的异步请求完成,然后再继续调用 API。
我已经让它与下面的代码一起工作,但我对它不满意。我正在寻找一种更好的替代方法,而不是在 while 循环中简单地轮询变量。
/// <summary>
/// Calls the API.
/// </summary>
/// <param name="callback">The callback.</param>
/// <param name="api">The API.</param>
/// <param name="queryStrings">The query strings.</param>
public static void CallApi(AsyncCallback callback, string api, Dictionary<string, string> queryStrings = null)
{
var uri = new Uri(string.Format("{0}{1}{2}", ApiBaseUrl, api, queryStrings.ToQueryString()));
if (accessTokenExpires < DateTime.Now.AddSeconds(300))
{
RefreshAccessToken();
}
// Start new thread so we don't lock up the UI thread while waiting
var thread = new Thread(
() =>
{
// Wait for the access token to be updated
while (accessTokenExpires < DateTime.Now.AddSeconds(300)) ;
var request = WebRequest.CreateHttp(uri);
request.Headers["Authorization"] = string.Format("OAuth {0}", accessToken);
request.BeginGetResponse(callback, request);
});
thread.Start();
}
/// <summary>
/// Refresh the access token.
/// </summary>
private static void RefreshAccessToken()
{
if (Config.GoogleOAuthRefreshToken == string.Empty)
{
// TODO - Present the OAuth popup to the user
return;
}
var uri = new Uri(GetTokenUrl);
var request = WebRequest.CreateHttp(uri);
request.Method = "POST";
request.ContentType = "application/x-www-form-urlencoded";
request.BeginGetRequestStream(RefreshToken_GetRequest, request);
}