Sarotobi
Sarotobi

Reputation: 831

Getting a reponse from a web api in JSON format

I am new with web service and API's and trying to get a response from a URL with a post method and passing a parameter to it. I am developing a C# winform application that sending request to this api and must return the output in JSON format. Below is my code so war i only getting an OK response instead of the actual JSON data.

private void button1_Click(object sender, EventArgs e)
        {
            string postData = "station=sub";
            byte[] byteArray = Encoding.UTF8.GetBytes(postData);



            Uri target = new Uri("http://apijsondata/tz_api/");
            WebRequest myReq = WebRequest.Create(target);

            myReq.Method = "POST";
            myReq.ContentType = "application/x-www-form-urlencoded";
            myReq.ContentLength = byteArray.Length;

            using (var dataStream = myReq.GetRequestStream())
            {
                dataStream.Write(byteArray, 0, byteArray.Length);
            }

            using (var response = (HttpWebResponse)myReq.GetResponse())
            {
                //Do what you need to do with the response.
                MessageBox.Show(response.ToString());
            }


        }

Upvotes: 0

Views: 40

Answers (1)

Anu Viswan
Anu Viswan

Reputation: 18153

You should use a StreamReader together with HttpWebResponse.GetResponseStream()

For example,

 var reader = new StreamReader(response.GetResponseStream());
 var json = reader.ReadToEnd();

Upvotes: 1

Related Questions