I've been looking around for a solution, but couldn't manage to find one. I'm looking to send a post request from an ESP8266 on a local API. Here is my code :
#include <ESP8266WiFi.h>
#include <ESP8266HTTPClient.h>
#include <WiFiClient.h>
String ssid = "HUAWEI P30 lite";
String password = "testazerty";
String serverName = "http://192.168.56.1:3030/drink/voltron";
void setup() {
Serial.begin(115200);
WiFi.begin(ssid, password);
Serial.println("Connecting");
while(WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.print(".");
}
Serial.println("");
Serial.print("Connected to WiFi network with IP Address: ");
Serial.println(WiFi.localIP());
}
void loop() {
if(WiFi.status()== WL_CONNECTED){
WiFiClient client;
HTTPClient http;
http.begin(client, serverName);
http.addHeader("Content-Type", "application/json");
int httpResponseCode = http.POST("{\"city\":\"toronto\"}");
Serial.print("HTTP Response code: ");
Serial.println(httpResponseCode);
http.end();
}
}
Both my computer and ESP8266 are connected to my phone network (HUAWEI).
192.168.56.1 is the IP of my computer.
API is running, and I can successfully make the request from postman (see image below).
It always return -1 as http code. I activated debug level HTTP_CLIENT, here is what I have on the serial monitor :
11:07:41.645 -> SDK:2.2.2-dev(38a443e)/Core:3.0.2=30002000/lwIP:STABLE-2_1_2_RELEASE/glue:1.2-48-g7421258/BearSSL:6105635
11:07:41.645 -> fpm close 1
11:07:41.645 -> mode : sta(30:83:98:b1:da:62)
11:07:41.645 -> add if0
11:07:41.645 -> Connecting
11:07:42.160 -> .....scandone
11:07:45.348 -> state: 0 -> 2 (b0)
11:07:45.348 -> .state: 2 -> 3 (0)
11:07:45.441 -> state: 3 -> 5 (10)
11:07:45.441 -> add 0
11:07:45.441 -> aid 6
11:07:45.441 -> cnt
11:07:45.441 ->
11:07:45.441 -> connected with HUAWEI P30 lite, channel 6
11:07:45.441 -> dhcp client start...
11:07:45.864 -> ....ip:192.168.43.88,mask:255.255.255.0,gw:192.168.43.1
11:07:47.870 -> .
11:07:47.870 -> Connected to WiFi network with IP Address: 192.168.43.88
11:07:47.870 -> [HTTP-Client][begin] url: http://192.168.56.1:3030/drink/voltron
11:07:47.870 -> [HTTP-Client][begin] host: 192.168.56.1 port: 3030 url: /drink/voltron
11:07:47.870 -> [HTTP-Client][sendRequest] type: 'POST' redirCount: 0
11:07:53.021 -> [HTTP-Client] failed connect to 192.168.56.1:3030
11:07:53.021 -> [HTTP-Client][returnError] error(-1): connection failed
11:07:53.021 -> HTTP Response code: -1
11:07:53.021 -> [HTTP-Client][end] tcp is closed

localhostis the device itself ... synonymous with 127.0.0.1 ... did you mean to saylocal hostinstead?