Problems with Jsonconvert.Serializeobject and Stringcontent

Asked

Viewed 316 times

0

I am developing an application Xamarin Forms that will persist data via web service (PHP - Mysql), but I have problems sending data via POST

I have the event below and the same from the message of Cadastrado com sucesso!, but when I check the database the information is empty.

Registration button event code

private async void cadastroButton_Clicked(object sender, EventArgs e)
{
    if (string.IsNullOrEmpty(nomeEntry.Text))
    {
        await DisplayAlert("Erro", "Campo nome obrigatório!", "Ok");
        nomeEntry.Focus();
        return;
    }
    if (string.IsNullOrEmpty(celularEntry.Text))
    {
        await DisplayAlert("Erro", "Campo celular obrigatório!", "Ok");
        celularEntry.Focus();
        return;
    }

    waitActivityIndicator.IsVisible = true;
    waitActivityIndicator.IsRunning = true;

    var ramal = new DeviceRamal
    {   
        ram_nome = nomeEntry.Text,            
        ram_celular = celularEntry.Text,
    };

    var jsonRequest = JsonConvert.SerializeObject(ramal);
    var content = new StringContent(jsonRequest, Encoding.UTF8, "text/json");

    string result;

    try
    {
        HttpClient client = new HttpClient();
        client.BaseAddress = new Uri("http://meusite.com.br");
        string url = string.Format("/contato/insert.php");
        var response = await client.PostAsync(url, content);
        result = response.Content.ReadAsStringAsync().Result;
    }
    catch (Exception)
    {
        await DisplayAlert("Erro", "Sem conexão no momento!", "Ok");
        return;
    }


    waitActivityIndicator.IsVisible = false;
    waitActivityIndicator.IsRunning = false;
    await DisplayAlert("Sucesso", "Cadastrado com sucesso!", "Ok");
}

If you do so Do not send the parameters

string url = string.Format("/contato/insert.php");
var response = await client.PostAsync(url, content);

If you do so Send the parameters

string url = string.Format("/contato/index.php?email={0}&password={1}", userEntry.Text, passwordEntry.Text);
var response = await client.GetAsync(url);

I took from the try catch and Sponse returns the following:

{Statuscode: 200, Reasonphrase: 'OK', Version: 1.1, Content: >System.Net.Http.Streamcontent, Headers: { Date: Thu, 04 Aug 2016 00:59:45 GMT Server: Apache X-Powered-By: PHP/5.4.42 Connection: close Transfer-Encoding: chunked Content-Type: text/html }}

Observing with Postasync does not work, with Getasync works, client.PostAsync("http://site.com.br/appramal/f/insertRamal.php?ram_celular={0}"...

And I touched the code and it still doesn’t work.

    private async void cadastroRamalButton_Clicked(object sender, EventArgs e)
    {
        if (unidadePicker.SelectedIndex == -1)
        {
            await DisplayAlert("Erro", "Selecione a unidade", "Ok");
            unidadePicker.Focus();
            return;
        }
        if (string.IsNullOrEmpty(nomeEntry.Text))
        {
            await DisplayAlert("Erro", "Campo nome obrigatório!", "Ok");
            nomeEntry.Focus();
            return;
        }
        if (string.IsNullOrEmpty(ramalEntry.Text))
        {
            await DisplayAlert("Erro", "Campo nome obrigatório!", "Ok");
            ramalEntry.Focus();
            return;
        }
        if (string.IsNullOrEmpty(ramalVirtualEntry.Text))
        {
            await DisplayAlert("Erro", "Campo ramal virtual obrigatório!", "Ok");
            ramalVirtualEntry.Focus();
            return;
        }
        if (string.IsNullOrEmpty(celularEntry.Text))
        {
            await DisplayAlert("Erro", "Campo celular obrigatório!", "Ok");
            celularEntry.Focus();
            return;
        }
        if (setorPicker.SelectedIndex == -1)
        {
            await DisplayAlert("Erro", "Selecione o setor", "Ok");
            setorPicker.Focus();
            return;
        }
        if (string.IsNullOrEmpty(emailEntry.Text))
        {
            await DisplayAlert("Erro", "Campo email obrigatório!", "Ok");
            emailEntry.Focus();
            return;
        }
        if (string.IsNullOrEmpty(skypeEntry.Text))
        {
            await DisplayAlert("Erro", "Campo skype obrigatório!", "Ok");
            skypeEntry.Focus();
            return;
        }

        waitActivityIndicator.IsVisible = true;
        waitActivityIndicator.IsRunning = true;

        DeviceRamal ramal = new DeviceRamal();
        ramal.ram_celular = celularEntry.Text;
        ramal.ram_email = emailEntry.Text;
        ramal.ram_nome = nomeEntry.Text;
        ramal.ram_ramal = ramalEntry.Text;
        ramal.ram_ramalvirtual = ramalVirtualEntry.Text;
        ramal.ram_skype = skypeEntry.Text;
        ramal.set_codigo = this.setorList[setorPicker.SelectedIndex].set_codigo;
        ramal.uni_codigo = this.unidadeList[unidadePicker.SelectedIndex].uni_codigo;

        string result;

        HttpClient client = new HttpClient();

        var response = client.PostAsync("http://site.com.br/appramal/f/insertRamal.php",
            new StringContent(JsonConvert.SerializeObject(ramal).ToString(),
            Encoding.UTF8, "application/json")).Result;

        if (response.IsSuccessStatusCode)
        {
            dynamic content = JsonConvert.DeserializeObject(response.Content.ReadAsStringAsync().Result);

            await DisplayAlert("Sucesso", "Ramal cadastrado com sucesso!", "Ok");
            waitActivityIndicator.IsVisible = false;
            waitActivityIndicator.IsRunning = false;
        }

    }
  • You are doing a POST and trying to pass the parameters through the URL?

  • 2

    Something else try..catch does not take server error return failures as Unauthorized, etc. Check the contents of the variable result and you’ll see that the actual server return. The way you’re doing will always be Sucesso

No answers

Browser other questions tagged

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