skip to content
Linkedin Twitter feed logo
22 March 2008

How to HTTP Post in .NET and handle the 500 errors

If you google you will find a lot of posts that will tell you how to HTTP post (some call it HTML post) in .NET. However, they all fail, or at least the ones I found, to tell you how to handle the returned 500 errors and retrieve the message behind it.

I have been posting to a service and getting the “500 Internal Server Error” which doesn’t tell much! I had done some research to get the real error behind it. Here is my code snippet in C#:

public static string Post(string url, string postData) {

byte[] buffer = Encoding.UTF8.GetBytes(postData);
int bufferLength = buffer.Length;
HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(url);
request.Method = "POST";
request.ContentLength = bufferLength;

string result;

using (Stream requestStream = request.GetRequestStream()) {
    requestStream.Write(buffer, 0, bufferLength);

    try {
        using (HttpWebResponse response = (HttpWebResponse)request.GetResponse()) {
            using (Stream responseStream = response.GetResponseStream()) {
                using (StreamReader readStream = 
                       new StreamReader(responseStream, Encoding.UTF8)) {
                    result = readStream.ReadToEnd();
                }
            }
        }
    }
    catch (WebException wEx) {
        using (Stream errorResponseStream = wEx.Response.GetResponseStream()) {
            using (StreamReader errorReadStream = 
                   new StreamReader(errorResponseStream, Encoding.UTF8)) {
                result = errorReadStream.ReadToEnd();
            }
        }
    }
}

return result;
}

I have tested the code and it is working, please let me know what do you think or if you have a better approach.

1Comment
leave your own
  • R97 March 4th, 2009

    Same thing for c++/.net :

    [code:c#]
    using System::Net::HttpWebRequest;
    using System::Net::WebRequest;
    using System::Net::HttpWebResponse;
    using System::Net::WebResponse;
    using System::IO::StreamReader;
    using System::Net::WebException;

    HttpWebResponse ^HttpWResponse;
    StreamReader ^sr, ^serr;

    try {
    HttpWebRequest ^ HttpWRequest = safe_cast(WebRequest::Create(url));

    HttpWResponse = safe_castHttpWRequest->GetResponse());
    sr = gcnew StreamReader(HttpWResponse->GetResponseStream());
    return sr->ReadToEnd();
    }
    catch (WebException ^ex) {
    serr = gcnew streamReader(ex->Response->GetResponseStream());
    //Reponse complete du serveur
    return serr->ReadToEnd();
    //return ex->Message;//Simple reponse d’erreur du serveur
    }
    finally {
    if (HttpWResponse != nullptr)
    HttpWResponse->Close();
    if (sr != nullptr)
    sr->Close();
    }

    }
    [/code]

    A+

Leave a Reply

Gravatar