3

在获得具有所需权限的身份验证令牌后,我正在尝试访问用户的任务。

请求网址:

https://www.googleapis.com/tasks/v1/lists/%40default/tasks?key={YOUR_API_KEY}

提出请求的代码:

    public void FetchTasks(string url)
    {
        var httpWebRequest = HttpWebRequest.CreateHttp(url);
        httpWebRequest.BeginGetResponse(new AsyncCallback(FinishedWebRequest), httpWebRequest);
    }

    private void FinishedWebRequest(IAsyncResult ar)
    {
        var httpWebRequest = ar.AsyncState as HttpWebRequest;
        var httpWebResponse = (HttpWebResponse) httpWebRequest.EndGetResponse(ar);
        byte[] responseByteArray= new byte[200];
        httpWebResponse.GetResponseStream().Read(responseByteArray, 0, responseByteArray.Length);
    }

回复

    {
 "error": {
  "errors": [
   {
    "domain": "global",
    "reason": "required",
    "message": "Login Required",
    "locationType": "header",
    "location": "Authorization"
   }
  ],
  "code": 401,
  "message": "Login Required"
 }
}

我是否需要其他任何内容作为请求标头的一部分以及 URL 中的身份验证令牌?

4

1 回答 1

4

您需要将AuthorizationHTTP 标头设置access_token为对您想要访问其任务的用户有效。假设您已经完成了 OAuth 2.0 舞蹈并且有一个有效的access_token,您可以通过更改为以下内容来设置标题FetchTasks()

public void FetchTasks(string url, string accessToken)
{
    var httpWebRequest = HttpWebRequest.CreateHttp(url);
    request.Headers.Add("Authorization", "Bearer "+accessToken);
    httpWebRequest.BeginGetResponse(new AsyncCallback(FinishedWebRequest), httpWebRequest);
}

Also, it looks like you're accessing the APIs using HTTP directly. Managing OAuth 2.0 tokens can be a bit cumbersome, You may want to investigate using the official Google .NET API client library which takes care of a lot of the heavy lifting for you.

于 2013-01-06T04:38:32.240 回答