I'm trying to connect to a server, both using ESP8266Httpclient and WiFiClient(Secure), but no matter what I do the connection fails.
WiFiClient(Secure) version:
#include <ESP8266WiFi.h>
#include <ESP8266HTTPClient.h>
#include <WiFiClient.h>
const char* ssid = "wifi";
const char* password = "pass";
WiFiClientSecure client;
char server[64] = "website.domain", url[64] = "/path/to/data";
void setup() {
Serial.begin(115200);
WiFi.begin(ssid, password);
while(WiFi.status() != WL_CONNECTED) yield();
}
void loop() {
if (!client.connect(server, 443)) Serial.println("Connection failed");
else {
Serial.println("Connection success");
}
}
This always prints "Connection failed", no matter what combination I try: I tried connecting with port 80 and 443, using WiFiClient and WiFiClientSecure, adding and removing "http(s)://" from the server, they all return "Connection failed".
ESP8266Httpclient version:
#include <ESP8266WiFi.h>
#include <ESP8266HTTPClient.h>
#ifndef STASSID
#define STASSID "wifi"
#define STAPSK "pass"
#endif
void setup() {
Serial.begin(115200);
WiFi.begin(STASSID, STAPSK);
while (WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.print(".");
}
Serial.println("");
Serial.print("Connected! IP address: ");
Serial.println(WiFi.localIP());
}
void loop() {
// wait for WiFi connection
if ((WiFi.status() == WL_CONNECTED)) {
WiFiClientSecure client;
HTTPClient http;
Serial.print("[HTTP] begin...\n");
http.begin(client, "https://website.domain/path/to/data", 443);
http.addHeader("Content-Type", "application/json");
Serial.print("[HTTP] POST...\n");
int httpCode = http.POST("{\"points\":[{\"lat\":mylat,\"lng\":mylng}],\"fuelType\":\"1-x\",\"priceOrder\":\"asc\"}");
if (httpCode > 0) {
Serial.printf("[HTTP] POST... code: %d\n", httpCode);
Serial.println("Redirect location: " + http.getLocation());
//if (httpCode == HTTP_CODE_OK) {
const String& payload = http.getString();
Serial.println("received payload:\n<<");
Serial.println(payload);
Serial.println(">>");
//}
} else Serial.printf("[HTTP] POST... failed, error: %s\n", http.errorToString(httpCode).c_str());
http.end();
}
delay(10000);
}
This snippet behaves differently: if I connect to http://website.domain/path/to/data I get HTTP code 301 (moved permanently), which returns location https://website.domain/path/to/data.
If I then change the endpoint to https://website.domain/path/to/data, it returns error -1 (connection failed). I tried every combination in this code as well: port 80 and 443, with and without http(s)://, WiFiClient and WiFiClientSecure, nothing worked. I might be overlooking something very simple, or this might not be possible at all.
Thanks to Juraj for the suggestion to put client.setInsecure(). I thought I'd already done that, but you actually need to call it after you create the client and before you pass it to httpclient. That way it'll actually be set as insecure. Thanks again Juraj.
Related
I am new to Arduino and I am not so familiar with it. I am not sure why the client cannot connect to the server and I have been looking at it for hours. Any solution to this would be a great help.
So I successfully establish a server with the code below. But...
// server.ino
#include <ESP8266WiFi.h>
#include <ESP8266WebServer.h>
const char* ssid = "WifiName"; // Wifie name
const char* password = "WifiPassword"; // Wifi password
float sensor_value = 0.0;
String Website;
ESP8266WebServer server(80);
void setup(){
Serial.begin(115200);
WiFi.mode(WIFI_AP);
Serial.print("Connecting to ");
Serial.println(ssid);
WiFi.begin(ssid, password);
while(WiFi.status()!=WL_CONNECTED){
Serial.print(".");
delay(500);
}
Serial.println("Server started at port 80.");
Serial.println("WiFi connected.");
Serial.println("IP address: ");
Serial.print("URL=http://");
Serial.println(WiFi.localIP());
server.on("/", handleIndex); //use the top root path report last sensor value
server.on("/update",handleUpdate); // use this route to update sensor value
server.begin();
}
void loop(){
server.handleClient();
}
void handleIndex(){
Website = "<html><body onload ='process()'><div id='div1'>"+ String(sensor_value) +"</div></body></html>";
server.send(200," text/html",Website);
}
void handleUpdate(){
sensor_value = server.arg("value").toFloat();
Serial.println(sensor_value);
server.send(200,"text/plain","Updated");
}
I try to connect a client to the server so it could send data to the server, but a connection between the client and the server cannot be established and I don't know why. I check the IP address and it is all correct I just don't get why the client fails to connect to the server
#include <ESP8266WiFi.h>
#include <ESP8266WebServer.h>
#include <HX711.h>
#include "Wire.h"
#define DOUT D5
#define CLK D6
HX711 scale;
const char* ssid = "WifiName";
const char* password = "Wifipassowrd";
float calibration_factor = 107095;
float val_Weight;
const char* host = "192.168.0.167"; // Server host IP.
const int port = 80;
WiFiClient client;
void setup() {
Serial.begin(115200); //set baud rate
Serial.println("Connecting to ");
Serial.println(ssid);
WiFi.begin(ssid, password);
while (WiFi.status() != WL_CONNECTED)
{
delay(500);//millisecond
Serial.print(".");
}
Serial.println("");
Serial.println("WiFi connected & connect to client");
}
void loop() {
//connect to the server and send the data as URL parameter
if(client.connect(host, port)){
String url = "update?value=";
url+=String(25.0);
client.print(String("GET /") + url + "HTTP/1.1\r\n" + "Host: " + host + "\r\n" +
"Connection: close\r\n\r\n");
delay(10);
Serial.println("Response: ");
while(client.available()){
String line = client.readStringUntil('\r');
Serial.print(line);
}
}else{
Serial.println("fail");
}
}
Any help would be great thanks!!!
Check the passwords, you have a typo.
const char* password = "Wifipassowrd";
Why I am unable to send get request. It always response 400.The URL are okay there is no problem in it. Actually I need to send data using get request. I have tried my best to find the solution but I didn't get any idea about it. Please anyone can help me with the code
#include <ESP8266WiFi.h>
#include <ESP8266HTTPClient.h>//this header is used to send get request and see response
#include <WiFiClient.h>
const char* ssid = "myssid";
const char* password = "mypswd";
String host_url="https://api-test.technofield.net";
String url1="/api/data?token=TEST_TOKEN_123&data=";
int httpPort=80;
void setup() {
Serial.begin(9600);
WiFi.begin(ssid, password); //Connect to my WiFi router
Serial.println("");
Serial.print("Connecting"); //initiall step just displaying connecting
// Wait for connection
while (WiFi.status() != WL_CONNECTED) { //the llop wiil execute till wifi is not connected
delay(500);
Serial.print(".");
}
//If connection successful show IP address in serial monitor
Serial.println("");
Serial.print("Connected to ");
Serial.println(ssid);// connected to given ssid
Serial.print("IP address: ");
Serial.println(WiFi.localIP()); //IP address assigned to your ESP
}
void loop(){
if(WiFi.status()==WL_CONNECTED){ //we will perform action if wifi is connected
HTTPClient http; //intialize object of HTTPclient which is importent
String data="Sunil Kumar Yadav";
//String token="TEST_TOKEN_123";
url1=url1+data;
//full APi url is created you can manipulate those above data and token vaiable.
http.begin(host_url,httpPort,url1);//specify the request,begin the request
int httpCode=http.GET(); //Send the request
// if (httpCode>0){ //lets see the response from server
// String payload = http.getString();//store response on payload variable
// Serial.print("==============");//just for seperating the wifi connection status and server response
// Serial.println(payload);//print the response payload
// }
Serial.print(httpCode);
http.end();//if there is begin there will be end ,it will Close the connection
}
delay(500); //send the request in every 2sec, you can change it according to your need
//you can also specify the time so that it will be easy to identify on which time data is send
}
Following is the output:
301
==============<html>
<head><title>301 Moved Permanently</title></head>
<body>
<center><h1>301 Moved Permanently</h1></center>
<hr><center>nginx</center>
</body>
</html>
I dont know how to solve this.
There's one (of several) example how to do this with HTTPs here: https://github.com/esp8266/Arduino/blob/master/libraries/ESP8266HTTPClient/examples/BasicHttpsClient/BasicHttpsClient.ino
#include <ESP8266WiFi.h>
#include <ESP8266HTTPClient.h>
#include <WiFiClientSecure.h>
const char* ssid = "myssid";
const char* password = "mypswd";
String url = "https://api-test.technofield.net/api/data?token=TEST_TOKEN_123&data=";
void setup() {
Serial.begin(115200);
WiFi.begin(ssid, password);
Serial.println("");
Serial.print("Connecting");
while (WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.print(".");
}
Serial.println("");
Serial.print("Connected to ");
Serial.println(ssid);
Serial.print("IP address: ");
Serial.println(WiFi.localIP());
}
void loop() {
if (WiFi.status() == WL_CONNECTED) {
WiFiClientSecure client;
client.setInsecure();
HTTPClient https;
String data = "Sunil%20Kumar%20Yadav";
String fullUrl = url + data;
Serial.println("Requesting " + fullUrl);
if (https.begin(client, fullUrl)) {
int httpCode = https.GET();
Serial.println("============== Response code: " + String(httpCode));
if (httpCode > 0) {
Serial.println(https.getString());
}
https.end();
} else {
Serial.printf("[HTTPS] Unable to connect\n");
}
}
delay(5000);
}
import WiFiClientSecure.h
note how I set client.setInsecure(); which you shouldn't in your real code, rather us the root certificate of your end point as shown here https://github.com/esp8266/Arduino/blob/master/libraries/ESP8266WiFi/examples/HTTPSRequest/HTTPSRequest.ino#L29
you should URL-encode the data parameter like so String data = "Sunil%20Kumar%20Yadav"
Derived from the following code.
I uploaded that code to my ESP8266 and it's all good and okay when I communicate with it with my laptop while my laptop is connected to my network with a LAN cable.
The problem is: when I try to communicate with the ESP with my laptop or phone over Wi-Fi I get ERR_CONNECTION_REFUSED though they rarely work and communicate. I tried another phone another router, and did a factory reset to my router, and all the same.
I know that there is an option in the router that is called AP Isolation and it's been checked and it's disabled.
My question is: What could possibly be the reason for this error ERR_CONNECTION_REFUSED when I communicate with ESP8266 with that code?
If someone could help me I would be pleased as I am stuck in this situation.
The ESP code (same as the link):
#include <ESP8266WiFi.h>
const char* ssid = "*****";
const char* password = "*******";
WiFiServer server(80);
void setup() {
Serial.begin(115200);
Serial.println();
Serial.printf("Connecting to %s ", ssid);
WiFi.begin(ssid, password);
while (WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.print(".");
}
Serial.println(" connected");
server.begin();
Serial.printf("Web server started, open %s in a web browser\n", WiFi.localIP().toString().c_str());
}
// prepare a web page to be send to a client (web browser)
// the connection will be closed after completion of the response
// the page will be refreshed automatically every 5 sec
String prepareHtmlPage() {
String htmlPage = String("HTTP/1.1 200 OK\r\n") +
"Content-Type: text/html\r\n" +
"Connection: close\r\n" +
"Refresh: 5\r\n" + "\r\n" +
"<!DOCTYPE HTML>" + "<html>" +
"Analog input: " + String(analogRead(A0)) +
"</html>" + "\r\n";
return htmlPage;
}
void loop() {
WiFiClient client = server.available();
// wait for a client (web browser) to connect
if (client) {
Serial.println("\n[Client connected]");
while (client.connected()) {
// read line by line what the client (web browser) is requesting
if (client.available()) {
String line = client.readStringUntil('\r');
Serial.print(line);
// wait for end of client's request, that is marked with an empty line
if (line.length() == 1 && line[0] == '\n') {
client.println(prepareHtmlPage());
break;
}
}
}
delay(1); // give the web browser time to receive the data
// close the connection:
client.stop();
Serial.println("[Client disconnected]");
}
}
I hope its not too late and it helps someone in need.
You need to do 2 things
Before WiFi.begin(), you need to add
WiFi.mode(WIFI_STA);
Second, you need to
#include <ESP8266mDNS.h>
in setup()
if (MDNS.begin("esp8266")) {
Serial.println("MDNS responder started");
}
and in loop()
MDNS.update();
Lastly, do not forget to add the following in every server response. Else, you will hit CORS error.
server.sendHeader("Access-Control-Allow-Origin", "*");
Please dont forget to add supporting libraries. Let me know if it works. Demo code would look like the below
#include <ESP8266WiFi.h>
#include <WiFiClient.h>
#include <ESP8266WebServer.h>
#include <ESP8266mDNS.h>
const char* ssid = "<your SSID>";
const char* password = "<your WIFI Password>>";
int serverPort = 80;
int boardBaud = 115200;
ESP8266WebServer server(serverPort);
void handleRoot() {
server.sendHeader("Access-Control-Allow-Origin", "*");
server.send(200, "text/html", "<h1>Hello World</h1>");
}
void handleNotFound() {
if (server.method() == HTTP_OPTIONS)
{
server.sendHeader("Access-Control-Allow-Origin", "*");
server.sendHeader("Access-Control-Max-Age", "10000");
server.sendHeader("Access-Control-Allow-Methods", "PUT,POST,GET,OPTIONS");
server.sendHeader("Access-Control-Allow-Headers", "*");
server.send(204);
}
else
{
server.send(404, "text/plain", "Error");
}
}
void setup(void) {
Serial.begin(boardBaud);
WiFi.mode(WIFI_STA);
WiFi.begin(ssid, password);
// Wait for connection
while (WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.print(".");
}
Serial.println("");
Serial.print("IP address: ");
Serial.println(WiFi.localIP());
if (MDNS.begin("esp8266")) {
Serial.println("MDNS responder started");
}
server.on("/", handleRoot);
server.onNotFound(handleNotFound);
server.begin();
Serial.println("HTTP server started");
}
void loop(void) {
server.handleClient();
MDNS.update();
}
I tried to Run this code but the connection fails and HTTPCode returns -1 , I'm using WIFI manager and it works sucessfully connected to the network
the link is worked successfully on POSTman and data posted in Database
Hi All, I tried to Run this code but the connection fails and HTTPCode returns -1 , I'm using WIFI manager and it works sucessfully connected to the network
the link is worked successfully on POSTman and data posted in Database
#include <OneWire.h>
#include <DallasTemperature.h>
#include <ESP8266WiFi.h>
#include <WiFiManager.h>
#include <ESP8266HTTPClient.h>
#include <Wire.h>
IPAddress staticIP750_100(192,168,1,16);
IPAddress gateway750_100(192,168,1,1);
IPAddress subnet750_100(255,255,255,0);
HTTPClient http;
#define ONE_WIRE_BUS 2 // DS18B20 on NodeMCU pin D4
OneWire oneWire(ONE_WIRE_BUS);
DallasTemperature DS18B20(&oneWire);
float temp_0;
const char* host = "http://mysite2020.info";
void setup()
{
Serial.begin(115200);
WiFiManager wifimanger ;
DS18B20.begin();
Wire.begin(D2, D1)
readTemp();
WiFi.mode(WIFI_STA);
wifimanger.autoConnect("Inlet Device","12345");
while ((!(WiFi.status() == WL_CONNECTED))){
delay(300);
Serial.println("...");
}
Serial.println("WiFi connected");
WiFi.config(staticIP750_100, gateway750_100, subnet750_100);
WiFi.hostname("Inlet Device") ;
delay(3000);
Serial.println("Welcome To Device No : 1");
Serial.println("IP address: ");
Serial.println(WiFi.localIP());
Serial.println("Your Gateway is : ");
Serial.println((WiFi.gatewayIP().toString().c_str()));
Serial.println("Your Hostname is : ");
Serial.println((WiFi.hostname()));
delay(3000);
Serial.println("Welcome to my Project!");
delay(3000);
}
void loop() {
Serial.println(host); // Use WiFiClient class to create TCP connections
WiFiClient client;
const int httpPort = 80;
if (!client.connect(host, httpPort))
{
Serial.println("connection failed");
return;
}
Serial.print("Requesting URL: ");
sendtemp ();
}
void sendtemp ()
{
temp_0=23.26;
String url = "http://mysite2020.info/Api/insert_mssqlserver.php?Reading=" + String(temp_0);
Serial.println(url);
http.begin(url);
http.addHeader("Content-Type", "application/x-www-form-urlencoded");
auto httpCode = http.GET();
Serial.println(httpCode); //Print HTTP return code
String payload = http.getString();
Serial.println(payload); //Print request response payload
http.end(); //Close connection Serial.println();
Serial.println("closing connection");
delay(500);
}
I have made a simple Node.js local server to receive POST requests from ESP32 and put it in a database. The server is working fine as I tested it using postman. The server is listening to port 127.0.0.1:3000. My problem is that client.connect(host, port) always returns false. I cannot connect to the client in order to make POST requests.
#include "Arduino.h"
#include "Arduino.h"
#include "WiFi.h"
WiFiClient client;
const IPAddress server(192,168,1,10);
const int httpPort = 3000;
const char* ssid = "******";
const char* password = "********";
void setup() {
Serial.begin(115200);
Serial.println();
Serial.println("Booted");
Serial.println("Connecting to Wi-Fi");
WiFi.begin (ssid, password);
WiFi.mode(WIFI_STA);
while (WiFi.status() != WL_CONNECTED) {
Serial.print(".");
delay(500);
yield();
}
Serial.println("WiFi connected");
if (client.connect(server,httpPort )) {
Serial.println("Client Connected");
} else {
Serial.println("No Connection");
}
void loop() {
}
The solution was to make the server listen to 0.0.0.0, which includes all IPv4 addresses on the server machine, instead of the loopback IP address 127.0.0.1