ESP8266 400 BAD REQUEST when connecting to an API using dynamic parameters

Asked

Viewed 11 times

0

I am trying to make an RFID reader using ESP8266 to check via API whether the card/tag has access authorization or not. When I try to dynamically place the card data in my URL it displays a 400 BAD REQUEST error as a response and on my web server. If I take the value and type manually it works.

#include <SPI.h>
#include <MFRC522.h>
#include <ESP8266WiFi.h>
#include <ESP8266HTTPClient.h>
#define SS_PIN 4
#define RST_PIN 5
#define bloqueado 0
#define liberado 2
#define rele 16

const char* ssid = "rede";
const char* password = "senha";
MFRC522 mfrc522(SS_PIN, RST_PIN);
WiFiClient wifiClient;

String dados;
String formata(String str)
{
  int i = 0, j = 0;
  while (str[i])
  {
    if (str[i] != ' ')
          str[j++] = str[i];
    i++;
  }
  str[j] = '\0';

  str[str.length()-1] = '\0';
  return str;
}

void setup() {
  Serial.begin(115200);
  SPI.begin();
  mfrc522.PCD_Init();

  pinMode(liberado, OUTPUT);
  pinMode(bloqueado, OUTPUT);
  pinMode(rele, OUTPUT);

  WiFi.begin(ssid, password);
  while (WiFi.status() != WL_CONNECTED) {
    delay(1000);
    Serial.println("Conectando ao WiFi..");
  }
  Serial.println(WiFi.localIP());
 
  Serial.println("Aproxime o cartao...");
  Serial.println();
}

void loop() {  
  if ( ! mfrc522.PICC_IsNewCardPresent()) {
    return;
  }
  if ( ! mfrc522.PICC_ReadCardSerial()) {
    return;
  }
  
  Serial.print("Tag :");
  String id= "";
  byte letra;
  for (byte i = 0; i < mfrc522.uid.size; i++) 
  {
     Serial.print(mfrc522.uid.uidByte[i] < 0x10 ? " 0" : " ");
     Serial.print(mfrc522.uid.uidByte[i], HEX);
     id.concat(String(mfrc522.uid.uidByte[i] < 0x10 ? " 0" : " "));
     id.concat(String(mfrc522.uid.uidByte[i], HEX));
  }
  Serial.println();
  id.toUpperCase();
  String server = "http://192.168.100.10";
  dados = formata(id.substring(1));
  HTTPClient http;
  String api = String(server + "/api/acesso/libera/" + dados;
  Serial.println(api);
  http.begin(wifiClient,api);
  int httpCode = http.GET();
  if(httpCode > 0) {
      String payload = http.getString();
      Serial.println(payload);
  }}

When I put String api = String(server + "/api/acesso/libera/12345678"; works the right way, but String api = String(server + "/api/acesso/libera/" + dados; it sends the same information to the server (data = 12345678 for example), only from BAD REQUEST.

No answers

Browser other questions tagged

You are not signed in. Login or sign up in order to post.