Click here to Skip to main content
15,662,459 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
we have received bellow error
The underlying connection was closed: An unexpected error occurred on a receive.

What I have tried:

var request = (HttpWebRequest)WebRequest.Create(EndPoint);

request.Method = Method;
request.ContentLength = 0;
request.ContentType = contentType;
request.Timeout = 600000;
request.KeepAlive = false;

request.UseDefaultCredentials = true;
request.Proxy.Credentials = System.Net.CredentialCache.DefaultCredentials;
request.Method = WebRequestMethods.Http.Post.ToString();
request.Credentials = new NetworkCredential(username, password);

if (Method == "POST")
    object input = new
        firstName = "a",
        LastName = "b",

    string inputJson = (new JavaScriptSerializer()).Serialize(input);
    byte[] bytes = System.Text.Encoding.ASCII.GetBytes(inputJson);
    request.ContentLength = bytes.Length;
    System.IO.Stream os = request.GetRequestStream();
    os.Write(bytes, 0, bytes.Length);
using (var response = (HttpWebResponse)request.GetResponse())// request.address changes at this line on "POST" method types
    var responseValue = string.Empty;

    if (response.StatusCode != HttpStatusCode.OK)
        var message = String.Format("Request failed. Received HTTP {0}", response.StatusCode);
        throw new ApplicationException(message);

    // grab the response
    using (var responseStream = response.GetResponseStream())
        if (responseStream != null)
            using (var reader = new StreamReader(responseStream))
                responseValue = reader.ReadToEnd();

    return responseValue;
Updated 6-Jan-19 23:56pm

1 solution

Here is a good article that shows some ways to do it:[^]
Personally I found the HttpClient way too tricky and would not recommend it.
Share this answer
RAJ PERVI 7-Jan-19 6:50am    

We have got the solution. but if we remove mandatory fields it become bad request.

any solution for this.
RickZeeland 7-Jan-19 6:53am    
Don't think so, you would have to change things on the server side so those fields are not mandatory anymore. But maybe you could try to send some dummy info instead ...
RAJ PERVI 7-Jan-19 6:55am    
Thank for your reply, but bill amount is mandatory and we can not passed as zero

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900