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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-04 22:15:09  来源:igfitidea点击:

C# Xml in Http Post Request Message Body

c#xmlhttpwebrequesthttpwebresponse

提问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 WebRequestclass.

你应该使用这个WebRequest类。

There is an annotated sample available here to send data:

这里有一个带注释的样本可用于发送数据:

http://msdn.microsoft.com/en-us/library/debx8sh9.aspx

http://msdn.microsoft.com/en-us/library/debx8sh9.aspx

回答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();
        }
    }
}