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) { //http://stackoverflow.com/questions/2182544/c-httpwebrequest-getresponse-how-is-statuscode-usage-handled-for-a-non-excepti //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). //http://discuss.joelonsoftware.com/default.asp?dotnet.12.524225.2 if (ex.Status == WebExceptionStatus.UnknownError) { HttpStatusCode httpStatusCode = ((HttpWebResponse) ex.Response).StatusCode; } ... }