AdafruitHTTP helps make working with HTTP requests easier, including HTTPS based servers with TLS certificates.  

It includes convenient callbacks for incoming data, as well as helper functions to deal with HTTP response headers, response codes, and other HTTP specific details.

AdafruitHTTP API

The AdafruitHTTP class has the following public functions:

bool addHeader    ( const char* name, const char* value );
bool clearHeaders ( void );

bool get          ( char const *url );
bool get          ( char const * host, char const *url );

bool post         ( char const *url, char const* encoded_data );
bool post         ( char const * host, char const *url, char const* encoded_data );

HTTP Headers

The follow functions are provided as helpers working with 'header' entries in your HTTP requests.

bool addHeader (const char* name, const char* value)

Adds a new header name/value pair to the HTTP request.

Parameters:

  • name: A null-terminated string representing the 'name' in the header name/value pair.
  • value: A null-terminated string representing the 'value' in the name/value pair.

Returns: 'True' (1) if the header was successfully added, otherwise 'false' (0).

Up to ten (10) header name/value pairs can be inserted into your HTTP request.
// Setup the HTTP request with any required header entries
http.addHeader("User-Agent", "curl/7.45.0"); // Simulate curl
http.addHeader("Accept",     "text/html");
http.addHeader("Connection", "keep-alive");

bool clearHeaders (void)

Clears all user-defined headers in the pending HTTP request.

Parameters: None

Returns: 'True' (1) if the headers were successfully cleared, otherwise 'false' (0).

HTTP GET Requests

The following functions enable you to send HTTP GET requests to an HTTP server:

bool get (char const* url)

This is a shortcut for the function below and uses the 'host' specified in .connect instead of re-entering it in the get request.  See below for details.

This shortcut function will only work if you used .connect with a domain name. It will return an error if you used .connect with an IP address. Please use the full .get() function below when connecting via an IP address.

bool get (char const* host, char const* url)

Sends a GET request to the specified host and url.

Parameters:

  • host: A null-terminated string containing the host name for the HTTP server (ex. "www.adafruit.com"). This is normally the same as the host used in .connect, but you can also access other host names that resolve to the same domain or IP such as "learn.adafruit.com" or "io.adafruit.com".
  • url: The path for the HTTP request (ex. "/home/about.html")

Returns: 'True' (1) if the request was successful, otherwise 'false' (0).

// Connect to the HTTP server
http.connect("www.adafruit.com", 80);

// Add the required HTTP header name/value pairs
http.addHeader("User-Agent", "curl/7.45.0"); // Simulate curl
http.addHeader("Accept",     "text/html");
http.addHeader("Connection", "keep-alive");

// Send the HTTP GET request
http.get("wifitest.adafruit.com", "/testwifi/index.html");

HTTP POST Requests

HTTP POST requests allow you to submit data to the HTTP server via optional encoded arguments in the URL.

The following functions help you work with POST requests:

bool post (char const* url, char const* encoded_data)

This is a shortcut for the function below and uses the 'host' specified in .connect instead of re-entering it in the post request.  See below for details.

This shortcut function will only work if you used .connect with a domain name. It will return an error if you used .connect with an IP address. Please use the full .post() function below when connecting via an IP address.

bool post (char const* host, char const* url, char const* encoded_data)

Sends a POST request to the HTTP server at 'host'.

