Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles / web / ASP.NET

Calling a webservice programmatically

3.22/5 (7 votes)
30 May 2012CPOL 84.5K  
Calling webservice at runtime

Introduction

Calling a webservice is basically easy in .NET, it is only a matter of adding the webservice as a web reference and using the generated classes. Sometimes you will need to build requests and send them programmatically. In this article we will see you to do it.

Background

Intermediate knowledge in .NET, webservices.

Using the code

C++
string completeUrl ="<a href="http://localhost/testwebservice">http://localhost/testwebservice</a>";

// Create a request for the URL.         
WebRequest request = WebRequest.Create(completeUrl);

// If required by the server, set the credentials.
request.Credentials = CredentialCache.DefaultCredentials;


// If you have a proxy configured.
WebProxy proxyObject = new WebProxy("<a href="http://proxy.com/">http://proxy.com/</a>", true);
request.Proxy = proxyObject;


//Get the response.
HttpWebResponse response = (HttpWebResponse)request.GetResponse();

// Get the stream containing content returned by the server.
Stream dataStream = response.GetResponseStream();


// Open the stream using a StreamReader for easy access.
StreamReader reader = new StreamReader(dataStream);
// Read the content.
string responseFromServer = reader.ReadToEnd();

// Cleanup the streams and the response.

reader.Close();
dataStream.Close();            
response.Close();

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)