简体   繁体   English

等待Windows Phone 7上的WebRequest

[英]Waiting on a WebRequest on Windows Phone 7

I'm doing some work with Google APIs in Windows Phone 7 using OAuth2. 我正在使用OAuth2在Windows Phone 7中使用Google API。

Before I can make a call to the API I need to update the access token (if required). 在我可以调用API之前,我需要更新访问令牌(如果需要)。

The issue I'm having is waiting for the async request updating the token to finish before proceeding with call to the API. 我遇到的问题是在继续调用API之前等待更新令牌的异步请求完成。

I've got it working with the code below, but I'm not happy with it. 我已经使用了下面的代码,但我对此并不满意。 I'm looking for a better alternative to simply polling a variable in a while loop. 我正在寻找一个更好的替代方案来简单地轮询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);
    }

I think you have the beginnings of what you need, but just need to use the Async nature of the WebRequest to it's fullest. 我认为你有你需要的开端,但只需要使用WebRequest的Async特性就可以了。 Here is an example of how this can be done 这是一个如何做到这一点的例子

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

    RefreshAccessToken(() =>
        {
            var request = WebRequest.CreateHttp(uri);
            request.Headers["Authorization"] = string.Format("OAuth {0}", accessToken);
            request.BeginGetResponse(callback, request);
        });
}

private static void RefreshAccessToken(Action callback)
{
    if(IsTokenExpired() == false)
    {
        if(callback != null) callback();
        return;
    }
    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(asyncResult =>
    {
        // Do anything for POST
        request.BeginGetResponse(asyncResult2 =>
        {
            // Read stream, and process
            if(callback != null) callback();
        }, null);
    }, request);
}

private bool IsTokenExpired()
{
    return accessTokenExpires < DateTime.Now.AddSeconds(300);
}

Have you considered using the Async-CTP or VS 2012 to convert this logic into a Task.Delay call? 您是否考虑过使用Async-CTP或VS 2012将此逻辑转换为Task.Delay调用? It can probably even help with your web request code. 它甚至可以帮助您的Web请求代码。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM