Harvest(考勤卡应用程序)API

发布于 2024-11-03 14:35:21 字数 387 浏览 6 评论 0原文

Harvest 是我在工作中使用的时间跟踪应用程序。虽然 Web UI 非常简单,但我想添加一些自定义功能。我注意到他们有一个 API...所以我想用 C# 为其制作一个自定义桌面客户端。

只看页面,信息量不大。您可以找到的 C# 示例(经过一番挖掘后)也没有多大帮助。那么...我到底如何在 C# 中使用 API 呢?

API 页面链接

如有任何帮助,我们将不胜感激:)

Harvest is the time tracking application that I use at my job. While the web UI is quite simple, there are a few custom features I would like to add. I noticed they have an API... So I want to make a custom desktop client in C# for it.

Just looking at the page, its not very informative. The C# sample that you can find (after doing some digging) doesn't help much either. So... How in the world do I use the API with C#?

Link to API page

Any help would be greatly appreciated :)

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

东风软 2024-11-10 14:35:21

Harvest 使用 REST API,所以它的作用是执行 get/put/post向服务器上的网址发出请求,它将返回结果(通常采用 XML 或 JSON 格式(在本例中似乎是 XML))。快速 Google 搜索返回了关于如何使用 REST API 的本教程,希望这足以满足您的需求需要。如果没有,请随时向我们询问您在使用 REST 和 C# 时遇到的具体问题

,在这里我将尝试向他们的示例添加更多评论:

using System;
using System.Net;
using System.IO;
using System.Text;
using System.Security.Cryptography.X509Certificates;
using System.Net.Security;

class HarvestSample
{
    //This is used to validate the certificate the server gives you,
    //it allays assumes the cert is valid.
    public static bool Validator (object sender, X509Certificate certificate,
        X509Chain chain, SslPolicyErrors sslPolicyErrors)
    {
        return true;
    }

    static void Main(string[] args)
    {
        //setting up the initial request.
        HttpWebRequest request;
        HttpWebResponse response = null;
        StreamReader reader;
        StringBuilder sbSource;
        //1. Set some variables specific to your account.
        //This is the URL that you will be doing your REST call against.
        //Think of it as a function in normal library.
        string uri = "https://yoursubdomain.harvestapp.com/projects";
        string username="[email protected]";
        string password="yourharvestpassword";
        string usernamePassword = username + ":" + password;

        //This checks the SSL cert that the server will give us,
        //the function is above this one.
        ServicePointManager.ServerCertificateValidationCallback = Validator;

        try
        {
            //more setup of the connection
            request = WebRequest.Create(uri) as HttpWebRequest;
            request.MaximumAutomaticRedirections = 1;
            request.AllowAutoRedirect = true;

            //2. It's important that both the Accept and ContentType headers
            //are set in order for this to be interpreted as an API request.
            request.Accept = "application/xml";
            request.ContentType = "application/xml";
            request.UserAgent = "harvest_api_sample.cs";
            //3. Add the Basic Authentication header with username/password string.
            request.Headers.Add("Authorization", "Basic " + Convert.
                ToBase64String(new ASCIIEncoding().GetBytes(usernamePassword)));
            //actually perform the GET request
            using (response = request.GetResponse() as HttpWebResponse)
            {
                //Parse out the XML it returned.
                if (request.HaveResponse == true && response != null)
                {
                    reader = new StreamReader(response.GetResponseStream(),
                        Encoding.UTF8);
                    sbSource = new StringBuilder(reader.ReadToEnd());
                    //4. Print out the XML of all projects for this account.
                    Console.WriteLine(sbSource.ToString());
                }
            }
        }
        catch (WebException wex)
        {
            if (wex.Response != null)
            {
                using (HttpWebResponse errorResponse = (HttpWebResponse)wex.Response)
                {
                    Console.WriteLine(
                    "The server returned '{0}' with the status code {1} ({2:d}).",
                    errorResponse.StatusDescription, errorResponse.StatusCode,
                    errorResponse.StatusCode);
                }
            }
            else
            {
                Console.WriteLine( wex);
            }
        }
        finally
        {
            if (response != null) { response.Close(); }
        }
    }
}

Harvest is using a REST API, so what is does is you do a get/put/post request to a web address on the server and it will return a result (usually formatted in XML or JSON (appears to be XML in this case)). A quick Google search returned this tutorial on how to use a REST API, hopefully that will be enough for what you need. If not, feel free to ask us about specific problems you are having using REST and C#

Here I will try to add some more comments to their sample:

