使用Web服务的HTTP POST

时间:2012-07-12 11:27:26

标签: c# xml asmx

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

我有一个从数据库中提取数据的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服务,这部分我不知道怎么写,我不知道我在写跟踪,我相信它必须像这样去一些< / p>

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

有人可以帮助我!谢谢!

2 个答案:

答案 0 :(得分: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();

答案 1 :(得分: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();
相关问题