Friday, June 6, 2008

Passing credentials to URL - when reading content from a url using System.Net namespace

This is a simple case where a data feed load application was reading from multiple resources for getting feed data. One of the provider switched to basic authentication and required a username and password being passed to access their resource. This can be done very easily using System.Net.NetworkCredential. Let's jump into couple of methods as example to read data from a url requiring credentials:

// Using System.Net.WebClient

WebClient webClient = new WebClient();

webClient.Credentials = new NetworkCredential("userName", "password");

// I set my proxy with webProxy method and use it if needed

//webClient.Proxy = this.webProxy;

using (Stream stream = webClient.OpenRead(url))

{

using (StreamReader reader = new StreamReader(stream))

{

string response = reader.ReadToEnd();

return response;

}

}

// Using System.Net.HttpWebRequest

HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(url);

request.Credentials = new NetworkCredential("userName", "password");

// I set my proxy with webProxy method and use it if needed

//request.Proxy = this.webProxy;

using (Stream stream = request.GetResponse().GetResponseStream())

{

using (StreamReader reader = new StreamReader(stream))

{

string response = reader.ReadToEnd();

return response;

}

}
Love coding!

3 comments:

Anonymous said...

This works for me. Awesome code.

Anonymous said...

Thanks a lot Sir!
You solved my problem.

God bless!

Anonymous said...

Thanks a bunch. Was overworking the whole thing setting up a credentialscache and what not. Cheers