开发者

500 Internal Server Error when using HttpWebRequest, how can I get to the real error?

I'm trying to improve the information provided in response to an error handled within an app.

This is the code:

Try
        httpRequestObj = HttpWebRequest.Create(strRequest)
        httpRequestObj.Method = "GET"
        httpRequestObj.UseDefaultCredentials = True
*       httpResponse = httpRequestObj.GetResponse
        Using reader As StreamReader = New StreamReader(httpResponse.GetResponseStream())
            strXML = reader.ReadToEnd()
        End Using
    Catch ex As WebException
        'do something with ex
    End Try

The webexception is thrown on the * line

Currently all I see in the Exception is开发者_如何学JAVA "The remote server returned an error: (500) Internal Server Error". I've looked at the exception in debug but the info I need isn't there- I guess the response would need to be read in to see that info but it never gets that far.

If I take the request and paste it into my browser directly I can see the error details in XML format that is returned from the API I'm calling, info like:

<Error>
  <description>info I want to get to here</description> 
  <detail /> 
  <code>info I want to get to here</code> 
  <source /> 
  <category>info I want to get to here</category> 
  <file>info I want to get to here</file> 
  <line>info I want to get to here</line> 
  <pad /> 
</Error>

Is there any way I can change this code so that I can get past the 500 error and see the actual response, I'd like to be able to parse this xml to find out the real problem for the failure.

Note: the Exception does have an ex.Response (System.Net.HttpWebResponse), but I can't see the info I need in there, only a load of Header info.


You can get the error response from the exception....

try
{
....
} catch(Exception e) {
   if (e is WebException && ((WebException)e).Status==WebExceptionStatus.ProtocolError)
   {
      WebResponse errResp = ((WebException)e).Response;
      using(Stream respStream = errResp.GetResponseStream())
      {
         // read the error response
      }
   }
}


        System.Net.WebResponse response = null;
        try
        {
            response = wreq.GetResponse();
        }
        catch (WebException e)
        {
            if (e.Status == WebExceptionStatus.ProtocolError)
            {
                string error = new System.IO.StreamReader(e.Response.GetResponseStream()).ReadToEnd();
            }
        }
        catch (Exception e)
        {
        }

as simple as this, You will get entire response in the string error.


Try to use Fiddler. It's debuging proxy, which will show you all data sending between client and server. You'll be able to see all headers and context as well.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