我正在使用webservice来调用其他服务。我必须用循环调用许多服务。
现在的问题是,当某些服务不可用时,循环就会中断。
HttpWebRequest request = WebRequest.Create(stringBuilder.ToString()) as HttpWebRequest;
request.ContentType = "application/json; charset=utf-8";
request.Credentials = CredentialCache.DefaultCredentials;
response = (HttpWebResponse)request.GetResponse();
if (response.StatusCode != HttpStatusCode.OK)
{
continue;
}
当服务不可用时(错误500),在我检查statusCode之前它已经坏了。
response = (HttpWebResponse)request.GetResponse();
如何检查错误并继续与其他服务通话?
答案 0 :(得分:2)
这是设计并在文档中有详细解释,请参阅:http://msdn.microsoft.com/en-us/library/system.net.httpwebrequest.getresponse.aspx
如果抛出WebException,请使用的Response和Status属性 确定服务器响应的异常。
使您的代码看起来像:
HttpWebRequest request = WebRequest.Create(stringBuilder.ToString()) as HttpWebRequest;
request.ContentType = "application/json; charset=utf-8";
request.Credentials = CredentialCache.DefaultCredentials;
try
{
response = (HttpWebResponse)request.GetResponse();
// perform normal processing
}
catch(WebException ex)
{
// are you sure you just want to swallow the exception like this?
continue;
}