繁体   English   中英

如何使用 httpwebrequest 发送正文为字符串或字符的 POST 请求?

[英]How do I send a POST request with a body that is a string or a character using httpwebrequest?

我有一个 Post 调用,它需要一个字符串 GUID "AA0DB615-D4CB-4466-BC23-0E0083002220" 我正在使用 HTTPWebRequest 发送请求,但我不确定如何将它与我的 Post 请求一起添加。 基本上我没有在 HTTPWebRequest 中找到任何方法来发送只是一个字符串或字符数据类型的 Post。 他们是不是像 request.AddBody 一样。

我还查看了 GetResponseStream。 我可以使用它作为字符串或字符数据类型写入正文并发送调用吗? 我坚持这一点,任何帮助都会很棒

这是一个使用HttpWebRequest在正文中发送纯文本 GUID 的示例请求,如果您想明确 state 内容类型是纯文本,可以将内容类型设置为“text/plain”

var request = (HttpWebRequest)WebRequest.Create("URL GOES HERE");
request.Method = "POST";
var content = Guid.NewGuid().ToString(); //You should replace this with your GUID
var encoding = new ASCIIEncoding();
var bytes = encoding.GetBytes(content);
request.ContentType = "text/plain";
request.ContentLength = bytes.Length;
using (var requestStream = request.GetRequestStream())
{
    requestStream.Write(bytes, 0, bytes.Length);
    var response = request.GetResponse() as HttpWebResponse;
}

暂无
暂无

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

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