Solved

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

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

Gigs: Get Your Project Delivered by an Expert

Select from freelancers specializing in everything from database administration to programming, who have proven themselves as experts in their field. Hire the best, collaborate easily, pay securely and get projects done right.

Question has a verified solution.

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

Suggested Solutions

Entity Framework is a powerful tool to help you interact with the DataBase but still doesn't help much when we have a Stored Procedure that returns more than one resultset. The solution takes some of out-of-the-box thinking; read on!
Exception Handling is in the core of any application that is able to dignify its name. In this article, I'll guide you through the process of writing a DRY (Don't Repeat Yourself) Exception Handling mechanism, using Aspect Oriented Programming.
This tutorial gives a high-level tour of the interface of Marketo (a marketing automation tool to help businesses track and engage prospective customers and drive them to purchase). You will see the main areas including Marketing Activities, Design …
Established in 1997, Technology Architects has become one of the most reputable technology solutions companies in the country. TA have been providing businesses with cost effective state-of-the-art solutions and unparalleled service that is designed…

808 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