【发布时间】:2011-11-07 21:15:36
【问题描述】:
我正在启动一个 HttpWebRequest,然后检索它的响应。有时,我会收到 500(或至少 5##)错误,但没有说明。我可以控制两个端点,并希望接收端获得更多信息。例如,我想将异常消息从服务器传递到客户端。这可以使用 HttpWebRequest 和 HttpWebResponse 吗?
代码:
try
{
HttpWebRequest webRequest = HttpWebRequest.Create(URL) as HttpWebRequest;
webRequest.Method = WebRequestMethods.Http.Get;
webRequest.Credentials = new NetworkCredential(Username, Password);
webRequest.ContentType = "application/x-www-form-urlencoded";
using(HttpWebResponse response = webRequest.GetResponse() as HttpWebResponse)
{
if(response.StatusCode == HttpStatusCode.OK)
{
// Do stuff with response.GetResponseStream();
}
}
}
catch(Exception ex)
{
ShowError(ex);
// if the server returns a 500 error than the webRequest.GetResponse() method
// throws an exception and all I get is "The remote server returned an error: (500)."
}
对此的任何帮助将不胜感激。
【问题讨论】:
-
我只是补充一点,始终建议尽量减少由
try语句包裹的内容。在您的情况下,using行之前的所有内容都可能写在外面。
标签: c# httpwebrequest httpwebresponse