Appending Headers to WebSocket Connection?

physiii
Posts: 23
Joined: Fri Nov 17, 2017 9:37 pm

Appending Headers to WebSocket Connection?

Postby physiii » Wed Dec 11, 2019 4:53 pm

I need to append some keys to the http header when connecting via websockets.

From the websocket example, I tried:

Code: Select all

    esp_websocket_client_handle_t client = esp_websocket_client_init(&websocket_cfg);
    esp_http_client_set_header(client, "x-device-id", device_id);
    esp_http_client_set_header(client, "x-device-type", "generic");
    esp_http_client_set_header(client, "x-device-token", token);
    esp_websocket_register_events(client, WEBSOCKET_EVENT_ANY, websocket_event_handler, (void *)client);
But esp_http_client_set_header hasn't been declared. Is there a esp_websocket_set_header equivalent?

How do I append keys to the header when connecting with websockets?

RichPiano
Posts: 123
Joined: Mon May 18, 2020 2:51 pm

Re: Appending Headers to WebSocket Connection?

Postby RichPiano » Wed Jan 04, 2023 10:25 am

Yes it is possible. You can use the .headers field when initializing the websocket client for esp_websocket_client_init().

However: There's no comfy function to guarantee that the headers will have the right format, so you have to care for that yourself. The library (currently) just pastes what you give it into the http transport header section as-is.

To make it work you need to make sure that each header string follows the following format:

Code: Select all

<key>: <value>\r\n
e.g

Code: Select all

esp_websocket_client_config_t config = {
            .headers = "X-Client-Info: mylib/2.1.0\r\n",
            // ...
        };
Note the double dot and space ": " as well as the "\r\n" CRLF symbols at the end. Also make sure that your keys and values do not contain whitespace!

Who is online

Users browsing this forum: Bing [Bot] and 136 guests