Solved

Toggl API with C# (The remote server returned an error: (407) Proxy Authentication Required.)

Posted on 2013-11-17
4
1,354 Views
Last Modified: 2013-11-18
Hi All,

i was trying to call the toggl API using c# but its throwing the above exception at " using (StreamWriter writer = new StreamWriter(authRequest.GetRequestStream(), Encoding.ASCII))"

 please correct me what im doing wrong

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;
using System.IO;
using System.Net;

public class Program
{
    private const string TogglTasksUrl = "https://toggl.com/reports/api/v2/tasks.json";
    private const string TogglAuthUrl = "https://www.toggl.com/api/v2/me";

    private const string AuthenticationType = "Basic";
    private const string ApiToken = "15869be800840d58ed4ec1a9e5e32235";
    private const string Password = "test1395";

    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 = Password + "=" + ApiToken;
        authRequest.ContentLength = value.Length;
        using (StreamWriter writer = new StreamWriter(authRequest.GetRequestStream(), Encoding.ASCII))
        {
            writer.Write(value);
        }

        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();
        using (var reader = new StreamReader(tasksResponse.GetResponseStream(), Encoding.UTF8))
        {
            jsonResult = reader.ReadToEnd();
        }

        var tasks = JsonConvert.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);
        }
    }

    public class Task
    {
        [JsonProperty(PropertyName = "start")]
        [JsonConverter(typeof(IsoDateTimeConverter))]
        public DateTime Start { get; set; }

        [JsonProperty(PropertyName = "stop")]
        [JsonConverter(typeof(IsoDateTimeConverter))]
        public DateTime Stop { get; set; }

        [JsonProperty(PropertyName = "duration")]
        public int Duration { get; set; }

        [JsonProperty(PropertyName = "description")]
        public string Description { get; set; }

        [JsonProperty(PropertyName = "project")]
        public Project Project { get; set; }
    }

    public class Project
    {
        [JsonProperty(PropertyName = "name")]
        public string Name { get; set; }

        [JsonProperty(PropertyName = "client_project_name")]
        public string Client { get; set; }
    }
}

Open in new window

0
Comment
Question by:Sha1395
  • 3
4 Comments
 
LVL 52

Accepted Solution

by:
Carl Tawn earned 500 total points
ID: 39656176
You need to pass your authentication information in the header for the request, not as the body contents. According to the documentation, if you have a token you should be doing something like:
// create request
HttpWebRequest request = (HttpWebRequest)WebRequest.Create("https://www.toggl.com/api/v2/me");

CookieContainer cookies = new CookieContainer();
request.CookieContainer = cookies;

// build authentication token
string authToken = "15869be800840d58ed4ec1a9e5e32235:api_token";

// encode to Base64
byte[] bytes = Encoding.ASCII.GetBytes(authToken);
authToken = Convert.ToBase64String(bytes);

// write the "Authorization" header
request.Headers.Add("Authorization", "Basic " + authToken);
request.Method = "GET";

// get the response
WebResponse response = request.GetResponse();

Open in new window

0
 

Author Comment

by:Sha1395
ID: 39657918
thanks carl_tawn, i tried your code with my test token but im getting the same proxy error.

here is the code

Toggl account details

username :test1395@gmil.com
pwd:Test1395
Token :15869be800840d58ed4ec1a9e5e32235


        // create request
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create("https://www.toggl.com/api/v2/me");

            CookieContainer cookies = new CookieContainer();
            request.CookieContainer = cookies;

            // build authentication token
            //string authToken = "15869be800840d58ed4ec1a9e5e32235:api_token";
            string authToken = "15869be800840d58ed4ec1a9e5e32235";

            // encode to Base64
            byte[] bytes = Encoding.ASCII.GetBytes(authToken);
            authToken = Convert.ToBase64String(bytes);

            // write the "Authorization" header
            request.Headers.Add("Authorization", "Basic " + authToken);
            request.Method = "GET";

            // get the response
            WebResponse response = request.GetResponse();

Open in new window

0
 

Author Comment

