Consuming REST windows forms

0

I'm trying to consume a JSON REST, I'm developing a module for a legacy Windows Forms system, it's not working, it does not return anything.

Follow the code:

var client = new RestClient("https://selador.homologacao.portalseloam.com.br/auth");
var request = new RestRequest(Method.POST);


request.JsonSerializer.DateFormat = "POST";
request.AddHeader("content-type", "application/x-www-form-urlencoded");
request.AddParameter("username", "xxxxxx", ParameterType.QueryString);
request.AddParameter("password", "xxx@xxxx", ParameterType.QueryString);
request.AddParameter("client_id", "xxxxxxx", ParameterType.QueryString);
request.AddParameter("grant_type", "password", ParameterType.QueryString);

var response = client.Execute(request);

The parameters username , password , client_id and grant_type are required.

Creating a separate method and trying to get the result by calling "Call (). Result".

It arrives at this line it crashes the system

var request = await cliente.PostAsync("/auth", content);



static void Main(string[] args)
{
    ServicePointManager.ServerCertificateValidationCallback += (sender, cert, chain, sslPolicyErrors) => true;
    var response = Program.Call().Result;
}

static async Task<string> Call()
{
    var parametros = new Dictionary<string, string>();
    parametros.Add("username", "004143");
    parametros.Add("password", "fpf@1212");
    parametros.Add("client_id", "selador");
    parametros.Add("grant_type", "password");

    using (var cliente = new HttpClient())
    {
        cliente.BaseAddress = new Uri("https://selador.homologacao.portalseloam.com.br");
        var content = new FormUrlEncodedContent(parametros);
        var request = await cliente.PostAsync("/auth", content);
        return await request.Content.ReadAsStringAsync();
    }
}

Another question

How do I generate a Json object in the following format:

{
 "ato": {
  "codigo": "030011",
  "codigoTabelaCusta": "0320161001"
 },
 "natureza": {
  "tipo": 1
 },
  "partes": ["DEVEDOR", "APRESENTANTE, CREDOR"],
  "selo": {
  "convenio": false,
  "escrevente": "USUÁRIO DE SUPORTE PADRÃO",
  "protocolo": "12345",
  "valorTitulo": 511.00
 }
}

I already generated a string and it worked, I would like to know how to generate a Json object.

    
asked by anonymous 08.08.2016 / 16:16

1 answer

1

Following is an example using the System.Net .Http.HttpClient :

static void Main(string[] args)
{
    ServicePointManager.ServerCertificateValidationCallback += (sender, cert, chain, sslPolicyErrors) => true;
    var response = Program.Call().Result;
}

static async Task<string> Call()
{
    var parametros = new Dictionary<string, string>();
    parametros.Add("username", "004143");
    parametros.Add("password", "fpf@1212");
    parametros.Add("client_id", "selador");
    parametros.Add("grant_type", "password");

    using (var cliente = new HttpClient())
    {
        cliente.BaseAddress = new Uri("https://selador.homologacao.portalseloam.com.br");
        var content = new FormUrlEncodedContent(parametros);
        var request = await cliente.PostAsync("/auth", content);
        return await request.Content.ReadAsStringAsync();
    }
}

Remembering that this is the recommended way to make Web requests from .Net 4.5

Note that the https://selador.homologacao.portalseloam.com.br link does not have a verified certificate, so it is not considered secure, so an exception will occur when executing this code.

However, it is possible to make a technical arrangement so that certificate is not validated, but I do not advise you to ignore this verification in the production environment;

ServicePointManager.ServerCertificateValidationCallback += (sender, cert, chain, sslPolicyErrors) => true;

The above code is returning the following string.:

{ 
   "access_token":"eyJhbGciOiJSUzI1NiJ9.eyJqdGkiOiI1ZDY5MmMwNC02MDc2LTRlNDEtYjRlNi01NjUwMTRmNWYzODEiLCJleHAiOjE0NzA2NzMwNTUsIm5iZiI6MCwiaWF0IjoxNDcwNjcyNDU1LCJpc3MiOiJodHRwOi8va2V5Y2xvYWstcG9ydGFsOjgwODAvYXV0aC9yZWFsbXMvc2VsYWRvci1hcGkiLCJhdWQiOiJzZWxhZG9yIiwic3ViIjoiZDgyMjM0NDAtODdhOC00MDNkLTkyNTYtZmQ5NTFiODY1MDJlIiwiYXpwIjoic2VsYWRvciIsInNlc3Npb25fc3RhdGUiOiJiZjMzNDhlYy0zNGQ4LTQzNGItODE0OC1mZDhjM2NkYTQ3ZTAiLCJjbGllbnRfc2Vzc2lvbiI6ImQxODExZjQzLWE1ZmQtNGE1MC1hMzdjLWY3YjY1OThiYzE1NyIsImFsbG93ZWQtb3JpZ2lucyI6W10sInJlc291cmNlX2FjY2VzcyI6eyJzZWxhZG9yIjp7InJvbGVzIjpbImNhcnRvcmlvIl19LCJhY2NvdW50Ijp7InJvbGVzIjpbIm1hbmFnZS1hY2NvdW50Ii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AwOO-SelhTDAAv6mguO0LMfy-HAuhKMDVcRpuoHsF0jwklEOUC2KeC6T2fdI7su8Sn5v5aRuj1bSxwOD9VluY21_zYGQ34E0CJKwudzLDkLM6CF-xoC5Y69TORdVPzztXyUgafQ_pExVnM--0TLB8jUL2YXQaOZk7oAB0tAiDo7rUqKyERpI4sjtV-GjutcC3vJWH-hHiIfJFxjik5HutuH245uQ5lp-N-dfUkVvp1A-bDTnB4LKgmCMzXze2B63H4se3xZZg",
   "not-before-policy":1447334813,
   "session-state":"bf3348ec-34d8-434b-8148-fd8c3cda47e0"
}

So before working on this object, I advise you to deserialize it. to do so define a class with the following structure.

[DataContract]
public class DadosAcesso
{       
    [DataMember(Name = "access_token")]
    public string AccessToken { get; set; }
    [DataMember(Name = "refresh_expires_in")]
    public int RefreshExpiresIn { get; set; }
    [DataMember(Name = "refresh_token")]
    public int RefreshToken { get; set; }
    [DataMember(Name = "token_type")]
    public string TokenType { get; set; }
    [DataMember(Name = "id_token")]
    public string IdToken { get; set; }
    [DataMember(Name = "not-before-policy")]
    public int NotBeforePolicy { get; set; }
    [DataMember(Name = "session-state")]
    public Guid SessionState { get; set; }
}

Then use Json.NET :

var response = Program.Call().Result;
var dadosAcesso = JsonConvert.DeserializeObject<DadosAcesso>(response);

EDIT - Sending a JSON

The first thing to do is serializar your object, done this you will have a string that contains a json .

Then you can instantiate a StringContent by passing the string with json and giving mime-type application/json .

var objeto = new MyObjeto { MyProp1 = "For", MyProp2 = "Bar" };
var json = await Task.Run(() => {
    JsonConvert.SerializeObject(objeto);
});

using (var cliente = new HttpClient())
{
    cliente.BaseAddress = new Uri("https://selador.homologacao.portalseloam.com.br");
    var content = new StringContent(json , Encoding.UTF8, "application/json");
    var request = await cliente.PostAsync("/auth", content);
    return await request.Content.ReadAsStringAsync();
}
    
08.08.2016 / 17:22