Consuming a web service with http request response in .NET?
I need开发者_如何学C to create xml message and send it to the web service. Then I should handle the response by looking at the response xml that is coming from service. I have used WCF before but I should do it with old style.
Where should I start ?
Thanks in advance.
Here's some basic C# code that does what you want, where url is the URL of the web service you're calling, action is the soap action of the service and envelope is a string containing the soap envelope for the request:
WebRequest request = CreateHttpRequestFromSoapEnvelope(url, action, envelope);
WebResponse response = request.GetResponse();
private WebRequest CreateHttpRequestFromSoapEnvelope(string url, string action, string envelope)
{
WebRequest request = WebRequest.Create(new Uri(url));
request.Method = "POST";
request.ContentType = "text/xml";
request.Headers.Add(action);
ServicePointManager.Expect100Continue = false;
ApplyProxyIfRequired(request);
using (Stream stream = request.GetRequestStream())
{
using (StreamWriter streamWriter = new StreamWriter(stream))
{
StringBuilder builder = new StringBuilder();
builder.Append("<?xml version=\"1.0\" encoding=\"utf-8\"?>");
builder.Append(envelope);
string message = builder.ToString();
streamWriter.Write(message);
}
}
return request;
}
If you don't want to use WCF / ASMX clients you should start by learning HTTP and SOAP (1.1, 1.2) to understand needed HTTP headers for POST requests and message construction and reading + HttpWebRequest. Doing it this way doesn't make sense - stick with WCF or ASMX (that is actually the old way).
Add a reference to the web service. Visual Studio will create classes for you so that you don't need to create the XML request and parse the XML response yourself.
Check this link http://msdn.microsoft.com/en-us/library/d9w023sx(v=VS.90).aspx
精彩评论