Skip to main content

HTTP/HTTPS

HTTP (HyperText Transfer Protocol) is the standard way to talk to web servers. TinyCLR provides both client and server implementations built on top of the Networking Core stack, plus HTTPS via the built-in TLS 1.2 support.

NuGet packages: GHIElectronics.TinyCLR.Devices.Network for the network controller, and GHIElectronics.TinyCLR.Networking.Http for HttpWebRequest and HttpListener.

HTTP client

The example below connects to bing.com and reads robots.txt. An active network connection (Ethernet, WiFi, cellular) must be up before the request runs.

using System;
using System.Diagnostics;
using System.Net;
using System.Text;

var url = "http://www.bing.com/robots.txt";

int read = 0;
int total = 0;
byte[] result = new byte[512];

try{
using (var req = HttpWebRequest.Create(url) as HttpWebRequest){
req.KeepAlive = false;
req.ReadWriteTimeout = 2000;

using (var res = req.GetResponse() as HttpWebResponse)
using (var stream = res.GetResponseStream()){
do{
read = stream.Read(result, 0, result.Length);
total += read;

Debug.WriteLine("read: " + read + ", total: " + total);

var page = new string(Encoding.UTF8.GetChars(result, 0, read));
Debug.WriteLine("Response: " + page);
} while (read != 0);
}
}
}
catch (Exception ex){
Debug.WriteLine("HTTP request failed: " + ex.Message);
}

HTTP server

TinyCLR provides an HttpListener class for hosting an HTTP server on the device. The example below listens on port 80, increments a counter for every request, and returns a small HTML page.

note

The client device (phone, PC, etc.) must be on the same local network as the SITCore to reach the server by its local IP address.

using System.Diagnostics;
using System.Net;
using System.Text;

var listener = new HttpListener("http", 80);
listener.Start();
Debug.WriteLine("Listening...");

var clientRequestCount = 0;

while (true){
// GetContext blocks until a request arrives.
var context = listener.GetContext();
var response = context.Response;

var responseString = "<html><body>I am TinyCLR Server. Client request count: " + (++clientRequestCount) + "</body></html>";
var buffer = Encoding.UTF8.GetBytes(responseString);

response.ContentLength64 = buffer.Length;

var output = response.OutputStream;
output.Write(buffer, 0, buffer.Length);
output.Close(); // Always close the output stream.
}

Point a browser on the same network at the device's IP — for example, http://192.168.1.6/:

Server response in a web browser

HTTPS

HTTPS works the same way as HTTP — just use an https:// URL. The transport is handled by the built-in TLS 1.2 implementation, no additional client code required.

var url = "https://www.bing.com/robots.txt";
// ... same HttpWebRequest code as the HTTP client example above.

HTTPS is also the underlying transport used by the cloud SDKs — see Azure and AWS for higher-level integrations.

API reference

NamespaceDescription
GHIElectronics.TinyCLR.Networking.HttpHTTP/HTTPS client classes