How, after a POST request, to receive JSON feedback on C#?

Asked

Viewed 1,377 times

2

I need that after making a requisition POST http, I also receive the json return that is in the echo of php.

This is the test code on php

<?php
    if(isset($_POST['request']))
    {
        echo $jsonret = '{"request":"sim","name":"'.$_POST['request'].'"}';
    }
    else
    {
        echo $jsonret = '{"request":"não","name":"invalid"}';
    }
?>

This was my attempt at C#, as asynchronous methods should always be of the void type, tried using a static variable, but even so, it does not change the string.

Observing: the request works without any problem.

private void button1_Click(object sender, EventArgs e)
{
    RequestJson();
    MessageBox.Show(retornojson);
}
static string retornojson = "nulo";
public async void RequestJson()
{
    string req = "enviado";
    //url do arquivo
    string URL = "http://localhost/testjsonreturn";
    var myHttpClient = new HttpClient();

    //idusuario
    var formContent = new FormUrlEncodedContent(new[]
        {
        new KeyValuePair<string, string>("request", req)
        });
    var request = await myHttpClient.PostAsync(URL, formContent);
    retornojson = request.ToString();
}
  • Because of that statement: devem ser sempre do tipo void and variable static is obliged because?

  • Because the request can only be made asynchronously, var request = await myHttpClient.PostAsync(URL, formContent);

  • Pera a little you made a statement that the method can not be void and that’s not true? even what you went through is not void is with return! I know the solution to this problem, but, is with return? until I know with Task also!

  • You want the solution to this code?

  • Yes, it is possible by task to make the return, if you can give me the solution I thank you.

2 answers

3


Although Virgilio’s reply is correct, I’d like to suggest a few changes.

First, the class HttpClient implements the interface IDisposable, then initialize it using the block using().

The await HttpClient.PostAsync returns a HttpResponseMessage, this owns the Status of the request, so it’s interesting that you validate its value.

Finally, your request returns an object with a known and expected format, so it is interesting that you deserialize this object.

[DataContract]
public class RetornoModel
{
    [DataMember(Name = "request")]
    public string Request { get; set; }

    [DataMember(Name = "name")]
    public string Name { get; set; }

}

public static class Program
{
    public static void Main()
    {
        var model = Program.PostData("http://localhost/testjsonreturn", "enviado").GetAwaiter().GetResult();
    }

    public static async Task<RetornoModel> PostData(string url, string req)
    {
        var parametros = new Dictionary<string, string>();
        values.Add("request", req);
        var content = new FormUrlEncodedContent(parametros);

        using (var httpClient = new HttpClient())
        {
            var response = await httpClient.PostAsync(url, content);
            if (response.StatusCode == HttpStatusCode.OK)
            {
                var json = await response.Content.ReadAsStringAsync();
                return await Task.Factory.StartNew<RetornoModel>(() =>
                {
                    return JsonConvert.DeserializeObject<RetornoModel>(json);
                });
            }
            return null;
        }
    }
}
  • +1 another way.

  • @Virgilionovic is not really another way, just suggest some improvements, after all I believe that the AP is not familiar with the C#.

  • Sincerely @Tobymosque I get in doubt when it restricted only to void, but, yes everything is valid!

2

There are two ways I know:

private async void button1_Click(object sender, EventArgs e)
{
    await RequestJson();
    MessageBox.Show(retornojson);
}

private static string retornojson;
public async Task RequestJson()
{
    string req = "enviado";            
    string URL = "http://localhost/testjsonreturn.php";
    var myHttpClient = new HttpClient();
    var formContent = new FormUrlEncodedContent(new[]
        {
            new KeyValuePair<string, string>("request", req)
        });
    var request = await myHttpClient.PostAsync(URL, formContent);
    retornojson = await request.Content.ReadAsStringAsync();            
    myHttpClient.Dispose();            
}

or

private async void button1_Click(object sender, EventArgs e)
{
    retornojson = await RequestJson();
    MessageBox.Show(retornojson);
}

private static string retornojson;
public async Task<string> RequestJson()
{
    string req = "enviado";            
    string URL = "http://localhost/testjsonreturn.php";
    var myHttpClient = new HttpClient();
    var formContent = new FormUrlEncodedContent(new[]
        {
            new KeyValuePair<string, string>("request", req)
        });
    var request = await myHttpClient.PostAsync(URL, formContent);
    return await request.Content.ReadAsStringAsync();                        
}

Had some problems the address for example, missed .php and when the requisition process was actually carried out, 1 line of code was missing:

retornojson = await request.Content.ReadAsStringAsync();

to read the contents sent by PHP.

  • 1

    It worked perfectly here, thanks for the help!

  • Okay, @Joãopedro ...

Browser other questions tagged

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