简体   繁体   English

HttpClient中的c#http内容

[英]HttpClient in c# http content

I am trying to send a json to a certain localhost site but somehow im not able to do it properly. 我正在尝试将json发送到某个localhost站点但不知何故我无法正常执行。 Im getting an issue in the PostAsync line: 我在PostAsync行中遇到问题:

Cannot implicitly convert type 'System.Threading.Tasks.Task<System.Net.Http.HttpResponseMessage>' to 'System.Net.Http.HttpResponseMessage

I do not really know how to fix the conversion, thanks for any help. 我真的不知道如何修复转换,感谢您的帮助。

using (HttpClient client = new HttpClient())
{
    try
    {
        StringContent json = new StringContent(jsonText, Encoding.UTF8, "application/json");
        HttpResponseMessage response = client.PostAsync("http://www.localhost.com/", json);
        response.EnsureSuccessStatusCode();
        string responseBody =  response.Content.ReadAsStringAsync();
        // Above three lines can be replaced with new helper method below
        // string responseBody = await client.GetStringAsync(uri);

        Console.WriteLine(responseBody);
    }
    catch (HttpRequestException e)
    {
        Console.WriteLine("\nException Caught!");
        Console.WriteLine("Message :{0} ", e.Message);
    }
}

请尝试添加等待您的PostAsync和ReadAsStringAsync最好的问候。

When executing asynchronous function calls you have to await task completion before getting actual return value of function. 执行异步函数调用时,必须在获取函数的实际返回值之前await任务完成。

Also please notice that when your method has at least one await you have to decorate your method with async keyword. 另请注意,当您的方法至少有一个await您必须使用async关键字装饰您的方法。

Following is working example of your code snippet. 以下是您的代码段的工作示例。

using (HttpClient client = new HttpClient())
{
    try
    {
        StringContent json = new StringContent(jsonText, Encoding.UTF8, "application/json");
        HttpResponseMessage response = await client.PostAsync("http://www.localhost.com/", json);
        response.EnsureSuccessStatusCode();
        string responseBody = await response.Content.ReadAsStringAsync();
        // Above three lines can be replaced with new helper method below
        // string responseBody = await client.GetStringAsync(uri);

        Console.WriteLine(responseBody);
    }
    catch (HttpRequestException e)
    {
        Console.WriteLine("\nException Caught!");
        Console.WriteLine("Message :{0} ", e.Message);
    }
}

There are plenty of good Q&A's regarding async/await issue, one good example here . 关于异步/等待问题有很多很好的问答, 这里有一个很好的例子。

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

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