Solved

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

Posted on 2013-11-17
4
1,337 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

What Is Threat Intelligence?

Threat intelligence is often discussed, but rarely understood. Starting with a precise definition, along with clear business goals, is essential.

Join & Write a Comment

Extention Methods in C# 3.0 by Ivo Stoykov C# 3.0 offers extension methods. They allow extending existing classes without changing the class's source code or relying on inheritance. These are static methods invoked as instance method. This…
Article by: Ivo
Anonymous Types in C# by Ivo Stoykov Anonymous Types are useful when  we do not need to follow usual work-flow -- creating object of some type, assign some read-only values and then doing something with them. Instead we can encapsulate this read…
Sending a Secure fax is easy with eFax Corporate (http://www.enterprise.efax.com). First, Just open a new email message.  In the To field, type your recipient's fax number @efaxsend.com. You can even send a secure international fax — just include t…
Excel styles will make formatting consistent and let you apply and change formatting faster. In this tutorial, you'll learn how to use Excel's built-in styles, how to modify styles, and how to create your own. You'll also learn how to use your custo…

708 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

17 Experts available now in Live!

Get 1:1 Help Now