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

编程入门 行业动态 更新时间:2024-10-10 03:26:23
本文介绍了如何在Windows Phone 8的HttpClient请求中发送Post正文?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我已经编写了下面的代码来发送标头,发布参数.问题是我正在使用SendAsync,因为我的请求可以是GET或POST.我如何在这部分代码中添加POST正文,以便如果在我提出的请求中添加了任何正文信息,并且如果它的简单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();

推荐答案

这取决于您拥有的内容.您需要使用新的requestMessage.Content属性="noreferrer"> 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.

哦,它甚至更好(来自此 answer ):

Oh, it can be even nicer (from this answer):

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

更多推荐

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

本文发布于:2023-10-12 04:20:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1483707.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:如何在   正文   Windows   Phone   HttpClient

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!