ArduinoWebsockets icon indicating copy to clipboard operation
ArduinoWebsockets copied to clipboard

How to use HttpClient in conjunction with WebSocketClient?

Open SunboX opened this issue 3 years ago • 3 comments

Hi,

I'm using a Wemos D1 Mini (ESP8266) and I want to access the Slack RTM API.

So I first need to do a Http GET request against https://slack.com/api/rtm.connect with an Authentication (Bearer) header. From that I'm getting the wss:// endpoint I have to connect to.

I. already saw the Secure Example, but I don't know how to do the HTTP GET request first and than free up the connection for the WebSocket Client.

Do you have a small example?

SunboX avatar Jun 08 '21 13:06 SunboX

Can you just do a GET request, parse the result and then, once you have the endpoint, create a new websocket connection?

Regarding how to do GET requests on an esp8266, try googling "esp8266 http example" or something like that... There are many options :)

Gil

gilmaimon avatar Jun 10 '21 20:06 gilmaimon

I dont think both can be used concurrently. One connection has to be closed and then re-opened. Is there any way to make this work concurrently (on different ports) ? i.e. internally it can create 2 ssl certificates and use different certificates for different connections ?

gb-123-git avatar Dec 14 '21 23:12 gb-123-git

I think I'm running into the same issue.

My code is doing a HTTP POST first, using the ESP8266HTTPClient library, afterwards I want to connect to a WebSocket Server via ArduinoWebsockets. The HTTP POST is working fine, the WebSocket does not connect. When I comment the addDevices the WebSocktClient connects fine.

These are the relevant parts I believe. addDevices() is called first, doing the HTTP POST, aftewards websocket.connect(...) is initiated. After this first HTTP POST I don't need the HTTPClient any longer, but apparently a http.end() is not sufficient to close and free the connection.

What am I missing?

Thank You

Part of Setup()

// Backend will prevent duplication - safe to send everytime
addDevices();

websocket.onMessage(onMessageCallback);
websocket.onEvent(onEventsCallback);

websocket.addHeader("Authorization", authHeader);
websocket.connect(getWebsocketConnStr());

Function addDevices()

void addDevices() {
  client.setInsecure(); //disable certificate check
  http.begin(client, config.endpoint);
  http.addHeader("Authorization", authHeader);
  http.addHeader("Content-Type", "application/json");
  int res = http.POST(CONFIG::devices);
  http.end();
  
  DEBUG_SERIAL.print("Add Devices Return Code and Payload: ");
  DEBUG_SERIAL.println(res);
  DEBUG_SERIAL.println(http.getString());
}

Update: Adding a "client.stop()" after the "http.end()" in the addDevices() made it working now. At least for my use-case. But, I found this rather by trial & error, I don't understand the reason. Not sure if someone could provide an explanation for it?

tbabik avatar Aug 24 '22 22:08 tbabik