Assigning Basic Authorization HTTP Header to HttpWebRequest
If you're making a call to a HTTP resource that requires a Basic Authorization HTTP header, you can use the following code:
HttpWebRequest request = (HttpWebRequest)WebRequest.Create("url-here");
request.Credentials = new NetworkCredential("username", "password");
Then post the request in the usual way.
The confusion comes because on the first call the HTTP header will not be present on the request. The framework is relying on the first call receiving a 401 response, with a WWW-Authenticate header present, giving a Basic realm=<realm-name> value. A second call will then be made with the correct headers in place.
If you are just consuming the resource, chances are the server will respond in a way that allows this behaviour. However, if it doesn't respond with a 401, or that 401 response doesn't contain the WWW-Authenticate header (or you just don't want to make 2 calls), then you have to manually add the Authorization header to the request:
byte[] authBytes = Encoding.UTF8.GetBytes("user:password".ToCharArray());
request.Headers["Authorization"] = "Basic " + Convert.ToBase64String(authBytes);