2016-03-14 91 views
0

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

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

编辑:你用一个简单的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,也在doc中。

// 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."); 

你有没有试过这样的?

+0

我遇到的问题是响应称它是响应在第一位定义的行上的错误,所以我没有机会捕获流,因为代码已将其称为错误。 (在这一行:HttpWebResponse myHttpWebResponse =(HttpWebResponse)myHttpWebRequest.GetResponse();) –

+0

添加适当的错误检查,然后此解决方案工作。 –

+0

您是否完成错误检查?你添加了一个try-catch? – informaticienzero