katit
katit

Reputation: 17905

Get proper response from http call, not exception

Here is code I use to POST into RESTful web service. My problem is with a last line. For example, my server can reply with different messages and same code. Now, unless I get 200 OK I just get exception on last line.

I'd like to have better access to response header, etc no matter what code I got. How is that possible?

var request = WebRequest.Create(Options.DitatServerUri + Options.DitatAccountId + "/integration/trip") as HttpWebRequest;
            if (request == null) return false;

            request.ContentType = "application/json";
            request.Headers.Add(HttpRequestHeader.Authorization, "Basic " + Convert.ToBase64String(Encoding.UTF8.GetBytes(Options.DitatLoginName + ":" + Options.DitatPassword)));
            request.Method = "POST";

            var serializer = new JavaScriptSerializer();

            var serializedData = serializer.Serialize(trip);

            var bytes = Encoding.UTF8.GetBytes(serializedData);

            request.ContentLength = bytes.Length;
            var os = request.GetRequestStream();
            os.Write(bytes, 0, bytes.Length);
            os.Close();

            var response = request.GetResponse();

Example: I get WebException "Invalid Operation" but server actually send message with error explanation.

Upvotes: 1

Views: 1722

Answers (2)

Adam Mihalcin
Adam Mihalcin

Reputation: 14458

Building on what Jon said above in the comments, the exception thrown for a bad status code is most likely a WebException, which has Response and Status properties, as per this MSDN page. Therefore, you can get the response via:

WebResponse response = null;
try
{
    response = request.GetResponse();
}
catch (WebException ex)
{
    response = ex.Response;
}

Upvotes: 1

Daniel Mann
Daniel Mann

Reputation: 58980

Why not catch the exception and handle it appropriately?

try 
{
    var response = request.GetResponse(); 
}
catch (WebException webEx) 
{
    Console.WriteLine("Error: {0}", ((HttpWebResponse)webEx.Response).StatusDescription);
}

Upvotes: 1

Related Questions