c# - 如何在 Windows Phone 8 中的 HttpClient 请求中发送 Post 正文?

标签 c# windows-phone-8 httpclient

我已经编写了下面的代码来发送标题,发布参数。问题是我正在使用 SendAsync,因为我的请求可以是 GET 或 POST。我如何将 POST Body 添加到这段代码中,以便如果有任何 post body 数据,它会添加到我发出的请求中,如果它是简单的 GET 或 POST 没有 body,它会以这种方式发送请求。请更新以下代码:

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();

最佳答案

更新 2:

来自 @Craig Brown :

As of .NET 5 you can do:
requestMessage.Content = JsonContent.Create(new { Name = "John Doe", Age = 33 });

参见 JsonContent类文档

更新 1:

哦,它可以更好(来自 answer ):

requestMessage.Content = new StringContent("{\"name\":\"John Doe\",\"age\":33}", Encoding.UTF8, "application/json");

这取决于你有什么内容。您需要使用新的 HttpContent 初始化您的 requestMessage.Content 属性.例如:

...
// Add request body
if (isPostRequest)
{
    requestMessage.Content = new ByteArrayContent(content);
}
...

content 是您的编码内容。您还应该包含正确的 Content-type header 。

关于c# - 如何在 Windows Phone 8 中的 HttpClient 请求中发送 Post 正文?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25158452/

相关文章:

c# - XNA : How to use double value within Draw() method instead of float to get precise rotation?

c# - Where vs. foreach with if - 为什么会有不同的结果?

javascript - 放大时平滑自动滚动到底部 JavaScript

windows-phone-8 - Windows Phone 8 应用程序栏

c# - 在服务之间共享 HttpClient

java - HttpClient 4.1.x 的文档在哪里?

c# - 如何从 Httpclient.SendAsync 调用获取和打印响应

c# - 当 SSL 不可行时,最好的 WCF 安全模式是什么

c# - C#中如何从DataGridView中获取选中的行内容?

c# - 在 wp8 的 TextBox 中禁用复制和粘贴