Resolved How to send request body using HTTPWebrequest

Anonymous

Well-known member
Joined
Sep 29, 2020
Messages
94
Programming Experience
Beginner
Hello Finally i found a post api which sends and receives data in XML format.

My API has a request body -

C#:
<Person>
<Id>12345</Id>
<Customer>John Smith</Customer>
<Quantity>1</Quantity>
<Price>10.00</Price>
</Person>


I am confused as how I should I hit the api with this body from the code -

I have created a proxy class for this one -

C#:
    [System.SerializableAttribute()]
    [System.ComponentModel.DesignerCategoryAttribute("code")]
    [System.Xml.Serialization.XmlTypeAttribute(AnonymousType = true)]
    [System.Xml.Serialization.XmlRootAttribute(Namespace = "", IsNullable = false)]
    public partial class Person
    {

        private ushort idField;

        private string customerField;

        private byte quantityField;

        private decimal priceField;

        /// <remarks/>
        public ushort Id
        {
            get
            {
                return this.idField;
            }
            set
            {
                this.idField = value;
            }
        }

        /// <remarks/>
        public string Customer
        {
            get
            {
                return this.customerField;
            }
            set
            {
                this.customerField = value;
            }
        }

        /// <remarks/>
        public byte Quantity
        {
            get
            {
                return this.quantityField;
            }
            set
            {
                this.quantityField = value;
            }
        }

        /// <remarks/>
        public decimal Price
        {
            get
            {
                return this.priceField;
            }
            set
            {
                this.priceField = value;
            }
        }
    }

The is the code I am writing for hitting the API -

C#:
var request = (HttpWebRequest)WebRequest.Create("https://reqbin.com/sample/post/xml");



            Person person = new Person();

         

            Console.WriteLine("Enter ID");

            person.Id = Convert.ToUInt16(Console.ReadLine());



            Console.WriteLine("Enter Name");

            person.Customer = Console.ReadLine();



            Console.WriteLine("Enter Quantity");

            person.Quantity = Convert.ToByte(Console.ReadLine());



            Console.WriteLine("Enter Price");

            person.Price = Convert.ToDecimal(Console.ReadLine());



       

            var data = Encoding.ASCII.GetBytes(person); ----- I am not sure about this one.

How do I proceed ?
 
Last edited:
Serialize your Person object into an XML string. Send that string as the request body.

Why did you abandon the idea of using an HttpClient from your previous threads?
 
Serialize your Person object into an XML string. Send that string as the request body.

Why did you abandon the idea of using an HttpClient from your previous threads?
I want to learn both. I am first trying it with HttpWebRequest then I will try with HttpClient.

I serialized the object but now I am getting

C#:
System.Net.ProtocolViolationException:
You must provide a request body if you set ContentLength>0 or SendChunked==true.
Do this by calling [Begin]GetRequestStream before [Begin]GetResponse.

I did the following -

C#:
    // Serialize the person into an XML string
            var serializer = new XmlSerializer(typeof(Person));
            var sb = new StringBuilder();
            using (XmlWriter xmlWriter = XmlWriter.Create(sb))
            {
                serializer.Serialize(xmlWriter, person);
            }

            // Byte array data to send
            var data = Encoding.ASCII.GetBytes(sb.ToString());


            request.Method = "POST";
            request.ContentType = "application/xml";
            request.ContentLength = data.Length;

            var response = (HttpWebResponse)request.GetResponse();

            var responseString = new StreamReader(response.GetResponseStream()).ReadToEnd();

            Console.WriteLine(responseString);

            XmlSerializer deserializer = new XmlSerializer(typeof(Response));

            Response result = new Response();

            using (TextReader reader = new StringReader(responseString))
            {
                result = (Response)serializer.Deserialize(reader);
            }

            //Console.WriteLine(name);

            Console.WriteLine("Finally we received " + result.ResponseMessage);



            response.Close();
 
As it says, call GetRequestStream before GetResponse. Copy the post data to the the request stream.
 
You have to get the request stream and copy your post data to it.
 
The error was telling you exactly what you needed to do. If you checked the documentation for the GetRequestStream() method, it even has sample code.
Thanks it works now but I am getting a System.NotSupportedException for Length and Position. Its not that its stopping my application . My application is working but I saw it while debugging.

1603720653518.png
 
Yes, that is normal for some of the debugging visualizers. Some streams are write only, and so some properties are not supported for such streams.
 
Back
Top Bottom