by:Sha1395
ID: 39658006
Hi Carl_tawn, i changed a code a bit advised by TheLearnedOne  but this throw a new exception

"The remote server returned an error: (403) Forbidden"

HEre is the code

 HttpWebRequest request = (HttpWebRequest)WebRequest.Create("https://www.toggl.com/api/v2/me");
            //HttpWebRequest request = (HttpWebRequest)WebRequest.Create("https://toggl.com/reports/api/v2/details");
            IWebProxy theProxy = request.Proxy;
            if (theProxy != null)
            {
                theProxy.Credentials = CredentialCache.DefaultCredentials;
            }
            CookieContainer cookies = new CookieContainer();
            request.UseDefaultCredentials = true;
            request.CookieContainer = cookies;

            // build authentication token
            //string authToken = "15869be800840d58ed4ec1a9e5e32235:api_token";
            string authToken = "c620724108921c4530e745798ed19104";

            // encode to Base64
            byte[] bytes = Encoding.ASCII.GetBytes(authToken);
            authToken = Convert.ToBase64String(bytes);

            // write the "Authorization" header
            request.Headers.Add("Authorization", "Basic " + authToken);
           //request.Proxy.Credentials = System.Net.CredentialCache.DefaultCredentials;
            request.Method = "GET";

            // get the response
            WebResponse response = request.GetResponse();

Open in new window


my config file:

<configuration>
  <system.net>
    <defaultProxy useDefaultCredentials="true">
     </defaultProxy>
  </system.net>
  </configuration>

Open in new window

0
 

Author Comment

by:Sha1395
ID: 39658349
Thanks again for your great help, i modified code a bit and its working this is the working version to get initial contact with the API and extract the base data of that particular token.

 // create request
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create("https://www.toggl.com/api/v8/me");
            //HttpWebRequest request = (HttpWebRequest)WebRequest.Create("https://toggl.com/reports/api/v2/details");
            IWebProxy theProxy = request.Proxy;
            if (theProxy != null)
            {
                theProxy.Credentials = CredentialCache.DefaultCredentials;
            }
            CookieContainer cookies = new CookieContainer();
            request.UseDefaultCredentials = true;
            request.CookieContainer = cookies;
            request.ContentType = "application/json";
            request.CookieContainer = cookies;
            // build authentication token
            //string authToken = "15869be800840d58ed4ec1a9e5e32235:api_token";
            string authToken = "c620724108921c4530e745798ed19104:api_token";

            // encode to Base64
            byte[] bytes = Encoding.ASCII.GetBytes(authToken);
            authToken = Convert.ToBase64String(bytes);

            // write the "Authorization" header
            request.Headers.Add("Authorization", "Basic " + authToken);
           //request.Proxy.Credentials = System.Net.CredentialCache.DefaultCredentials;
            request.Method = "GET";

            // get the response
            //WebResponse response = request.GetResponse();
            using (HttpWebResponse response = request.GetResponse() as HttpWebResponse)
            {
                StreamReader reader = new StreamReader(response.GetResponseStream());
                Console.Write(reader.ReadToEnd());
            }

Open in new window

0

Featured Post

Is Your Active Directory as Secure as You Think?

More than 75% of all records are compromised because of the loss or theft of a privileged credential. Experts have been exploring Active Directory infrastructure to identify key threats and establish best practices for keeping data safe. Attend this month’s webinar to learn more.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Suggested Solutions

Introduction This article series is supposed to shed some light on the use of IDisposable and objects that inherit from it. In essence, a more apt title for this article would be: using (IDisposable) {}. I’m just not sure how many people would ge…
We all know that functional code is the leg that any good program stands on when it comes right down to it, however, if your program lacks a good user interface your product may not have the appeal needed to keep your customers happy. This issue can…
This Micro Tutorial will teach you how to censor certain areas of your screen. The example in this video will show a little boy's face being blurred. This will be demonstrated using Adobe Premiere Pro CS6.
Hi friends,  in this video  I'll show you how new windows 10 user can learn the using of windows 10. Thank you.

867 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

22 Experts available now in Live!

Get 1:1 Help Now