.NET Consuming Web Service with HttpRequest

Connecting to web services in Visual Studio 2010 can be a headache if configuration is not done properly. For instance, service references with authentication requires additional line of codes in web.config or app.config. These codes are placed between client header tags.

In some case, authentication may not be enough. Web service may require inputs and these inputs are send via XML structure. In my case, some input fields are nullable which creates xsi:nil="true" attribute in request.xml. It brokes the requested structure. There may be other cases that results in similar errors.

To solve the problem, I decided to call web service directly via HttpRequest.I downloaded and installed Soap Pro Trial edition to create exact request.xml. I added authentication code from app.config to request.xml for secure connection.
Then I wrote the following code:

HttpWebRequest req = (HttpWebRequest)WebRequest.Create("web service url ");
req.Headers.Add("SOAPAction", "\"thisl line can be found in first line of your request.xml"");
req.ContentType = "text/xml;charset=\"utf-8\"";
req.Accept = "text/xml";
req.Method = "POST";
//open request stream and unite with my stream which has the request.xml
using (Stream stm = req.GetRequestStream())
using (StreamWriter stmw = new StreamWriter(stm))
stmw.Write("xml string request.xml");
WebResponse response = req.GetResponse();

After getting the correct response the response.xml can be converted to a string.

Stream responseStream = response.GetResponseStream();
StreamReader resso = new StreamReader(responseStream);
string bobo = "";
bobo = resso.ReadToEnd();

Donot forget to close your streams at the end.

No comments:

Post a Comment