How To POST SOAP To A .Net Web Service



TODO

Have you ever wanted to POST SOAP to a .Net Webservice?

 

SOLUTION:

HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create("http://myservice.com/myservice.asmx");

String xmlString = "<?xml version=\"1.0\" encoding=\"UTF-8\"?><soapenv:Envelope xmlns:soapenv=\"http://www.w3.org/2003/05/soap-envelope\"><soapenv:Body>YOUR SOAP BODY HERE</soapenv:Body></soapenv:Envelope>";
ASCIIEncoding encoding = new ASCIIEncoding();

byte[] bytesToWrite = encoding.GetBytes(xmlString);
request.Method = "POST";
request.ContentLength = bytesToWrite.Length;
request.ContentType = "application/soap+xml; charset=UTF-8; action=\"http://myservice.com/MyMethod\"";
request.UserAgent = "Axis2";
request.Host = "myservice.com";
Stream newStream = request.GetRequestStream();
newStream.Write(bytesToWrite, 0, bytesToWrite.Length);
newStream.Close();

try
{
    HttpWebResponse response = (HttpWebResponse)request.GetResponse();
    Stream dataStream = response.GetResponseStream();
    StreamReader reader = new StreamReader(dataStream);

    string responseFromServer = reader.ReadToEnd();
    Console.WriteLine(responseFromServer);
}
catch (WebException ex)
{
    Console.WriteLine(ex);
    WebResponse errRsp = ex.Response;
    using (StreamReader rdr = new StreamReader(errRsp.GetResponseStream()))
    {
        Console.WriteLine(rdr.ReadToEnd());
    }
}

 

NOTES:

No notes apply to this topic.



Add comment

  Country flag

biuquote
  • Comment
  • Preview
Loading