简体   繁体   English

如何使用HttpClient发布数据? (比实际可行的答案)

[英]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? 这个问题在这里: 如何使用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: 调用与Web服务器连接的方法的方法:

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: 然后与Web服务器连接的方法:

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. 您可能会猜到,但是我正在尝试一种方法(通过POST)将一些称为“ markString”的数据发送到Web服务器,而不是接收它,并且根据“ markString”,它返回某些json对象。

This web server is already working properly (I tested it out with some plug-in, it work like it should) 该Web服务器已经可以正常工作(我已经通过一些插件对其进行了测试,它应该可以正常工作)

This method is supposed to send the "markString" and receive the data back so then i can use it in the app. 这种方法应该发送“ markString”并接收回来的数据,这样我就可以在应用程序中使用它了。

I'm making a Xamarin Android application. 我正在制作一个Xamarin Android应用程序。

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 . 还需要考虑的是,我根本没有任何连接问题,实际上,当我尝试使用Web客户端执行该应用程序时,它正在发送数据,但是我希望它使用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. 默认情况下, await捕获“上下文”(在这种情况下为UI上下文),并在该上下文中恢复执行。 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. 因此,如果调用async方法和任务上的块(例如GetAwaiter().GetResult()Wait()Result ),则UI线程将被阻止,这将阻止async方法继续和完成。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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