Reading HttpStatusCode in a HttpWebResponse

I had problem when the response from a Tomcat server to a HttpWebRequest has a statusCode different from 204 (HttpStatusCode.NoContent), for example in case of “HTTP Status 401 – Bad credentials” or “HTTP Status 403 – Forbidden”.
In fact, in the callback the “request.EndGetResponse” gives a WebException, that is:

response = (HttpWebResponse)request.EndGetResponse(ar);

gives a

System.Net.WebException:  {The remote server returned an error: NotFound."}

so I couldn’d read the response.StatusCode;

A client from Android, that uses the DefaultHttpClient java class, rightly understand that responses from the server with all the statuscodes. On the contrary with My phone 7 client at first I make it work fine ONLY when there is statuscode = NoContent [that means the Credentials are correct (statusCode == HttpStatusCode.NoContent] otherwise a System.Net.WebException: {The remote server returned an error: NotFound.”} is raised and I cannot check the reason of the failure.

After some debug I found that all the responses that are not valid throws a WebException in the callback and then you can get the HttpStatusCode recovering the Response from the WebException variable as explained in the following:

private void AuthenticationCompleted(IAsyncResult ar) {
UserEventArgs args = null;
HttpWebRequest request = (HttpWebRequest)ar.AsyncState;
HttpWebResponse response = null;
try {
// HttpWebResponse
response = (HttpWebResponse)request.EndGetResponse(ar);
//So it seems that there is not the needs to check "if (statusCode == HttpStatusCode.NoContent)"
//because only in thaty case there is not a WebException ....
catch (WebException ex) {
//The WebException is thrown whenever the web request cannot be executed successfully. For e.g 400 and 500 series of responses.
//WebExcpetion has a property named Status which will return the actual status of the response i.e 500 (Internal Server Error).
if (ex.Status == WebExceptionStatus.UnknownError) {
HttpStatusCode httpStatusCode = ((HttpWebResponse) ex.Response).StatusCode;

Informazioni su Enzo Contini

Electronic engineer
Questa voce è stata pubblicata in Windows Phone/Mobile e contrassegnata con , . Contrassegna il permalink.

Lascia un Commento/Leave a comment

Inserisci i tuoi dati qui sotto o clicca su un'icona per effettuare l'accesso:


Stai commentando usando il tuo account Chiudi sessione / Modifica )

Foto Twitter

Stai commentando usando il tuo account Twitter. Chiudi sessione / Modifica )

Foto di Facebook

Stai commentando usando il tuo account Facebook. Chiudi sessione / Modifica )

Google+ photo

Stai commentando usando il tuo account Google+. Chiudi sessione / Modifica )

Connessione a %s...