C# Post JSON to HTTP

Basically, in this example we are going to post a Name,Surname,Phone and Email data in JSON form. Then we will get our data as response and deserialize to object from JSON. Finally we will print name value which we send first.

Firstly, we need to install Newtonsoft.Json package using nuget. Follow instructions on https://www.newtonsoft.com/json In this example i am going to use Person Class to serialize our object.

#Person.cs    
public class Person
    {
        public Person()
        {
        }
        public string name { get; set; }
        public string surname { get; set; }
        public string phone { get; set; }
        public string email { get; set;}     
    }

We are sending our JSON to http page then we are getting response and printing name value in it.

  System.Net.WebRequest request = System.Net.WebRequest.Create("http://YOUR_URL/your_page.php");
            request.Method = "POST";
            Person person = new Person();
            person.name = "John";
            person.surname = "Doe";
            person.phone = "+1234567";
            person.email = "[email protected]";
            String myjson = "data=" +
 //Serializing object
 Newtonsoft.Json.JsonConvert.SerializeObject(person);

            byte[] byteArray = Encoding.UTF8.GetBytes(myjson);
            request.ContentType = "application/x-www-form-urlencoded";
            request.ContentLength = byteArray.Length;
            System.IO.Stream dataStream = request.GetRequestStream();          
            dataStream.Write(byteArray, 0, byteArray.Length);
            dataStream.Close();
            System.Net.WebResponse response = request.GetResponse(); 
            Console.WriteLine(((System.Net.HttpWebResponse)response).StatusDescription);

            using (dataStream = response.GetResponseStream())
            { 
                System.IO.StreamReader reader = new System.IO.StreamReader(dataStream);
                string responseFromServer = reader.ReadToEnd();
//Deserializing Response
                Person p = Newtonsoft.Json.JsonConvert.DeserializeObject< Person>(responseFromServer);
                Console.WriteLine(p.name);
            }

            response.Close();

Just a page to receive our data and serve it back as response.

//your_page.php

<?php

echo $_POST['data'];

PHP PDO CRUD Example

Connecting to database

<?php

try {
$dbh = new PDO("mysql:host=localhost;dbname=DATABASE_NAME", "DATABASE_USER","DATABASE_PASSWORD");
}
catch (PDOException $e) {
    print "Error!: " . $e->getMessage() . "<br/>";
    die();
}

$dbh = null;

Create

$sth = $dbh->prepare("INSERT INTO fruits (name,colour) VALUES (?,?)");

$sth->bindParam(1, "Apple", PDO::PARAM_STR);
$sth->bindParam(2, "red", PDO::PARAM_STR);

$sth->execute();

// OR

$sth = $dbh->prepare("INSERT INTO fruits (name,colour) VALUES (:name,:colour)");

$sth->bindParam(":name", "Apple", PDO::PARAM_STR);
$sth->bindParam(":colour", "red", PDO::PARAM_STR);

$sth->execute();

Read

 $sth = $dbh->prepare("SELECT name FROM fruits WHERE colour=:colour");
 $sth->bindParam(":colour", "red", PDO::PARAM_STR);
 $sth->execute();
 foreach ($sth->fetchAll() as $row) {
 echo $row['name'];             
 }

Update

 $sth = $dbh->prepare("UPDATE fruits SET colour=:colour WHERE name=:name");
 $sth->bindParam(":colour", "green", PDO::PARAM_STR);
 $sth->bindParam(":name", "kiwi", PDO::PARAM_STR);
 $sth->execute();

Delete

 $sth = $dbh->prepare("DELETE FROM fruits WHERE colour = :colour");
 $sth->bindParam(":colour", "green", PDO::PARAM_STR);
 $sth->execute();

Posting to HTTP with C#

First, create a WinForms application in Visual Studio.

Add 4 labels, 4 textBox and 1 button as seen above.

Click on button and write the code below. Change YOUR_URL and your_page. This code block will post our params same as HTML forms.

private void button1_Click(object sender, EventArgs e)
        {
            //Request
            System.Net.WebRequest request = System.Net.WebRequest.Create("http://YOUR_URL/your_page.php");
            request.Method = "POST";
            string postData = "name=" + textBox1.Text + "&surname=" + textBox2.Text + "&phone=" + textBox3.Text + "&email=" + textBox4.Text;
            byte[] byteArray = Encoding.UTF8.GetBytes(postData);
            request.ContentType = "application/x-www-form-urlencoded";
            request.ContentLength = byteArray.Length;
            System.IO.Stream dataStream = request.GetRequestStream();          
            dataStream.Write(byteArray, 0, byteArray.Length);
            dataStream.Close();  
            
            //Response            
            System.Net.WebResponse response = request.GetResponse();
            Console.WriteLine(((System.Net.HttpWebResponse)response).StatusDescription);
            using (dataStream = response.GetResponseStream())
            {
                System.IO.StreamReader reader = new System.IO.StreamReader(dataStream);  
                string responseFromServer = reader.ReadToEnd();
                MessageBox.Show(responseFromServer);
            }
            response.Close();
        }

Here is our your_page.php

<?php
header("Access-Control-Allow-Origin: *");

try {
    $dbh = new PDO("mysql:host=localhost;dbname=DB_NAME", "DB_USERNAME", "DB_PASSWORD");
} catch (PDOException $e) {
    print "Error!: " . $e->getMessage() . "<br/>";
    die();
}

$time = time();
$name = $_POST['name'];
$surname = $_POST['surname'];
$phone = $_POST['phone'];
$email = $_POST['email'];

$sth = $dbh->prepare("INSERT INTO patients (time, name, surname, phone, email) VALUES (?,?,?,?,?)");

$sth->bindParam(1, $time, PDO::PARAM_INT);
$sth->bindParam(2, $name, PDO::PARAM_STR);
$sth->bindParam(3, $surname, PDO::PARAM_STR);
$sth->bindParam(4, $phone, PDO::PARAM_STR);
$sth->bindParam(5, $email, PDO::PARAM_STR);

$create = $sth->execute();

echo "Person recorded.";

You will see response from your_page.php when you submit your form from our C# application.

HTTP Server/Client in Dart Language

Serves “A Basic HTTP Server” text response on http://127.0.0.1:2222

import 'dart:io';

main() {
  HttpServer
      .bind("127.0.0.1", 2222)
      .then((server) {
        server.listen((HttpRequest request) {
          request.response.write('A Basic HTTP Server');
          request.response.close();
        });
      });
}

Client

import 'dart:io';
import 'dart:convert';

main() {
new HttpClient().get('127.0.0.1', 2222, '/')
     .then((HttpClientRequest request) => request.close())
     .then((HttpClientResponse response) {
       response.transform(utf8.decoder).listen((contents) {
         print(contents);
       });
     });
}

Your first program in Dart Language

We are using chocolatey in Windows.

choco install dart-sdk

Reopen the cmd and install stagehand.

pub global activate stagehand

Let’s create our first program.

mkdir MyFirstApp
cd MyFirstApp

Creating a template…

stagehand console-full

Fetching dependencies…

pub get

Running app…

dart bin/main.dart

This example template also using a sample library within lib folder. You may change it’s content to affect calculate() function’s result. Such as…

int calculate() {
  return 10 * 2;
}