16

这是我的代码:

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

WebResponse wr = req.GetResponse();

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

4

2 回答 2

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

    WebResponse wr = req.GetResponse();
}
catch (WebException wex)
{
    var pageContent = new StreamReader(wex.Response.GetResponseStream())
                          .ReadToEnd();
}
于 2013-08-23T13:20:30.933 回答
0

我用这段代码解决了:

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();
            }
        }
    }
}
于 2017-11-06T01:07:47.900 回答