当前位置:  开发笔记 > 编程语言 > 正文

从HttpWebRequest和HttpWebResponse获取Http状态代码(200,301,404等)

如何解决《从HttpWebRequest和HttpWebResponse获取Http状态代码(200,301,404等)》经验,为你挑选了4个好方法。



1> dtb..:
Console.Write((int)response.StatusCode);

HttpStatusCode(类型response.StatusCode)是枚举,其中成员的值与HTTP状态代码匹配,例如

public enum HttpStatusCode
{
    ...
    Moved = 301,
    OK = 200,
    Redirect = 302,
    ...
}


@Alain双倍奖金; bool success = response.IsSuccessStatusCode;
@rusty:如果连接失败,因此无法发送请求并且无法接收响应,则不会有任何http状态代码.
额外:`bool success =((int)response.StatusCode)> = 200 &&((int)response.StatusCode)<300;`
如何获得**HTTP Substatus**值?例如,_404.13内容长度过大_参考:http://www.iis.net/configreference/system.webserver/security/requestfiltering/requestlimits

2> zeldi..:

您必须小心,4xx和5xx范围内的服务器响应会抛出WebException.您需要捕获它,然后从WebException对象获取状态代码:

try
{
    wResp = (HttpWebResponse)wReq.GetResponse();
    wRespStatusCode = wResp.StatusCode;
}
catch (WebException we)
{
    wRespStatusCode = ((HttpWebResponse)we.Response).StatusCode;
}



3> Wojciech Jak..:

根据'dtb',您需要使用HttpStatusCode,但是在'zeldi'之后,您需要特别注意代码响应> = 400.

这对我有用:

HttpWebResponse response = null;
HttpStatusCode statusCode;
try
{
    response = (HttpWebResponse)request.GetResponse();
}
catch (WebException we)
{
    response = (HttpWebResponse)we.Response;
}

statusCode = response.StatusCode;
Stream dataStream = response.GetResponseStream();
StreamReader reader = new StreamReader(dataStream);
sResponse = reader.ReadToEnd();
Console.WriteLine(sResponse);
Console.WriteLine("Response Code: " + (int)statusCode + " - " + statusCode.ToString());



4> Marc..:

只是要挟StatusCodeint.

var statusNumber;
try {
   response = (HttpWebResponse)request.GetResponse();
   // This will have statii from 200 to 30x
   statusNumber = (int)response.StatusCode;
}
catch (WebException we) {
    // Statii 400 to 50x will be here
    statusNumber = (int)we.Response.StatusCode;
}

推荐阅读
Chloemw
这个屌丝很懒,什么也没留下!
DevBox开发工具箱 | 专业的在线开发工具网站    京公网安备 11010802040832号  |  京ICP备19059560号-6
Copyright © 1998 - 2020 DevBox.CN. All Rights Reserved devBox.cn 开发工具箱 版权所有