我正在向 REST 服务发出 HTTP post 请求,当我收到 HttpWebResponse 返回时,我正在执行以下检查。当我执行 webresponse != null 时,我是否还应该检查 responseStream != null
HttpWebResponse webResponse = webRequest.GetResponse() as HttpWebResponse;
if (webResponse != null)
{
var responseStream = webResponse.GetResponseStream();
int responseCode = (int)webResponse.StatusCode;
if (responseStream != null && responseCode == (int)HttpStatusCode.Created)
{
cmsStoreWebResponse = ((new StreamReader(responseStream)).ReadToEnd());`
}
else
{
this.LogError(string.Format("{0}\n Endpoint: {1}\n {2} {3} {4}", ErrorCodes.IWS_CMSRetrieve_ERROR_001, oagEndpointUrl, ErrorCodes.IWS_CMSStore_ERROR_SERVICE_DOWN, responseStream, responseCode));
serviceData.Fatal = true;
serviceData.ErrorCode = ErrorCodes.IWS_EFORMSFORMSETS_001;
serviceData.ErrorDetails = string.Format("\nEndpoint: {0}\n {1}", oagEndpointUrl, ErrorCodes.RESPONSE_STREAM_NULL);
throw new FaultException<ServiceExceptionData>(serviceData, new FaultReason(string.Format("\nEndpoint: {0}\n {1}", oagEndpointUrl, ErrorCodes.RESPONSE_STREAM_NULL)));
}
}
else
{
this.LogError(string.Format("{0}\n Endpoint: {1}\n {2}", ErrorCodes.IWS_CMSRetrieve_ERROR_001, oagEndpointUrl, ErrorCodes.IWS_CMSStore_ERROR_SERVICE_DOWN));
serviceData.Fatal = true;
serviceData.ErrorCode = ErrorCodes.IWS_EFORMSFORMSETS_001;
serviceData.ErrorDetails = string.Format("\nEndpoint: {0}\n {1}", oagEndpointUrl, ErrorCodes.RESPONSE_STREAM_NULL);
throw new FaultException<ServiceExceptionData>(serviceData, new FaultReason(string.Format("\nEndpoint: {0}\n {1}", oagEndpointUrl, ErrorCodes.RESPONSE_STREAM_NULL)));
}
没有派生自的内置类型WebResponse
, 尤其HttpWebResponse
,可以返回 null。这种迷信的信念误导了许多开发人员。不要检查 null。这样的代码就是死代码。
与返回空流相比,null 意味着什么?!这根本不符合逻辑。
Also, GetResponse()
不能返回 null。再说一遍,这是什么意思? HTTP 协议不支持“空响应”的概念。如果由于库错误而发生这种情况,无论如何都无法处理这种情况。任何此类检查都没有帮助。
可以创建派生类WebResponse
返回疯狂的值,例如null
。没有内置类可以做到这一点,并且应该将其视为返回的错误null
。派生类WebResponse
非常罕见。我从来没有见过一个。
这是一个很好的代码模式:
var request = WebRequest.Create("http://example.org/");
using (var response = request.GetResponse())
using (var responseStream = response.GetResponseStream())
using (var responseReader = new StreamReader(responseStream))
{
var contents = responseReader.ReadToEnd();
}
它演示了如何使用简洁、安全地读取 HTTP URL 的内容HttpWebRequest
.
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)