2

.NET C# で新しい Toggl API (v8) を使用しようとしています。私のコードは litemedia ( http://litemedia.info/connect-to-toggl-api-with-net ) の例に基づいていますが、元々はバージョン 1 の API 用に作成されたものです。

    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.Unicode.GetBytes() では .NET 文字列で正しい結果が得られなかったため、Encoding.Default.GetBytes() を使用しました。Visual Studio のデフォルト設定に依存しないことを願っています。content-type は「application/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 に答える