Consume REST windows Forms

Asked

Viewed 2,646 times

0

I’m trying to consume a REST JSON, I’m developing a module for a legacy system in Windows Forms, it’s not working, nothing returns.

Follows 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 mandatory.


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

Gets on that line he locks 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 with 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 passing as a string and it worked, I would like to know how to generate a Json object.

1 answer

1


Follow 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 link https://selador.homologacao.portalseloam.com.br does not have a verified certificate, so it is not considered safe, so an exception will occur when executing this code.

However it is possible to make a technical arrangement so that the certificate is not validated, however 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.eyJqdGkiOiI1ZDY5MmMwNC02MDc2LTRlNDEtYjRlNi01NjUwMTRmNWYzODEiLCJleHAiOjE0NzA2NzMwNTUsIm5iZiI6MCwiaWF0IjoxNDcwNjcyNDU1LCJpc3MiOiJodHRwOi8va2V5Y2xvYWstcG9ydGFsOjgwODAvYXV0aC9yZWFsbXMvc2VsYWRvci1hcGkiLCJhdWQiOiJzZWxhZG9yIiwic3ViIjoiZDgyMjM0NDAtODdhOC00MDNkLTkyNTYtZmQ5NTFiODY1MDJlIiwiYXpwIjoic2VsYWRvciIsInNlc3Npb25fc3RhdGUiOiJiZjMzNDhlYy0zNGQ4LTQzNGItODE0OC1mZDhjM2NkYTQ3ZTAiLCJjbGllbnRfc2Vzc2lvbiI6ImQxODExZjQzLWE1ZmQtNGE1MC1hMzdjLWY3YjY1OThiYzE1NyIsImFsbG93ZWQtb3JpZ2lucyI6W10sInJlc291cmNlX2FjY2VzcyI6eyJzZWxhZG9yIjp7InJvbGVzIjpbImNhcnRvcmlvIl19LCJhY2NvdW50Ijp7InJvbGVzIjpbIm1hbmFnZS1hY2NvdW50Iiwidm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O-SelhTDAAv6mguO0LMfy-HAuhKMDVcRpuoHsF0jwklEOUC2KeC6T2fdI7su8Sn5v5aRuj1bSxwOD9VluY21_zYGQ34E0CJKwudzLDkLM6CF-xoC5Y69TORdVPzztXyUgafQ_pExVnM--0TLB8jUL2YXQaOZk7oAB0tAiDo7rUqKyERpI4sjtV-GjutcC3vJWH-hHiIfJFxjik5HutuH245uQ5lp-N-dfUkVvp1A-bDTnB4LKgmCMzXze2B63H4se3xZZg",
   "not-before-policy":1447334813,
   "session-state":"bf3348ec-34d8-434b-8148-fd8c3cda47e0"
}

then before working on this object, I advise you to deserialize it. for such 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 the 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 containing a json.

Then you can instantiate one StringContent passing the string with json and informing 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();
}
  • Toby, I tried to run the code you gave me, but you’re making an error on this line here: var request = await client.Postasync("/auth", content); {"The underlying connection was closed: Could not establish trust for secure SSL/TLS channel."}

  • @Thiagomartins after performing some corrections in the names of the variables, I tried to perform the Request, but the same was recursed because the certificate used on the site is invalid, so I had to make a gambiara to be able to consume this service.

  • @Thiagomartins made an edition with several details.

  • thank you very much, exactly what I needed. Very well explained, congratulations.

  • how do I reference the library of this [Datacontract]?

  • @Thiagomartins, System.Runtime.Serialization

  • even referencing the System.Runtime.Serialization library I can’t find the [Datacontract], it’s like it’s not referenced.

  • @Thiagomartins. you need to include the reference in the project and the using in the file.

  • worked out, I was faltering, I was forgetting to reference the dll in the project. Thanks again.

  • how do I fill a JSON body using Httpclient?

  • @Tobymosby, thank you very much brother, it worked.

  • @Tobymosby, I added one more question to my question, if you can help me with that...

  • @Thiagomartins, if you have new questions, please create new questions, for example, when asking how to submit a JSON, you changed the scope of the question, this is not interesting to Stackoverflow, in this case the ideal would be to open a new question with the new question.

Show 8 more comments

Browser other questions tagged

You are not signed in. Login or sign up in order to post.