HttpWebRequest.GetResponse()失败时如何获取错误信息

时间:2011-08-31 18:56:47

标签: c# httpwebrequest httpwebresponse

我正在启动一个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)."
}

非常感谢任何帮助。

5 个答案:

答案 0 :(得分:131)

  

这可以使用HttpWebRequest和HttpWebResponse吗?

您可以让您的Web服务器简单地捕获异常文本并将其写入响应正文,然后将状态代码设置为500.现在客户端遇到500错误时会抛出异常,但您可以读取响应流并获取异常消息。

所以你可以捕获一个WebException,如果从服务器返回非200状态代码并读取它的正文,将会抛出该代码:

catch (WebException ex)
{
    using (var stream = ex.Response.GetResponseStream())
    using (var reader = new StreamReader(stream))
    {
        Console.WriteLine(reader.ReadToEnd());
    }
}
catch (Exception ex)
{
    // Something more serious happened
    // like for example you don't have network access
    // we cannot talk about a server exception here as
    // the server probably was never reached
}

答案 1 :(得分:6)

我在尝试检查FTP站点上是否存在文件时遇到了这个问题。如果文件不存在,则在尝试检查其时间戳时会出错。但是我想通过检查它的类型来确保错误不是别的。

Response上的WebException属性属于FtpWebResponse类型,您可以在其中查看其StatusCode属性以查看您拥有的which FTP error

这是我最终得到的代码:

    public static bool FileExists(string host, string username, string password, string filename)
    {
        // create FTP request
        FtpWebRequest request = (FtpWebRequest)WebRequest.Create("ftp://" + host + "/" + filename);
        request.Credentials = new NetworkCredential(username, password);

        // we want to get date stamp - to see if the file exists
        request.Method = WebRequestMethods.Ftp.GetDateTimestamp;

        try
        {
            FtpWebResponse response = (FtpWebResponse)request.GetResponse();
            var lastModified = response.LastModified;

            // if we get the last modified date then the file exists
            return true;
        }
        catch (WebException ex)
        {
            var ftpResponse = (FtpWebResponse)ex.Response;

            // if the status code is 'file unavailable' then the file doesn't exist
            // may be different depending upon FTP server software
            if (ftpResponse.StatusCode == FtpStatusCode.ActionNotTakenFileUnavailable)
            {
                return false;
            }

            // some other error - like maybe internet is down
            throw;
        }
    }

答案 2 :(得分:1)

我遇到了类似的情况:

我尝试使用BasicHTTPBinding在HTTP错误消耗SOAP服务的情况下读取原始响应。

但是,使用GetResponseStream()阅读回复时,出现错误:

  

流不可读

所以,这段代码对我有用:

try
{
    response = basicHTTPBindingClient.CallOperation(request);
}
catch (ProtocolException exception)
{
    var webException = exception.InnerException as WebException;
    var rawResponse = string.Empty;

    var alreadyClosedStream = webException.Response.GetResponseStream() as MemoryStream;
    using (var brandNewStream = new MemoryStream(alreadyClosedStream.ToArray()))
    using (var reader = new StreamReader(brandNewStream))
        rawResponse = reader.ReadToEnd();
}

答案 3 :(得分:0)

您还可以使用this library将HttpWebRequest和Response包装到简单的方法中,这些方法根据结果返回对象。它使用了这些答案中描述的一些技术,并且有大量代码受此和类似线程的答案启发。它会自动捕获任何异常,尝试提取尽可能多的样板代码以提出这些Web请求,并自动反序列化响应对象。

使用此包装器代码看起来像的例子很简单

    var response = httpClient.Get<SomeResponseObject>(request);
    
    if(response.StatusCode == HttpStatusCode.OK)
    {
        //do something with the response
        console.Writeline(response.Body.Id); //where the body param matches the object you pass in as an anonymous type.  
    }else {
         //do something with the error
         console.Writelint(string.Format("{0}: {1}", response.StatusCode.ToString(), response.ErrorMessage);

    }

完整披露 该库是一个免费的开源包装器库,我是该库的作者。我没有从中赚钱,但多年来发现它非常有用,并且可以肯定,仍在使用HttpWebRequest / HttpWebResponse类的任何人都可以。

这不是灵丹妙药,但支持使用get和post以及JSON或XML请求和响应的异步和非异步方式进行get,post和delete。截至2020年6月21日,它一直处于积极维护状态

答案 4 :(得分:-2)

HttpWebRequest myHttprequest = null;
HttpWebResponse myHttpresponse = null;
myHttpRequest = (HttpWebRequest)WebRequest.Create(URL);
myHttpRequest.Method = "POST";
myHttpRequest.ContentType = "application/x-www-form-urlencoded";
myHttpRequest.ContentLength = urinfo.Length;
StreamWriter writer = new StreamWriter(myHttprequest.GetRequestStream());
writer.Write(urinfo);
writer.Close();
myHttpresponse = (HttpWebResponse)myHttpRequest.GetResponse();
if (myHttpresponse.StatusCode == HttpStatusCode.OK)
 {
   //Perform necessary action based on response
 }
myHttpresponse.Close();