2

我正在尝试将新的 Toggl API (v8) 与 .NET C# 一起使用。我的代码基于来自 litemedia ( http://litemedia.info/connect-to-toggl-api-with-net ) 的示例,但它最初是为 API 的版本 1 创建的。

    private const string TogglTasksUrl = "https://www.toggl.com/api/v8/tasks.json";
    private const string TogglAuthUrl = "https://www.toggl.com/api/v8/me"; //sessions.json";

    private const string AuthenticationType = "Basic";
    private const string ApiToken = "user token goes here";
    private const string Password = "api_token";

    public static void Main(string[] args)
    {
        CookieContainer container = new CookieContainer();
        var authRequest = (HttpWebRequest)HttpWebRequest.Create(TogglAuthUrl);

        authRequest.Credentials = CredentialCache.DefaultCredentials;
        authRequest.Method = "POST";
        authRequest.ContentType = "application/x-www-form-urlencoded";
        authRequest.CookieContainer = container;

        string value = ApiToken; //= Convert.ToBase64String(Encoding.Unicode.GetBytes(ApiToken));
        value = string.Format("{1}:{0}", Password, value);
        //value = Convert.ToBase64String(Encoding.Unicode.GetBytes(value));
        authRequest.ContentLength = value.Length;
        using (StreamWriter writer = new StreamWriter(authRequest.GetRequestStream(), Encoding.ASCII))
        {
            writer.Write(value);
        }

        try
        {
            var authResponse = (HttpWebResponse)authRequest.GetResponse();
            using (var reader = new StreamReader(authResponse.GetResponseStream(), Encoding.UTF8))
            {
                string content = reader.ReadToEnd();
            }

            HttpWebRequest tasksRequest = (HttpWebRequest)HttpWebRequest.Create(TogglTasksUrl);
            tasksRequest.CookieContainer = container;

            //var jsonResult = string.Empty;
            var tasksResponse = (HttpWebResponse)tasksRequest.GetResponse();
            MemoryStream ms = new MemoryStream();
            tasksResponse.GetResponseStream().CopyTo(ms);
            //using (var reader = new StreamReader(tasksResponse.GetResponseStream(), Encoding.UTF8))
            //{
            //    jsonResult = reader.ReadToEnd();
            //}

            ms.Seek(0, SeekOrigin.Begin);
            DataContractJsonSerializer ser = new DataContractJsonSerializer(typeof(Task));
            var tasks = ser.ReadObject(ms) as List<Task>;
            ms.Close();
            //var tasks = DataContractJsonConvert.DeserializeObject<Task[]>(jsonResult);

            foreach (var task in tasks)
            {
                Console.WriteLine(
                    "{0} - {1}: {2} starting {3:yyyy-MM-dd HH:mm}",
                    task.Project.Name,
                    task.Description,
                    TimeSpan.FromSeconds(task.Duration),
                    task.Start);
            }

        }
        catch (System.Exception ex)
        {

            throw;
        }
    }

以下行返回 404 错误。

                var authResponse = (HttpWebResponse)authRequest.GetResponse();
4

1 回答 1

3

这是有效的代码。由于我最近一直在寻找这个答案,因此可能还有其他人和我一样迷茫。注意:我使用 Encoding.Default.GetBytes() 是因为 Encoding.Unicode.GetBytes() 没有在我的 .NET 字符串上给出正确的结果。我希望它不依赖于 Visual Studio 的默认设置。内容类型是“应用程序/json”。抱歉,我还没有尝试过 POST 版本。

        string ApiToken = "user token goes here";
        string url = "https://www.toggl.com/api/v8/me"; 
        string userpass = ApiToken + ":api_token";
        string userpassB64 = Convert.ToBase64String(Encoding.Default.GetBytes(userpass.Trim()));
        string authHeader = "Basic " + userpassB64;

        HttpWebRequest authRequest = (HttpWebRequest)WebRequest.Create(url);
        authRequest.Headers.Add("Authorization", authHeader);
        authRequest.Method = "GET";
        authRequest.ContentType = "application/json";
        //authRequest.Credentials = CredentialCache.DefaultNetworkCredentials;

        try
        {
            var response = (HttpWebResponse)authRequest.GetResponse();
            string result = null;

            using (Stream stream = response.GetResponseStream())
            {
                StreamReader sr = new StreamReader(stream);
                result = sr.ReadToEnd();
                sr.Close();
            }

            if (null != result)
            {
                System.Diagnostics.Debug.WriteLine(result.ToString());
            }
            // Get the headers
            object headers = response.Headers;
        }
        catch (Exception e)
        {
            System.Diagnostics.Debug.WriteLine(e.Message + "\n" + e.ToString());
        }
于 2013-12-16T06:15:56.747 回答