0

我正在尝试像这样获取访问令牌,

 string uri = "https://graph.facebook.com/oauth/access_token?client_id=" +
                       APP_ID +
                       "&redirect_uri=&client_secret=" + APP_SECRET + "&grant_type=client_credentials";
            var access_token = GetMyData(uri);
public async Task<string> GetMyData(string urlToCall)
        {
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(urlToCall);
            request.Method = "GET";
            HttpWebResponse response = (HttpWebResponse)await request.GetResponseAsync();
            using (var sr = new StreamReader(response.GetResponseStream()))
            {
                return sr.ReadToEnd();
            }
        }
        public static Task<HttpWebResponse> GetResponseAsync(this HttpWebRequest request)
        {
            var taskComplete = new TaskCompletionSource<HttpWebResponse>();
            request.BeginGetResponse(asyncResponse =>
            {
                try
                {
                    HttpWebRequest responseRequest = (HttpWebRequest)asyncResponse.AsyncState;
                    HttpWebResponse someResponse = (HttpWebResponse)responseRequest.EndGetResponse(asyncResponse);
                    taskComplete.TrySetResult(someResponse);
                }
                catch (WebException webExc)
                {
                    HttpWebResponse failedResponse = (HttpWebResponse)webExc.Response;
                    taskComplete.TrySetResult(failedResponse);
                }
            }, request);
            return taskComplete.Task;
        } 

它卡在 var taskComplete = new TaskCompletionSource(); 并且花费了很多时间并且也没有获得访问令牌。出了什么问题?

4

1 回答 1

1

您可以使用以下代码实现此目的

public void GetMyData(string urlToCall)
{
    HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(urlToCall);
    request.BeginGetResponse(new AsyncCallback(ReadWebRequestCallback), request);
}

private static void ReadWebRequestCallback(IAsyncResult callbackResult)
{
    HttpWebRequest myRequest = (HttpWebRequest)callbackResult.AsyncState;
    HttpWebResponse myResponse = (HttpWebResponse)myRequest.EndGetResponse(callbackResult);

    using (StreamReader httpwebStreamReader = new StreamReader(myResponse.GetResponseStream()))
    {
        // Here you get the result
        string results = httpwebStreamReader.ReadToEnd();               
    }
    myResponse.Close();
}
于 2013-03-22T07:24:58.347 回答