Building an HTTP Client for Internet of Things in C

So, you’ve got a shiny new arduino or cc3200 or atmel wifi board and now you’re wondering how to get your sensor data into the cloud using an HTTP POST packet?

You’re going to need 3 string buffers, One to hold your Sensor data (in POST format), one to hold the length of that buffer (in ASCII), and an arbitrarily large buffer to hold the entire outgoing HTTP packet.  we’ll initialize them as follows:

unsigned char seBuffer[512];  //Holds the full POST packet
unsigned char sBuffer[384];   //Holds out Sensor data in POST format
unsigned char sBufferLen[8];  //Holds the Sizeof sBuffer

Why did I use those buffer names?  no idea.  I just did.  Call them whatever you want.

Now that we have our buffers, we need to get our sensor data into them.  For that, we’ll use sprintf(), which does more or less the same thing the printf() does, but points the output to a string buffer.  The first buffer we’ll fill holds our sensor data:

sprintf((char *)sBuffer, "command=%d&deviceid=%s&devicetype=%s&temperature=%d",

Seems nice and easy, right?  Next, we’ll get the string length of that buffer and store it in ASCII format, we’ll need it later:

sprintf((char *)sBufferLen, "%2d", (unsigned)strlen((char *)sBuffer));

Lastly, we piece it all together into a final assembled post packet in our largest buffer:

sprintf((char*) seBuffer, "POST %s HTTP/1.1\r\nHost: %s\r\n"
   "User-Agent: MyDeviceAgent/1.0\r\n"
   "Connection: close\r\n"
   "Content-Length: %s\r\n"
   "Content-Type: application/x-www-form-urlencoded\r\n\r\n"
   "%s\r\n\r\n", webappurl,servername,sBufferLen,sBuffer);

Now, load the entirety of seBuffer into your outgoing TCP socket.  The full Packet looks like this:

POST /sensorheartbeat.html HTTP/1.1\r\nHost:\r\n
User-Agent: MyDeviceAgent/1.0\r\n
Connection: close\r\n
Content-Length: 59\r\n
Content-Type: application/x-www-form-urlencoded\r\n\r\n

Don’t forget to read back your values from the web server you’re hitting, that’s important information to let you know if your POST was successful.