Reputation: 1003
I have been doing some Google searches and only getting partial successful on this topic. I was wondering if someone could suggest an example of doing an HTTP POST using C# to send XML to HTTP service.
I have a asmx web service that extracts data from database and I save that data to XML document. Now I have to send that XML document using SOAP protocol to HTTP service.
I have this part of code for connectig to service
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();
So does anybody have a code to send XML document to http service, this part I don't know how to write, I don't know am I on the write trace, I belive it has to go somethig like this
request.Method = "POST";
request.ContentType = "application/x-www-form-urlencoded";
So plese can somebody help me! THANKS!
Upvotes: 4
Views: 33898
Reputation: 143
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();
Upvotes: 1
Reputation: 86
Here is something I get, hope it's useful to you:
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();
Upvotes: 7