C# .NET 4.5.1 HttpClient 同步 POST 请求示例 - 获取 HttpResponseMessage
以下是一个使用 HttpClient 同步请求 POST 并返回 HttpResponseMessage 的例子:
using System;
using System.Net.Http;
using System.Text;
namespace HttpClientExample
{
class Program
{
static void Main(string[] args)
{
using (var httpClient = new HttpClient())
{
var url = 'http://example.com/api/test';
var content = new StringContent('{'name':'John Doe','age':30}', Encoding.UTF8, 'application/json');
var response = httpClient.PostAsync(url, content).Result;
if (response.IsSuccessStatusCode)
{
Console.WriteLine('Request successful.');
}
else
{
Console.WriteLine($'Request failed with status code {response.StatusCode}.');
}
Console.WriteLine($'Response content: {response.Content.ReadAsStringAsync().Result}');
}
}
}
}
在上面的例子中,我们首先创建了一个 HttpClient 实例。然后我们定义了请求的 URL 和请求体内容。这里我们使用了 StringContent 来创建一个 JSON 格式的请求体。接着我们使用 PostAsync 方法发送了一个 POST 请求,并使用 Result 属性阻塞等待请求响应。最后我们判断响应是否成功,如果成功则输出 'Request successful.',否则输出 'Request failed with status code {response.StatusCode}.'。最后我们输出响应的内容。注意,在使用 HttpResponseMessage 的 Content 属性之前,需要先调用 ReadAsStringAsync 方法将响应内容读取为字符串。
原文地址: https://www.cveoy.top/t/topic/mmoT 著作权归作者所有。请勿转载和采集!