Ajisha
Ajisha

Reputation: 47

How to send data from win forms to web using Json?

I cannot pass value properly. This code executed successfully but the null value reached to the specified page("http://.............).

Product objProduct = new Product();
objProduct.id = "1";
objProduct.name = "Sana";
string json = JsonConvert.SerializeObject(objProduct);

var baseAddress = "http://..................";

var http = (HttpWebRequest)WebRequest.Create(new Uri(baseAddress));
http.Accept = "application/json";
http.ContentType = "application/json";
http.Method = "POST";

string parsedContent = json;
ASCIIEncoding encoding = new ASCIIEncoding();
Byte[] bytes = encoding.GetBytes(parsedContent);

Stream newStream = http.GetRequestStream();
newStream.Write(bytes, 0, bytes.Length);
newStream.Close();

var response = http.GetResponse();

var stream = response.GetResponseStream();
var sr = new StreamReader(stream);
var content = sr.ReadToEnd();

Upvotes: 0

Views: 1454

Answers (2)

Muhammed Albarmavi
Muhammed Albarmavi

Reputation: 24434

Another simple solution that I use to make request is WebClient and your code can be like this

  Product objProduct = new Product();
  objProduct.id = "1";
  objProduct.name = "Sana";
  string json = JsonConvert.SerializeObject(objProduct);
  var baseAddress = "http://..................";

  var respond = "";

  //Post request 
  using (WebClient wc = new WebClient())
  {
    wc.Encoding = Encoding.UTF8;
    respond =  wc.UploadString(baseAddress, json);
  }

the respond variable here will have the result of API return

Upvotes: 0

jjchiw
jjchiw

Reputation: 4445

Can you use Microsoft.Net.Http

using (var client = new HttpClient()) 
{
    var objProduct = new Product();
    objProduct.id = "1";
    objProduct.name = "Sana";
    string json = JsonConvert.SerializeObject(objProduct);
    var content = new StringContent(json);
    var result = await client.PostAsync("http://localhost/product/", content);
    var responseAsString = await result.Content.ReadAsStringAsync();
}

Upvotes: 1

Related Questions