HttpWebRequest接受500内部服务器错误

本文关键字:服务器 错误 内部 接受 HttpWebRequest | 更新日期: 2023-09-27 18:28:43

这是我的代码:

HttpWebRequest req = WebRequest.Create(url) as HttpWebRequest;
WebResponse wr = req.GetResponse();

当服务器返回500内部服务器错误时,req中会抛出异常。GetResponse()。我希望GetResponse()接受这个响应代码,传递的url抛出这个响应代码是正常的。尽管响应代码500内部服务器错误,我还是想解析Html。是否可以对GetResponse()方法说不验证响应代码?

HttpWebRequest接受500内部服务器错误

try
{
    HttpWebRequest req = WebRequest.Create(url) as HttpWebRequest;
    WebResponse wr = req.GetResponse();
}
catch (WebException wex)
{
    var pageContent = new StreamReader(wex.Response.GetResponseStream())
                          .ReadToEnd();
}

我用以下代码解决了问题:

class Program
{
    static void Main(string[] args)
    {
        var soap = @"<s:Envelope xmlns:s=""http://schemas.xmlsoap.org/soap/envelope/"" xmlns:tem=""http://tempuri.org/""><s:Body><GetData xmlns = ""http://tempuri.org/""><value>2</value></GetData></s:Body></s:Envelope>";
        HttpWebRequest req = (HttpWebRequest)WebRequest.Create(@"http://localhost:51148/Service1.svc");
        req.Headers.Add($"SOAPAction", "http://tempuri.org/IService1/GetData");
        req.ContentType = "text/xml;charset='"utf-8'"";
        byte[] data = System.Text.Encoding.UTF8.GetBytes(soap);
        req.ContentLength = data.Length;
        req.Accept = "text/xml";
        req.Method = "POST";
        Stream stm = req.GetRequestStream();
        stm.Write(data, 0, data.Length);
        try
        {
            WebResponse response = req.GetResponse();
            Stream responseStream = response.GetResponseStream();
        }
        catch (WebException webex)
        {
            WebResponse errResp = webex.Response;
            using (Stream respStream = errResp.GetResponseStream())
            {
                StreamReader reader = new StreamReader(respStream);
                string text = reader.ReadToEnd();
            }
        }
    }
}