HTTP GET and POST with an Arduino UNO and an ENC28J60

This is purely for nostalgia’s sake: An HTTP GET request for an Arduino UNO with an ENC28J60.

#include <UIPEthernet.h>

EthernetClient client;
uint8_t mac[6] = {0x00,0x01,0x02,0x03,0x04,0x05};

void setup() {
  Serial.begin(9600);
  char server[] = "www.someserver.com";
  if(Ethernet.begin(mac) == 0){
    Serial.println("Failed to configure Ethernet using DHCP");
    while(1); //do nothing if ethernet failed to start
  }
  if (client.connect(server, 80)){
      Serial.println("Connected to server");
      client.println("GET / HTTP/1.1");
      client.println("Host: someserver.com");
      client.println();
  } else {
      Serial.println("Connection to server failed");
  }
}

void loop() {  
  while(client.connected()) {
    if(client.available()) {
      char c = client.read();
      if(c != -1) { // Check if read was successful
        Serial.print(c);  
      } else {
        Serial.println("Read failed");
        break;
      }
    }
  }

  if (!client.connected()) {
    Serial.println("Client disconnected");
    client.stop();
  }
}

HTTP POST request:

#include <UIPEthernet.h>

EthernetClient client;
uint8_t mac[6] = {0x00,0x01,0x02,0x03,0x04,0x05};
char server[] = "www.someserver.com";

void setup() {
  Serial.begin(9600);

  if(Ethernet.begin(mac) == 0){
    Serial.println("Failed to configure Ethernet using DHCP");
    while(1); // do nothing if ethernet failed to start
  }

  String data = preparePostData();
  if (client.connect(server, 80)){
    sendPostRequest(data);
  } else {
    Serial.println("Connection to server failed");
  }
}

void loop() {  
  while(client.connected()) {
    if(client.available()) {
      char c = client.read();
      if(c != -1) {
        Serial.print(c);  
      } else {
        Serial.println("Read failed");
        break;
      }
    }
  }

  if (!client.connected()) {
    Serial.println("Client disconnected");
    client.stop();
  }
}

String preparePostData() {
  String data = "sensor1=";
  data += analogRead(A0);
  data += "&sensor2=";
  data += analogRead(A1);
  return data;
}

void sendPostRequest(String data) {
  Serial.println("Connected to server");
  client.println("POST / HTTP/1.1");
  client.println("Host: someserver.com");
  client.println("Content-Type: application/x-www-form-urlencoded");
  client.print("Content-Length: ");
  client.println(data.length());
  client.println();
  client.println(data);
  client.println();
}

Sketch uses 21864 bytes (67%) of program storage space. Maximum is 32256 bytes.
Global variables use 1480 bytes (72%) of dynamic memory, leaving 568 bytes for local variables. Maximum is 2048 bytes.

Leave a comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.