HttpWebRequest Post Method sending partial Data

10,307

Solution 1

This worked for me, i think you miss the Encoding... using this i'm sending huge xml to server

        HttpWebRequest request = (HttpWebRequest)WebRequest.Create(connectionString);
        request.ContentType = "application/x-www-form-urlencoded";
        request.Method = "POST";
        byte[] byteArray = Encoding.UTF8.GetBytes(postData);
        // Set the ContentType property of the WebRequest.
        // 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();
        WebResponse response = request.GetResponse();
        //Console.WriteLine("Service Status Code:"+((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();

Solution 2

The way I've been doing it is only slightly different than your way:

HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(URL);
request.Method = WebRequestMethods.Http.Post;
request.ContentLength = DataToPost.Length;
request.ContentType = "application/x-www-form-urlencoded";
StreamWriter writer = new StreamWriter(request.GetRequestStream());
writer.Write(DataToPost);
writer.Close();
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
StreamReader reader = new StreamReader(response.GetResponseStream());

This way has been working for years.

Share:
10,307
Prem Singh
Author by

Prem Singh

Updated on June 04, 2022

Comments

  • Prem Singh
    Prem Singh almost 2 years

    I have the following code to send a POST request to Server.

    HttpWebRequest myWebRequest = (HttpWebRequest)HttpWebRequest.Create(uri);
    myWebRequest.Method = WebRequestMethods.Http.Post;
    myWebRequest.ContentLength = data.Length;
    myWebRequest.ContentType = "application/x-www-form-urlencoded";
    StreamWriter writer = new StreamWriter(myWebRequest.GetRequestStream());
    writer.Write(data);
    writer.Close();
    

    The data to be posted is an XML request with nearly 2000 Characters. I read the response as shown below.

    this.Response.ContentType = "text/xml";
    StreamReader reader = new StreamReader(this.Request.InputStream);
    string responseData = reader.ReadToEnd();
    

    The response data that we are obtaining above has only a portion of the actual data send.

    Please help me to get the full data.