Http Post 请求消息体中的 C# Xml
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/716024/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
C# Xml in Http Post Request Message Body
提问by jumbojs
I am looking for an example of how, in C#, to put a xml document in the message body of a http request and then parse the response. I've read the documentation but I would just like to see an example if there's one available. Does anyone have a example?
我正在寻找一个示例,说明如何在 C# 中将 xml 文档放入 http 请求的消息正文中,然后解析响应。我已经阅读了文档,但如果有可用的示例,我只想看一个示例。有人有例子吗?
thanks
谢谢
回答by Mehrdad Afshari
You should use the WebRequest
class.
你应该使用这个WebRequest
类。
There is an annotated sample available here to send data:
这里有一个带注释的样本可用于发送数据:
回答by Gratzy
private static string WebRequestPostData(string url, string postData)
{
System.Net.WebRequest req = System.Net.WebRequest.Create(url);
req.ContentType = "text/xml";
req.Method = "POST";
byte[] bytes = System.Text.Encoding.ASCII.GetBytes(postData);
req.ContentLength = bytes.Length;
using (Stream os = req.GetRequestStream())
{
os.Write(bytes, 0, bytes.Length);
}
using (System.Net.WebResponse resp = req.GetResponse())
{
if (resp == null) return null;
using (System.IO.StreamReader sr = new System.IO.StreamReader(resp.GetResponseStream()))
{
return sr.ReadToEnd().Trim();
}
}
}