Jim Rogers

Lives in Baton Rouge, LA, with two dogs, one cat, and one lovely wife. I'm a lead developer for GCR Incorporated.

Katrin and Jim

Month List

HttpWebRequest 401

by Jim Jul 22, 2008 9:12 AM

Getting data with HttpWebRequest is straightforward, until it isn't...

My program stopped working recently, returning a 401 unauthorized from my request. I knew I was sending the right credentials.

A random newsgroup thread tipped me off to the solution:

HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
request.Credentials = CredentialCache.DefaultCredentials;
request.Accept = "image/gif, image/x-xbitmap, image/jpeg, image/pjpeg, " + 
    "application/vnd.ms-excel, application/vnd.ms-powerpoint, " + 
    "application/msword, */*";
WebResponse response = request.GetResponse();

The key is setting the Accept property; I wasn't doing that before. I don't know what happened on the server that makes it now require this header, but now it works...