Domanda

Harvest è l'applicazione di monitoraggio volta che uso nel mio lavoro. Mentre l'interfaccia utente web è abbastanza semplice, ci sono un paio personalizzato dispone vorrei aggiungere. Ho notato che hanno un API ... Quindi voglio fare un client desktop personalizzato in C # per esso.

Proprio guardando la pagina, la sua non è molto istruttiva. Il C # esempio che è possibile trovare (dopo aver fatto qualche scavo) non aiuta molto. Quindi ... Come in tutto il mondo si utilizza l'API con C #?

link alla pagina API

Qualsiasi aiuto sarebbe molto apprezzato:)

È stato utile?

Soluzione

Harvest sta usando una API REST , quindi ciò che è non è di fare un get / mettere / richiesta POST a un indirizzo web sul server e verrà restituito un risultato (di solito formattati in XML o JSON (sembra essere XML in questo caso)). Una rapida ricerca google restituito questo tutorial su come utilizzare un'API REST, si spera che sarà abbastanza per quello che bisogno. In caso contrario, non esitate a chiedere a noi di problemi specifici che si stanno avendo utilizzando REST e C #

Qui cercherò di aggiungere alcuni commenti al loro campione

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="youremail@somewhere.com";
      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(); }
      }
   }
}

Altri suggerimenti

Ho anche lottato con loro API. La risposta di Scott è molto utile.

In ogni caso c'è una biblioteca molto utile e facile che si chiama EasyHTTP strega che potete trovare in NuGet . qui è lo stesso metodo di Scott, ma molto più breve:):

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;        
    }

Se volete saperne di più su WebAPI chiamate è possibile utilizzare Fidler o un più facile e RestClient che è un plugin per Firefox.

Con RestClient si può parlare di riposare server direttamente, molto utile se si vuole comprendere servizi RESTful.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top