Arduino Ethernet Shield: Malformed HTTP request to Laravel API

  access-control, arduino, c++, http, laravel

I am developing a simple Access Control system in which we have two mfrc522 readers and ethernet shield attached to Arduino UNO.

The flow is simple: a person scans a personal card and the card number (ID) is immediately transferred to my server (Laravel API) in a form of HTTP POST request.

Most of the time everything works fine, but sometimes I get the following:

Malformed HTTP request

How I initialize connection (this works fine for me):

byte mac[] = { 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED };
IPAddress server(192, 168, 0, 107);
IPAddress ip(192, 168, 0, 102);
IPAddress myDns(192, 168, 0, 1);
EthernetClient client;

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

  SPI.begin();
  Ethernet.init(10);

  digitalWrite(ETHERNET, HIGH); // disable ethernet shield
  // ... Initialize readers ...
  digitalWrite(ETHERNET, LOW); // enable it

  Serial.println("nInitialize Ethernet with DHCP:");
  Ethernet.begin(mac, ip, myDns);
  Serial.print("  IP: ");
  Serial.println(Ethernet.localIP());
  digitalWrite(ETHERNET, HIGH);
  digitalWrite(ssPins[0], LOW);
  digitalWrite(ssPins[1], LOW);
  delay(1000);
}

How I send a request after reading a card:

void sendRequest(MFRC522 rfid, const char* action) {
  // disable all readers and enable ethernet shield
  digitalWrite(ssPins[0], HIGH);
  digitalWrite(ssPins[1], HIGH);
  digitalWrite(ETHERNET, LOW);
  if (client.connect(server, 8000)) {
   Serial.print("Connected to ");
   Serial.println(client.remoteIP());
    
   String PostData = "{"rfid":"" + getUID(rfid.uid.uidByte, rfid.uid.size) + "", "action": "" + action + ""}";
   // Make a HTTP request:
   client.println("POST /api/scan HTTP/1.1");
   client.println("Host: 192.168.0.107:8000");
   client.println("Connection: close");
   client.println("User-Agent: Arduino/1.0");
   client.println("Content-Type: application/json");
   client.print("Content-Length: ");
   client.println(PostData.length());
   client.println("");
   client.println(PostData);
   client.println("");

   client.flush();
   client.stop();
   blinkRed();
  } else {
    Serial.println("connection failed");
    playErrorSound();
  }
  digitalWrite(ETHERNET, HIGH);
  digitalWrite(ssPins[0], LOW);
  digitalWrite(ssPins[1], LOW);
}

String getUID(byte *buffer, byte bufferSize) {
  String out = "";
  for (byte i = 0; i < bufferSize; i++) {
      out += String(buffer[i] < 0x10 ? " 0" : " ") + String(buffer[i], HEX);
  }
  out.toUpperCase();
  out.replace(" ", "");
  return out;
}

What triggers that malformed request? My code or there is something in Laravel framework?

Source: Windows Questions C++

LEAVE A COMMENT