HttpWebRequest accept 500 Internal Server Error

2019-04-19 12:33发布

问题:

This is my code:

HttpWebRequest req = WebRequest.Create(url) as HttpWebRequest;

WebResponse wr = req.GetResponse();

When the server returns 500 Internal Server Error, exception is thrown in req.GetResponse(). I would like the GetResponse() to accept this Response Code, it is normal for the passed url to throw this Response Code. I would like to parse the Html despite Response Code 500 Internal Server Error. Is it possible to say to GetResponse() method not to verify the Response Code?

回答1:

try
{
    HttpWebRequest req = WebRequest.Create(url) as HttpWebRequest;

    WebResponse wr = req.GetResponse();
}
catch (WebException wex)
{
    var pageContent = new StreamReader(wex.Response.GetResponseStream())
                          .ReadToEnd();
}


回答2:

I resolved with this code:

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();
            }
        }
    }
}