问题描述
我编写了下面的代码来发送标头、发布参数.问题是我使用的是 SendAsync,因为我的请求可以是 GET 或 POST.我如何将 POST Body 添加到这段代码中,以便如果有任何 post body 数据,它会被添加到我发出的请求中,如果它的简单 GET 或 POST 没有正文,它就会以这种方式发送请求.请更新以下代码:
I have written the code below to send headers, post parameters. The problem is that I am using SendAsync since my request can be GET or POST. How can I add POST Body to this peice of code so that if there is any post body data it gets added in the request that I make and if its simple GET or POST without body it send the request that way. Please update the code below:
HttpClient client = new HttpClient();
// Add a new Request Message
HttpRequestMessage requestMessage = new HttpRequestMessage(RequestHTTPMethod, ToString());
// Add our custom headers
if (RequestHeader != null)
{
foreach (var item in RequestHeader)
{
requestMessage.Headers.Add(item.Key, item.Value);
}
}
// Add request body
// Send the request to the server
HttpResponseMessage response = await client.SendAsync(requestMessage);
// Get the response
responseString = await response.Content.ReadAsStringAsync();
推荐答案
UPDATE 2:
来自@Craig Brown:
从 .NET 5 开始,您可以:requestMessage.Content = JsonContent.Create(new { Name = "John Doe", Age = 33 });
参见 JsonContent 类文档
哦,它可以更好(来自这个答案):
Oh, it can be even nicer (from this answer):
requestMessage.Content = new StringContent("{"name":"John Doe","age":33}", Encoding.UTF8, "application/json");
这取决于你有什么内容.您需要使用新的 HttpContent.例如:
This depends on what content do you have. You need to initialize your requestMessage.Content
property with new HttpContent. For example:
...
// Add request body
if (isPostRequest)
{
requestMessage.Content = new ByteArrayContent(content);
}
...
其中 content
是您编码的内容.您还应该包含正确的 Content-type 标头.
where content
is your encoded content. You also should include correct Content-type header.
这篇关于如何在 Windows Phone 8 的 HttpClient 请求中发送 Post 正文?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!