Tuesday, April 24, 2012

Unable to read data from transport connection. The connection was closed


public static string SendHTTP( string webRequest)
        {
            try
            {
                string strPostData = "";

                // Create a request using a URL that can receive a post.
                HttpWebRequest request = (HttpWebRequest)WebRequest.Create(webRequest);
                // Set the Method property of the request to POST.
                request.Method = "POST";

                //request.Credentials = System.Net.CredentialCache.DefaultNetworkCredentials;
               // request.KeepAlive = false;
                request.ProtocolVersion = HttpVersion.Version10;


                // Create POST data and convert it to a byte array.
                string postData = strPostData;
                byte[] byteArray = Encoding.UTF8.GetBytes(postData);
                // Set the ContentType property of the WebRequest.
                request.ContentType = "text/xml";
                // Set the ContentLength property of the WebRequest.
                request.ContentLength = byteArray.Length;
                // Get the request stream.
                Stream dataStream = request.GetRequestStream();
                // Write the data to the request stream.
                dataStream.Write(byteArray, 0, byteArray.Length);
                // Close the Stream object.
                dataStream.Close();
                // Get the response.
                WebResponse response = request.GetResponse();
                // Display the status.
                Console.WriteLine(((HttpWebResponse)response).StatusDescription);
                // Get the stream containing content returned by the server.
                dataStream = response.GetResponseStream();
                // Open the stream using a StreamReader for easy access.
                StreamReader reader = new StreamReader(dataStream);
                // Read the content.
                string responseFromServer = reader.ReadToEnd();

                // Clean up the streams.
                reader.Close();
                dataStream.Close();
                response.Close();
                // Display the content.
                return responseFromServer;

            }
            catch (System.Exception ex)
            {
                MessageBox.Show(ex.Message);
                return null;
            }

        }

No comments:

Post a Comment