Console.Write((int)response.StatusCode);
HttpStatusCode(类型response.StatusCode
)是枚举,其中成员的值与HTTP状态代码匹配,例如
public enum HttpStatusCode { ... Moved = 301, OK = 200, Redirect = 302, ... }
您必须小心,4xx和5xx范围内的服务器响应会抛出WebException.您需要捕获它,然后从WebException对象获取状态代码:
try { wResp = (HttpWebResponse)wReq.GetResponse(); wRespStatusCode = wResp.StatusCode; } catch (WebException we) { wRespStatusCode = ((HttpWebResponse)we.Response).StatusCode; }
根据'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());
只是要挟StatusCode
来int
.
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; }