How to do JSON data request

0

I need to collect some data from a program that has API:

PipeDrive API Reference

If I understand correctly, for each task, a URL will be generated to make Requeste data, for example:

https://api.pipedrive.com/v1/deals?stage_id=45&status=all_not_deleted&start=0&api_token=8***76c******9740**78223a2c

But how do I return this data in my application? The method is GET .

    
asked by anonymous 11.08.2017 / 18:04

1 answer

0

Hello, there are some approaches, I'll cite the one I think is more appropriate, which is using HttpClient .

If you can not find it in your project, install the following package: System.Net.Http

public class MinhaController : Controller
{
    // o HttpClient deve ter uma instancia estatica, para evitar ficar abrindo muitas portas.
    private static HttpClient httpClient;

    static MinhaController()
    {
        httpClient = new HttpClient();
        httpClient.BaseAddress = new Uri("https://api.pipedrive.com/v1/deals");
        httpClient.DefaultRequestHeaders.Accept.Clear();
        httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
        //Se precisar adicionar alguma autenticação, faça o aqui.
    }

    public async Task<ActionResult> Index()
    {
        var stageId = GetStageFromSomewhere();
        var token = GetTokenFromSomewhere();
        var queryString = $"?stage_id={stageId}&status=all_not_deleted&start=0&api_token={token}";
        var response = await httpClient.GetAsync(queryString);
        if (response.IsSuccessStatusCode)
        {
            var json = await response.Content.ReadAsStringAsync();
            var model = Newtonsoft.Json.JsonConvert.DeserializeObject<MeuModelo>(json)
            return Json(model);
        }
        return new HttpStatusCodeResult(HttpStatusCode.InternalServerError, "Erro ao acessar a API.");
    }
}

EDIT

The AP asked to list some other approaches, so come on.

  • HttpWebRequest - Quite complex, but allows you to control every aspect of the request.
  • WebClient - Abstraction of HttpWebRequest , quite simple, without many controls.
  • HttpClient - Available in .NET 4.5 , allows operation async/await and combines best of HttpWebRequest and WebClient .
  • RestSharp - Similar to HttpClient , but with async/await and better compatibility.

Then, in your case, HttpClient is the most indicated.

    
11.08.2017 / 18:24