HttpWebRequest.GetResponse() throws “Bad Request” 400 error

Question!

Following is the sample code with (changed actual URL and credentials)

ServicePointManager.ServerCertificateValidationCallback += new RemoteCertificateValidationCallback((object s, X509Certificate certificate, X509Chain chain, SslPolicyErrors sslPolicyErrors) => { return true; }); 

var requestUri = new Uri("https://example.com/path1/path2?var=somevar");

byte[] data = Encoding.UTF8.GetBytes("DEV72*12/27/06*TAYLOR*RICH*JOE*10/28/56*U0999495102*466666666*01*TAYLOR*TAMMY*M*10/26/52***CIGNA HMO*62308*UPIN*MEDICAL CENTER**MESSAGE*M*F*30");
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(requestUri);
request.PreAuthenticate = true;
request.UseDefaultCredentials = false;
request.Credentials = new NetworkCredential("UUUSSSEEERR", "PASSWORD");
request.ContentLength = data.Length;
request.ContentType = "text/plain";
request.Method = "POST";

using (Stream stream = request.GetRequestStream())
{
   stream.Write(data, 0, data.Length);
   stream.Flush();
}

StreamReader streamReader = null;

string result;
try
{
   streamReader = new StreamReader(request.GetResponse().GetResponseStream());
   result = streamReader.ReadToEnd();
}
finally
{
   streamReader.Close();
}

txtOutput.Text = result;

It always throws bad Request exception on first run but when I move back the cursor in debugger to first line it works fine and gives the proper response in txtOutput.text and same behaviour in detached application, first time it throws exception but second time it works fine, can some one give me some work around or let me know what wrong i am doing here. using .net 4.0.

Update:

for example following code is working for me but this is not the work around i am looking for i just added a while loop by catching WebException and if its statusCode is 400 i reloop the the code and it works

var requestUri = new Uri("https://example.com/path1/path2?var=somevar");

ServicePointManager.ServerCertificateValidationCallback += new RemoteCertificateValidationCallback((object s, X509Certificate certificate, X509Chain chain, SslPolicyErrors sslPolicyErrors) => { return true; }); 

byte[] data = Encoding.UTF8.GetBytes("DEV72*12/27/06*TAYLOR*RICH*JOE*10/28/56*U0999495102*466666666*01*TAYLOR*TAMMY*M*10/26/52***CIGNA HMO*62308*UPIN*MEDICAL CENTER**MESSAGE*M*F*30");
HttpWebRequest request = null;  
int counter = 0;
do
{
    request = (HttpWebRequest)WebRequest.Create(requestUri);

    request.PreAuthenticate = true;
    request.UseDefaultCredentials = false;
    request.Credentials = new NetworkCredential("USERNAME", "password");
    request.ContentLength = data.Length;
    request.ContentType = "text/plain";
    request.Method = "POST";

    using (Stream stream = request.GetRequestStream())
    {
        stream.Write(data, 0, data.Length);
        stream.Flush();
    }

    StreamReader streamReader = null;

    string result = string.Empty;
    try
    {
        streamReader = new StreamReader(request.GetResponse().GetResponseStream());
        result = streamReader.ReadToEnd();
    }
    catch (WebException ex)
    {
        HttpWebResponse response = (HttpWebResponse)ex.Response;
        if (response.StatusCode == HttpStatusCode.BadRequest)
        {
            counter++;
        }
        else
        {
            txtOutput.Text = ex.ToString();
        }
    }
    finally
    {
        if(streamReader != null) streamReader.Close();
    }

    txtOutput.Text = result;

} while (counter == 1);


Answers

A stream.Close(); after stream.Flush(); might probably help

By : fan711


This video can help you solving your question :)
By: admin