Is the server using HTTP basic authentication or some other kind? If it's using HTTP basic then you can set the Credentials
property on the web request to a credential containing the correct username and password, and set the PreAuthenticate
property to true.
Here's an example (it's untested, so use it as a guideline only):
var uri = new Uri("https://somesite.com/something");
var request = WebRequest.Create(uri) as HttpWebRequest;
request.Credentials = new NetworkCredential("myUserName","myPassword");
request.PreAuthenticate = true;
var response = request.GetResponse();
Note: In my experience doing this, there is some odd behavior in the .NET framework. You'd think it should do what the code says, but it actually does this:
- Send request to server with no credentials
- Server responds with 401
- Re-Send request with the credentials you gave it
- Server accepts request.
I have no idea why it would do this, as it seems broken, so perhaps it was a quirk of my machine and maybe it won't happen to you.
If your app is not performance sensitive, and your requests aren't POSTS of large data, you probably won't notice, but to get around it, I had to manually build the HTTP basic authentication header and set it on the HttpWebRequest
manually by manipulating the Headers
collection.