HTTP 400 Bad Request error on ESP8266

Hello everyone, currently I am working on an ESP8266 to send data to thingspeak but for some reason, I got the 400 Bad Request error, here's my code:

#include<ESP8266WiFi.h>
#include<WiFiClient.h>
#include<ESP8266HTTPClient.h>
#include <ArduinoJson.h>
String URL="http://api.thingspeak.com/update?api_key=ZJAA3PAI45NP0233&field1=";
void setup() {
  Serial.begin(9600);
  WiFi.disconnect();
  delay(2000);
  Serial.print("Start connection");
  WiFi.begin("***","***");
  while((!(WiFi.status()== WL_CONNECTED))){
      delay(200);
      Serial.print("..");
    }
  Serial.println("Connected");
}

void loop() {
  //get the data from Arduino Mega
  if(Serial.available()>0){
    String data = Serial.readStringUntil('\n');
    Serial.println(data);
    sendData(data);
  }
}

void sendData(String data)
{
  WiFiClient client;
  HTTPClient http;
  String newUrl=URL+data;
  Serial.println(newUrl);
  http.begin(client,newUrl);
  int responsecode=http.GET();
  Serial.println(responsecode);
  String payload=http.getString();
  Serial.println(payload);
  http.end();
  delay(5000);
}

and here's the error on the Serial Monitor

30.83

http://api.thingspeak.com/update?api_key=ZJAA3PAI45NP0233&field1=30.83

400
<html>
<head><title>400 Bad Request</title></head>
<body>
<center><h1>400 Bad Request</h1></center>
</body>
</html>

try data.trim(); in loop() after read

1 Like

Oh wow it works! Thank you for helping me

This topic was automatically closed 180 days after the last reply. New replies are no longer allowed.