Parameters:

  • host: A null-terminated string containing the host name for the HTTP server (ex. "www.adafruit.com"). This is normally the same as the host used in .connect, but you can also access other host names that resolve to the same domain or IP such as "learn.adafruit.com" or "io.adafruit.com".
  • url: The path for the HTTP post, minus the encoded arguments ("ex. "/testwifi/testpost.php"
  • encoded_data: The encoded data to send in the post request (minus the '?' characters, ex.: "name=feather&email=feather%40adafruit.com").
Note the "%40" for the '@' symbol in encoded_data above. All non alpha-numeric characters must be encoded before being transmitted.

Returns: 'True' (1) if the post succeeded, otherwise 'false' (0).

// Connect to the HTTP server
http.connect("www.adafruit.com", 80);

// Add the required HTTP header name/value pairs
http.addHeader("User-Agent", "curl/7.45.0"); // Simulate curl
http.addHeader("Accept",     "text/html");
http.addHeader("Connection", "keep-alive");

// Send the HTTP POST request
http.post("wifitest.adafruit.com",
          "/testwifi/testpost.php",
          "name=feather&email=feather%40adafruit.com");

HTTP GET Example

The following example shows a simple GET request using callbacks to handle the response from the HTTP server:

/*********************************************************************
 This is an example for our WICED Feather WIFI modules

 Pick one up today in the adafruit shop!

 Adafruit invests time and resources providing this open source code,
 please support Adafruit and open-source hardware by purchasing
 products from Adafruit!

 MIT license, check LICENSE for more information
 All text above, and the splash screen below must be included in
 any redistribution
*********************************************************************/

#include <adafruit_feather.h>
#include <adafruit_http.h>

#define WLAN_SSID            "yourSSID"
#define WLAN_PASS            "yourPassword"

#define SERVER               "wifitest.adafruit.com"     // The TCP server to connect to
#define PAGE                 "/testwifi/index.html" // The HTTP resource to request
#define PORT                 80                     // The TCP port to use

// Some servers such as Facebook check the user_agent header to
// return data accordingly. Setting 'curl' mimics a command line browser.
// For a list of popular user agents see: http://www.useragentstring.com/pages/useragentstring.php
#define USER_AGENT_HEADER    "curl/7.45.0"

int ledPin = PA15;

// Use the HTTP class
AdafruitHTTP http;

/**************************************************************************/
/*!
    @brief  TCP/HTTP received callback
*/
/**************************************************************************/
void receive_callback(void)
{
  // If there are incoming bytes available
  // from the server, read then print them:
  while ( http.available() )
  {
    int c = http.read();
    Serial.write( (isprint(c) || iscntrl(c)) ? ((char)c) : '.');
  }
}

/**************************************************************************/
/*!
    @brief  TCP/HTTP disconnect callback
*/
/**************************************************************************/
void disconnect_callback(void)
{
  Serial.println();
  Serial.println("---------------------");
  Serial.println("DISCONNECTED CALLBACK");
  Serial.println("---------------------");
  Serial.println();

  http.stop();
}

/**************************************************************************/
/*!
    @brief  The setup function runs once when the board comes out of reset
*/
/**************************************************************************/
void setup()
{
  Serial.begin(115200);

  // Wait for the USB serial to connect. Needed for native USB port only.
  while (!Serial) delay(1);

  Serial.println("HTTP Get Example (Callback Based)\r\n");

  // Print all software versions
  Feather.printVersions();

  // Try to connect to an AP
  while ( !connectAP() )
  {
    delay(500); // delay between each attempt
  }

  // Connected: Print network info
  Feather.printNetwork();

  // Tell the HTTP client to auto print error codes and halt on errors
  http.err_actions(true, true);

  // Set the callback handlers
  http.setReceivedCallback(receive_callback);
  http.setDisconnectCallback(disconnect_callback);

  // Connect to the HTTP server
  Serial.printf("Connecting to %s port %d ... ", SERVER, PORT);
  http.connect(SERVER, PORT); // Will halt if an error occurs
  Serial.println("OK");

  // Setup the HTTP request with any required header entries
  http.addHeader("User-Agent", USER_AGENT_HEADER);
  http.addHeader("Accept", "text/html");
  http.addHeader("Connection", "keep-alive");

  // Send the HTTP request
  Serial.printf("Requesting '%s' ... ", PAGE);
  http.get(SERVER, PAGE); // Will halt if an error occurs
  Serial.println("OK");
}

/**************************************************************************/
/*!
    @brief  The loop function runs over and over again
*/
/**************************************************************************/
void loop()
{
  togglePin(ledPin);
  delay(250);
}

/**************************************************************************/
/*!
    @brief  Connect to the defined access point (AP)
*/
/**************************************************************************/
bool connectAP(void)
{
  // Attempt to connect to an AP
  Serial.print("Attempting to connect to: ");
  Serial.println(WLAN_SSID);

  if ( Feather.connect(WLAN_SSID, WLAN_PASS) )
  {
    Serial.println("Connected!");
  }
  else
  {
    Serial.printf("Failed! %s (%d)", Feather.errstr(), Feather.errno());
    Serial.println();
  }
  Serial.println();

  return Feather.connected();
}

This guide was first published on Mar 23, 2016. It was last updated on Mar 23, 2016.

This page (AdafruitHTTP) was last updated on Feb 11, 2016.

Text editor powered by tinymce.