Click here to Skip to main content

Calling a webservice programmatically

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

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();


Web01 | 2.8.160208.1 | Advertise | Privacy
Copyright © CodeProject, 1999-2016
All Rights Reserved. Terms of Service