[Last Call] Learn about multicloud storage options and how to improve your company's cloud strategy. Register Now

x
?
Solved

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

Posted on 2013-11-17
4
Medium Priority
?
1,587 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
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 3
4 Comments
 
LVL 52

Accepted Solution

by:
Carl Tawn earned 2000 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

VIDEO: THE CONCERTO CLOUD FOR HEALTHCARE

Modern healthcare requires a modern cloud. View this brief video to understand how the Concerto Cloud for Healthcare can help your organization.

Question has a verified solution.

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

Article by: Ivo
C# And Nullable Types Since 2.0 C# has Nullable(T) Generic Structure. The idea behind is to allow value type objects to have null values just like reference types have. This concerns scenarios where not all data sources have values (like a databa…
The article shows the basic steps of integrating an HTML theme template into an ASP.NET MVC project
Sometimes it takes a new vantage point, apart from our everyday security practices, to truly see our Active Directory (AD) vulnerabilities. We get used to implementing the same techniques and checking the same areas for a breach. This pattern can re…
Have you created a query with information for a calendar? ... and then, abra-cadabra, the calendar is done?! I am going to show you how to make that happen. Visualize your data!  ... really see it To use the code to create a calendar from a q…

650 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