I have the following situation. I am calling some web api to login to a certain server. The call looks like that:
webhost/login?username=email@domain.com&password=alin
The return is always an xml like:
<response>
<error>invalid user</error>
</response>
or
<response>
<token>XXXXXXX</token>
</response>
So, if I call this api with the wrong credentials, the page return with a 401 http status, and then at this line
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
it raise an error and it jumps in catch block. (of course) The thing is, the next line
stream = response.GetResponseStream();
never get to happen so I will never get to read the returned xml , including the error message inside it. Still, if i just paste the link in browser, the page and teh xml gets loaded
Why does the browser loads the xml and my response component does not. by the way , i am doing this in C#
Thanks
Stream stream = null;
try
{
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(finalURL);
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
stream = response.GetResponseStream();
}
catch(Exception ex)
{
string x = ex.Message;
}
Well you’re not trying to look at the response.
If you catch a specific exception (as you should – catching
Exceptionis a bad idea in most cases) you could get at the response data:Note that you should have a
usingstatement for yourHttpWebResponsein the non-failure condition too, otherwise you’ll end up leaving resources open.