C#中的Http Post请求消息体中的Xml

12

我正在寻找一份 C# 的示例,展示如何将一个 XML 文档放入 HTTP 请求的消息体中,然后解析响应。我已经阅读了文档,但如果有可用的示例,我仍想看到一个。有人有示例吗?

谢谢

2个回答

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

5

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接