4

我一直在做一些谷歌搜索,但在这个主题上只取得了部分成功。我想知道是否有人可以建议一个使用 C# 将 XML 发送到 HTTP 服务的 HTTP POST 示例。

我有一个 asmx Web 服务,它从数据库中提取数据并将该数据保存到 XML 文档中。现在我必须使用 SOAP 协议将该 XML 文档发送到 HTTP 服务。

我有这部分代码用于连接服务

WebRequest myReq = WebRequest.Create("https://WEB_URL");
 System.Net.ServicePointManager.CertificatePolicy = new CertificatePolicyClass();

                string username = "SOMETHING";
                string password = "ELSE";
                string usernamePassword = username + ":" + password;
                CredentialCache mycache = new CredentialCache();
                mycache.Add(new Uri("https://WEB_URL"), "Basic", new  NetworkCredential(username, password));
                myReq.Credentials = mycache;
                myReq.Headers.Add("Authorization", "Basic " + Convert.ToBase64String(new ASCIIEncoding().GetBytes(usernamePassword)));

                WebResponse wr = myReq.GetResponse();
                Stream receiveStream = wr.GetResponseStream();
                StreamReader reader = new StreamReader(receiveStream, Encoding.UTF8);
                string content = reader.ReadToEnd();

那么有人有将XML文档发送到http服务的代码吗,这部分我不知道怎么写,我不知道我在写跟踪,我相信它必须像这样

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

所以请有人可以帮助我!谢谢!

4

2 回答 2

6

这是我得到的东西,希望它对你有用:

HttpWebRequest myReq = (HttpWebRequest)WebRequest.Create("https://WEB_URL");
myReq.Method = "POST";
myReq.ContentType = "text/xml";
myReq.Timeout = 30000;
myReq.Headers.Add("SOAPAction", ":\"#save\"");

byte[] PostData = Encoding.UTF8.GetBytes(xmlDocument);
myReq.ContentLength = PostData.Length;

using (Stream requestStream = myReq.GetRequestStream())
{
    requestStream.Write(PostData, 0, PostData.Length);
}

HttpWebResponse response = (HttpWebResponse)myReq.GetResponse();
于 2012-07-12T11:43:08.517 回答
1
    string soap = 
    @"<?xml version=""1.0"" encoding=""utf-8""?>
    <soap:Envelope xmlns:xsi=""http://www.w3.org/2001/XMLSchema-instance"" 
       xmlns:xsd=""http://www.w3.org/2001/XMLSchema"" 
       xmlns:soap=""http://schemas.xmlsoap.org/soap/envelope/"">
      <soap:Body>
        <Register xmlns=""http://tempuri.org/"">
          <id>123</id>
          <data1>string</data1>
        </Register>
      </soap:Body>
    </soap:Envelope>";


HttpWebRequest req = (HttpWebRequest)WebRequest.Create("http://localhost/WebServices/CustomerWebService.asmx");
req.Headers.Add("SOAPAction"http://tempuri.org/Register\"");
req.ContentType = "text/xml;charset=\"utf-8\"";
req.Accept = "text/xml";
req.Method = "POST";

using (Stream stm = req.GetRequestStream())
{
     using (StreamWriter stmw = new StreamWriter(stm))
     {
          stmw.Write(soap);
     }
}

WebResponse response = req.GetResponse();

Stream responseStream = response.GetResponseStream();
于 2016-01-12T15:58:59.633 回答