如何从 401 服务器错误获取标头
我正在编写一个端口扫描器来检测本地网络上运行的 Web 服务。其中一些 Web 服务需要基本身份验证 - 我不知道这些服务的用户名/密码,我只想列出它们,因此现阶段无法提供凭据。我正在使用代码:
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
}
然后我从返回的标头中解析出服务器名称 - 我知道它们正在被返回,因为我可以使用 fiddler 看到它们,但 HttpWebResponse 对象作为 GetResponse() 方法设置为 null正在抛出异常。基本上 - 我如何让它不抛出异常,而是返回标头以及状态代码 401。
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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
如果您捕获
WebException
,您将可以访问ex.Response
并且可以从那里检索标头。If you catch a
WebException
you'll have access toex.Response
and you can retrieve your headers from there.