Basically while calling a web service, we add service reference to the project. Visual studio automatically generates proxy for you and using that proxy class web service method will be called. But sometimes it is required to call a web service and authenticate it programmatically. There are ways to do this at run-time.
Below code explains the steps how to generate proxy, pass user credentials and call a web service programmatically at run-time.
- using System;
- using System.Net;
- using System.IO;
-
-
- class ConnectToWebService
- {
- static void Main(string[] args)
- {
- string sWebServiceUrl = "https://webservicename.com";
-
-
- WebRequest objWebRequest = WebRequest.Create(sWebServiceUrl);
-
-
- objWebRequest.Proxy = new WebProxy();
-
-
- objWebRequest.Credentials = new NetworkCredential("username", "password");
- objWebRequest.Proxy.Credentials = new NetworkCredential("username", "password");
-
-
- HttpWebResponse objWebResponse = (HttpWebResponse)objWebRequest.GetResponse();
-
-
- StreamReader objStreamReader = new StreamReader(objWebResponse.GetResponseStream());
-
-
- string sResponse = objStreamReader.ReadToEnd();
- Console.WriteLine(sResponse);
- Console.ReadLine();
-
-
- objStreamReader.Close();
- objWebResponse.Close();
- }
- }