Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I get headers from a 401 Server Error

I'm writing a port scanner to detect web services running on the local network. Some of these web services require basic authentication - I don't know the username/ password for these services, I just want to list them, so I can't provide the credentials at this stage. I'm using the code:

                    var request = (HttpWebRequest)WebRequest.Create("http://" + req);
                    request.Referer = "";
                    request.Timeout = 3000;
                    request.UserAgent = "Mozilla/5.0";
                    request.AllowAutoRedirect = false;
                    request.Method = WebRequestMethods.Http.Head;

                    HttpWebResponse response = null;

                    try
                    {
                        response = (HttpWebResponse) request.GetResponse();
                        // I want to parse the headers here for the server name but as the exception is thrown the response object is null.

                    }
                    catch (Exception ex)
                    {
                        //401 error is caught here - response is null
                    }

I'm then parsing out the server name from the headers that are returned - I know they are being returned because I can see them with fiddler but the HttpWebResponse object is set to null as the GetResponse() method is throwing an exception. Basically - how do I get it to not throw and exception but return the headers along with a status code of 401.

like image 627
Sean Avatar asked Jan 31 '12 05:01

Sean


People also ask

How do I check my 401 error?

In this guide, we've gone over five methods to solve the 401 Unauthorized Error code: Confirm the URL is correct – double-check the URL in case it's misspelled or outdated. Clear user end issues – clear the browser's cache and cookies for a possible solution. If that fails, try flushing your DNS cache.

What is a 401 authorization required error?

A 401 Authorization Required error means you can try accessing the resource again using the correct credentials. In other words, it's often a temporary problem, unlike an HTTP 403 error in which you're expressly forbidden to access the page you're hoping to reach.

How do you check 401 error in Postman?

Make sure that the URL is typed correctly. Verify the API documentation of the service you are trying to reach and make sure you have selected the right authorization type in Postman. Visit the service provider's page and look for a Sign in link. Enter your credentials and then try the page again.


1 Answers

If you catch a WebException you'll have access to ex.Response and you can retrieve your headers from there.

like image 189
lukiffer Avatar answered Nov 08 '22 17:11

lukiffer