C# Xml in Http Post Request Message Body

前端 未结 2 1185
栀梦
栀梦 2021-02-05 17:03

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

2条回答
  •  抹茶落季
    2021-02-05 17:44

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

提交回复
热议问题