using System;
using System.Net;
using System.IO;
using System.Text;
using System.Security.Cryptography.X509Certificates;
using System.Net.Security;

class HarvestSample
{
    //This is used to validate the certificate the server gives you,
    //it allays assumes the cert is valid.
    public static bool Validator (object sender, X509Certificate certificate,
        X509Chain chain, SslPolicyErrors sslPolicyErrors)
    {
        return true;
    }

    static void Main(string[] args)
    {
        //setting up the initial request.
        HttpWebRequest request;
        HttpWebResponse response = null;
        StreamReader reader;
        StringBuilder sbSource;
        //1. Set some variables specific to your account.
        //This is the URL that you will be doing your REST call against.
        //Think of it as a function in normal library.
        string uri = "https://yoursubdomain.harvestapp.com/projects";
        string username="[email protected]";
        string password="yourharvestpassword";
        string usernamePassword = username + ":" + password;

        //This checks the SSL cert that the server will give us,
        //the function is above this one.
        ServicePointManager.ServerCertificateValidationCallback = Validator;

        try
        {
            //more setup of the connection
            request = WebRequest.Create(uri) as HttpWebRequest;
            request.MaximumAutomaticRedirections = 1;
            request.AllowAutoRedirect = true;

            //2. It's important that both the Accept and ContentType headers
            //are set in order for this to be interpreted as an API request.
            request.Accept = "application/xml";
            request.ContentType = "application/xml";
            request.UserAgent = "harvest_api_sample.cs";
            //3. Add the Basic Authentication header with username/password string.
            request.Headers.Add("Authorization", "Basic " + Convert.
                ToBase64String(new ASCIIEncoding().GetBytes(usernamePassword)));
            //actually perform the GET request
            using (response = request.GetResponse() as HttpWebResponse)
            {
                //Parse out the XML it returned.
                if (request.HaveResponse == true && response != null)
                {
                    reader = new StreamReader(response.GetResponseStream(),
                        Encoding.UTF8);
                    sbSource = new StringBuilder(reader.ReadToEnd());
                    //4. Print out the XML of all projects for this account.
                    Console.WriteLine(sbSource.ToString());
                }
            }
        }
        catch (WebException wex)
        {
            if (wex.Response != null)
            {
                using (HttpWebResponse errorResponse = (HttpWebResponse)wex.Response)
                {
                    Console.WriteLine(
                    "The server returned '{0}' with the status code {1} ({2:d}).",
                    errorResponse.StatusDescription, errorResponse.StatusCode,
                    errorResponse.StatusCode);
                }
            }
            else
            {
                Console.WriteLine( wex);
            }
        }
        finally
        {
            if (response != null) { response.Close(); }
        }
    }
}
不爱素颜 2024-11-10 14:35:21

我也在他们的 API 上遇到了困难。斯科特的回答非常有用。

无论如何,有一个非常有用且简单的库,称为 EasyHttp,您可以在 NuGet 中找到。
这里的方法与 Scott 的方法相同,但更短:):

public static string getProjects()
    {

        string uri = "https://<companyname>.harvestapp.com/projects";
        HttpClient http = new HttpClient();
        //Http Header
        http.Request.Accept = HttpContentTypes.ApplicationJson;
        http.Request.ContentType = HttpContentTypes.ApplicationJson;
        http.Request.SetBasicAuthentication(username, password);
        http.Request.ForceBasicAuth = true;
        HttpResponse response = http.Get(uri);

        return response.RawText;        
    }

如果您想了解有关 WebApi 调用的更多信息,您可以使用 Fidler 或更简单的 RestClient 这是一个 Firefox 插件。

使用 RestClient,您可以直接与 REST 服务器通信,如果您想了解 RESTful 服务,这非常有帮助。

I've also struggled with their API. Scott's answer is very useful.

Anyway there is a very useful and easy library which is called EasyHttp witch you can find in NuGet.
here is the same method as Scott's but much shorter :):

public static string getProjects()
    {

        string uri = "https://<companyname>.harvestapp.com/projects";
        HttpClient http = new HttpClient();
        //Http Header
        http.Request.Accept = HttpContentTypes.ApplicationJson;
        http.Request.ContentType = HttpContentTypes.ApplicationJson;
        http.Request.SetBasicAuthentication(username, password);
        http.Request.ForceBasicAuth = true;
        HttpResponse response = http.Get(uri);

        return response.RawText;        
    }

If you want to learn more about WebApi calls you can use Fidler or a more easier and RestClient which is a Firefox plugin.

With RestClient you can talk to rest servers directly, very helpful if you want to understand RESTful services.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文