1

This is my first attempt to consume a rest webservice.

In this R WS I need to create a header and send values in json. Below is the code I am using.

var password = tb_Authorization.Text;
var user = tb_AppCaller.Text;

string wrURL = tb_URL.Text;

WebRequest req = WebRequest.Create(tb_URL.Text);
req.Method = "POST";
req.ContentType = "application/json";

req.Headers["Authorization"] = tb_Authorization.Text;
req.Headers["AppCaller"] = tb_AppCaller.Text;

I need to send a json like the following to obtain a response:

{ "lastName": "Jordan", "firstName": "Michael"} 

to obtain:

{ 
  "NumCountry": 1,
  "Country": [
    {
      "Name": "USA",
      "rank": 1
    }
  ]
}

In this last part my brain froze and I can't do the "next step". My basic question is how so I send json in header?

Vivek Nuna
  • 25,472
  • 25
  • 109
  • 197
Unow
  • 33
  • 1
  • 5

1 Answers1

2

You have to use StreamWriter and StreamReader.

var httpWebRequest = (HttpWebRequest)WebRequest.Create(tb_URL.Text);
httpWebRequest.ContentType = "application/json";
httpWebRequest.Method = "POST";

using (var streamWriter = new StreamWriter(httpWebRequest.GetRequestStream()))
{
    string json = "{\"lastName\": \"Jordan\", \"firstName\": \"Michael\"}";

    streamWriter.Write(json);
    streamWriter.Flush();
    streamWriter.Close();
}

var httpResponse = (HttpWebResponse)httpWebRequest.GetResponse();
using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
{
    var result = streamReader.ReadToEnd();
}
Vivek Nuna
  • 25,472
  • 25
  • 109
  • 197