Building Arduino Projects for the Internet of Things

(Steven Felgate) #1

CHAPTER 3 ■ COMMUNICATION PROTOCOLS


else
{
Serial.println("[ERROR] Connection Failed");
}


Serial.println("-----------------------------------------------");
}


This code is for sending an HTTP GET request, but as mentioned earlier, it has a
length limitation, so if you want to avoid this limitation then use HTTP POST instead.
The doHttpPost () function provided in Listing 3-3 encapsulates all the details of
preparing request for the POST method, connecting to the server, and sending the request.
Attempt to connect to the server using client.connect(server, port) in an
IF condition. So far, the code is similar to the HTTP GET request. If the connection is
successful, then prepare the request.
In a request that uses the POST method, data is also sent in name/value pair format,
but it is part of the request. As you can see in Listing 3-3 , sending an HTTP POST request
requires additional header information.
Finally, transmit the HTTP request to the server using the client.println()
method. This method will send the commands to the server over the network and then
receive any response from the server.


Listing 3-3. HTTP POST Request


void doHttpPost()
{
// Prepare data or parameters that need to be posted to server
String requestData = "requestData={\"requestVar:test\"}";


// Check if a connection to server:port was made
if (client.connect(server, port))
{
Serial.println("[INFO] Server Connected - HTTP POST Started");


// Make HTTP POST request
client.println("POST /post HTTP/1.1");
client.println("Host: " + String(server));
client.println("User-Agent: Arduino/1.0");
client.println("Connection: close");
client.println("Content-Type: application/x-www-form-urlencoded;");
client.print("Content-Length: ");
client.println(requestData.length());
client.println();
client.println(requestData);


Serial.println("[INFO] HTTP POST Completed");
}

Free download pdf