How to use POST on a json for an Http server

Asked

Viewed 1,346 times

1

I was thinking how can I post a json to an http server. The code I am using to do json is as follows:

Person person= new Person();
                    product.FirtsName = "Ola";
                    product.ID = 1;
                    product.age= 10;


                    string json = JsonConvert.SerializeObject(product);

And this is the class Person:

 public class Person
    {
        public int ID { get; set; }
        public string FirtsName { get; set; }
        public int age { get; set; }
    }

1 answer

2


First, I’ll change your class Pedro, to a class called Pessoa and arrange classifications. Decide whether to use properties in English or Portuguese. In this case, I will use the properties in English:

public class Person
{
    public int ID { get; set; }
    public string FirstName { get; set; }
    public int Age{ get; set; }
}

Adjusted this, you need a method asynchronous and an object HttpClient. In this case I chose to return one bool if the operation returns a successful code:

/// <summary>
/// Cria uma pessoa
/// </summary>
/// <param name="person">Objeto 'Person'</param>
/// <returns></returns>
private async Task<bool> CreatePersonAsync(Person person)
{
    var client = new HttpClient();
    client.BaseAddress = new Uri("endreço da sua web api");
    client.DefaultRequestHeaders.Accept.Add(new System.Net.Http.Headers.MediaTypeWithQualityHeaderValue("application/json"));

    // Transforma o objeto em json
    string json = JsonConvert.SerializeObject(person);

    // Envia o json para a API e verifica se obteve sucesso
    HttpResponseMessage response = await client.PostAsync("Controller da sua API para criar a pessoa", new StringContent(json, Encoding.UTF8, "application/json"));
    response.EnsureSuccessStatusCode();

    if (response.IsSuccessStatusCode)
    {
       return true;
    }

    return false;
}

Note that in "Your web api" is the http address of your API.

For example: http://criapessoa.azurewebsites.net/api/

Note that in "Controller of your API to create the person" is only the name of the controller responsible for creating the "person" (Person object).

For example: if within your API the Controller responsible for creating people is called "Person", that name will put.

Using the method

To call this method and wait for the result, you can do the following:

// Método para criar a pessoa e enviar para a Web API
public async void CreatePerson()
{
   // Cria um objeto "Person"
   var person = new Person()
   {
       ID = 1,
       FirstName = "Pedro",
       Age = 10
    }

    // Cria a pessoa e armazena o resultado
    var isOK = await CreatePersonAsync(person);

    // Verifica se obteve sucesso
    if(isOK)
    {
        // Pessoa criada com sucesso
    }
}

Note that the method needs to be async, for within it we shall call the method async we created earlier to create the person on the Web API. In addition, we use the directive await to wait for the method run and return.

  • And how can I add headers to your code ?

  • You already have a header added in the following line: client.DefaultRequestHeaders.Accept.Add(). You can add more in the same way.

  • Thank you so much for your help.

  • @I changed a few things in the answer. I disabled the code that was creating the Person object from within the http method and put an example of using the method and in the most "correct" way to do what you want.

  • What is the reference you need to use to use Httpclient?

  • using is this: using System.Net.Http;

  • In my condition I can’t use this using

  • What kind of project are you using? WPF, Asp.Net, Winforms?

  • console . net but do not know why not appear

  • I don’t have it yet

  • Chat.

Show 7 more comments

Browser other questions tagged

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