Solved

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

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

Technology Partners: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

Question has a verified solution.

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

Suggested Solutions

This article describes a simple method to resize a control at runtime.  It includes ready-to-use source code and a complete sample demonstration application.  We'll also talk about C# Extension Methods. Introduction In one of my applications…
This article introduced a TextBox that supports transparent background.   Introduction TextBox is the most widely used control component in GUI design. Most GUI controls do not support transparent background and more or less do not have the…
The Email Laundry PDF encryption service allows companies to send confidential encrypted  emails to anybody. The PDF document can also contain attachments that are embedded in the encrypted PDF. The password is randomly generated by The Email Laundr…

749 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