且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

C# 中的 HTTP 发布 XML 数据

更新时间:2021-11-13 05:36:18

一般:

发布 XML 数据并获取响应(作为字符串)的简单方法示例如下:

An example of an easy way to post XML data and get the response (as a string) would be the following function:

public string postXMLData(string destinationUrl, string requestXml)
{
    HttpWebRequest request = (HttpWebRequest)WebRequest.Create(destinationUrl);
    byte[] bytes;
    bytes = System.Text.Encoding.ASCII.GetBytes(requestXml);
    request.ContentType = "text/xml; encoding='utf-8'";
    request.ContentLength = bytes.Length;
    request.Method = "POST";
    Stream requestStream = request.GetRequestStream();
    requestStream.Write(bytes, 0, bytes.Length);
    requestStream.Close();
    HttpWebResponse response;
    response = (HttpWebResponse)request.GetResponse();
    if (response.StatusCode == HttpStatusCode.OK)
    {
        Stream responseStream = response.GetResponseStream();
        string responseStr = new StreamReader(responseStream).ReadToEnd();
        return responseStr;
    }
    return null;
}

根据您的具体情况:

代替:

request.ContentType = "application/x-www-form-urlencoded";

使用:

request.ContentType = "text/xml; encoding='utf-8'";

另外,删除:

string postData = "XMLData=" + Sendingxml;

并替换:

byte[] byteArray = Encoding.UTF8.GetBytes(postData);

与:

byte[] byteArray = Encoding.UTF8.GetBytes(Sendingxml.ToString());