How, after a POST request, receive the JSON return in C #?

2

I need to have a POST link request, so I also get the json in php .

This is the test code in 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 # , like asynchronous methods should always be of the void type, I tried using a static variable , but it still does not change the string .

Note: The request works without a 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();
}
    
asked by anonymous 07.11.2016 / 22:31

2 answers

3

Although Virgilio's answer is correct, I would like to suggest a few changes.

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

The await HttpClient.PostAsync returns a HttpResponseMessage , it has 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;
        }
    }
}
    
08.11.2016 / 01:03
2

There are 2 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();                        
}

There were some problems with the address, for example, .php was missing and when the request process was actually completed, 1 line of code was missing:

retornojson = await request.Content.ReadAsStringAsync();

to read the content sent by PHP .

    
08.11.2016 / 00:40