从httpwebresponse异常获取内容

时间:2016-03-14 20:41:21

标签: c# httpwebresponse

我的远程服务器将Web异常作为错误请求抛出。但我知道错误中包含的信息比我得到的更多。如果我查看异常中的详细信息,则不会列出响应的实际内容。我只能看到内容类型,内容长度和内容编码。如果我通过另一个库(例如restsharp)运行相同的消息,我将从远程服务器看到详细的异常信息。我怎么能从响应中获得更多细节,因为我知道远程服务器正在发送它们?

static string getXMLString(string xmlContent, string url)
{
        //string Url;
        string sResult;
        //Url = ConfigurationManager.AppSettings["UserURl"] + url;

        var httpWebRequest = (HttpWebRequest)WebRequest.Create(url);
        httpWebRequest.ContentType = "application/xml";
        httpWebRequest.Method = "POST";
        using (var streamWriter = new StreamWriter(httpWebRequest.GetRequestStream()))
        {
            streamWriter.Write(xmlContent);
            streamWriter.Flush();
            streamWriter.Close();
            var httpResponse = (HttpWebResponse)httpWebRequest.GetResponse();
            using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
            {
                var result = streamReader.ReadToEnd();
                sResult = result;
            }
        }
        return sResult;
}

1 个答案:

答案 0 :(得分:1)

编辑:您是否尝试使用简单的try-catch查看是否可以获得更多详细信息?

try
{
    var response = (HttpWebResponse)(request.GetResponse());
}
catch(Exception ex)
{
    var response = (HttpWebResponse)ex.Response;
}

在我的回答中,我注意到在代码中有一些关于编码的内容,你没有指定。请查看here以获取此类代码。

var encoding = ASCIIEncoding.ASCII;
using (var reader = new System.IO.StreamReader(response.GetResponseStream(), encoding))
{
    string responseText = reader.ReadToEnd();
}

here,在文档中,也是。

// Creates an HttpWebRequest with the specified URL. 
HttpWebRequest myHttpWebRequest = (HttpWebRequest)WebRequest.Create(url); 
// Sends the HttpWebRequest and waits for the response.         
HttpWebResponse myHttpWebResponse = (HttpWebResponse)myHttpWebRequest.GetResponse(); 
// Gets the stream associated with the response.
Stream receiveStream = myHttpWebResponse.GetResponseStream();
Encoding encode = System.Text.Encoding.GetEncoding("utf-8");
// Pipes the stream to a higher level stream reader with the required encoding format. 
StreamReader readStream = new StreamReader( receiveStream, encode );
Console.WriteLine("\r\nResponse stream received.");

你试过这个吗?