简体   繁体   中英

How to post data using HttpClient? (an answer than actually works)

There is another question about this, but it doesn't have a functioning solution at the end, and the only good answer, for some reason, doesn't work, not for the guy who ask it, not for me either.

This such question is here: How to post data using HttpClient?

Given the corresponding aclarations, this is the code I have so far:

The methods to call the method who connects with the web server:

private void Button_Click(object sender, System.EventArgs e)
{
    //. . . DO SOMETHING . . .
    PopulateListView();

    //. . . DO SOMETHING ELSE . . .
}

private void PopulateListView()
{
   //. . . DO SOMETHING . . .

   list = await "http://web.server.url".GetRequest<List<User>>();

   //. . . DO SOMETHING ELSE . . .
}

The method than connects with the web server:

public async static Task<T> SendGetRequest<T>(this string url)
{
    try
    {
        var uri = new Uri(url);
        HttpClient client = new HttpClient();
        //Preparing to have something to read
        var formContent = new FormUrlEncodedContent(new[]
                {
                    new KeyValuePair<string, string>("OperationType", "eaf7d94356e7fd39935547f6f15e1c4c234245e4")
                });

        HttpResponseMessage response = await client.PostAsync(uri, formContent);

        #region - - Envio anterior (NO FUNCIONO, SIN USO) - -
        //var stringContent = new StringContent("markString");
        //var sending = await client.PostAsync(url, stringContent);

        //MainActivity.ConsoleData = await client.PostAsync(url, stringContent);
        #endregion

        //Reading data
        //var response = await client.GetAsync(url);
        var json = await response.Content.ReadAsStringAsync();
        MainActivity.ConsoleData = json.ToString();
        return Newtonsoft.Json.JsonConvert.DeserializeObject<T>(json);
    }
    catch(Exception ex)
    {
        Console.WriteLine("Error: "+ex.ToString());
        return default(T);
    } 
}

You maybe guessed it, but I'm trying to make a method that send some data (through POST) called "markString" to a web-server than receive it and, depending of the "markString" it returns certain json Objects.

This web server is already working properly (I tested it out with some plug-in, it work like it should)

This method is supposed to send the "markString" and receive the data back so then i can use it in the app.

I'm making a Xamarin Android application.

Also have in mind than I don't have any connection problem at all, in fact the app is sending data in an excellent matter when I try to do it using web client, but I want it to send it using HttpClient .

The problem

The code is not returning anything. Any request for information, clarification, question, constructive comments or anything than can lead to an answer would be greatly appreciated too.

Thanks in advance.

void Main()
{
    var test = SendGetRequest("http://www.google.com");
    test.Dump();
}

public async static Task<string> SendGetRequest(string url)
{
    try
    {
        var uri = new Uri(url);
        HttpClient client = new HttpClient();
        //Preparing to have something to read
        var formContent = new FormUrlEncodedContent(new[]
                {
                    new KeyValuePair<string, string>("OperationType", "eaf7d94356e7fd39935547f6f15e1c4c234245e4")
                });

        HttpResponseMessage response = await client.PostAsync(uri, formContent);

        #region - - Envio anterior (NO FUNCIONO, SIN USO) - -
        //var stringContent = new StringContent("markString");
        //var sending = await client.PostAsync(url, stringContent);

        //MainActivity.ConsoleData = await client.PostAsync(url, stringContent);
        #endregion

        //Reading data
        //var response = await client.GetAsync(url);
        var json = await response.Content.ReadAsStringAsync();

        return json;
    }
    catch (System.Exception ex)
    {
        Console.WriteLine("Error: " + ex.ToString());
        return string.Empty;
    }

}

Most deadlock scenarios with asynchronous code are due to blocking further up the call stack .

By default await captures a "context" (in this case, a UI context), and resumes executing in that context. So, if you call an async method and the block on the task (eg, GetAwaiter().GetResult() , Wait() , or Result ), then the UI thread is blocked, which prevents the async method from resuming and completing.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM